コード例 #1
0
        // Zipファイルを解凍する
        private async void btnUnzip_Click(object sender, RoutedEventArgs e)
        {
            // ZipファイルへのUriオブジェクトを生成する
            var url = new Uri("ms-appx:///Assets/piyo.zip");

            // アプリケーション パッケージ内に格納されたZIPファイルのストリームを取得する
            var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(url);

            // ZipファイルのストリームからZipArchiveクラスのオブジェクトを生成する
            using (var randomStrm = await file.OpenReadAsync())            
            using (var strm = randomStrm.AsStream())
            using (var archive = new System.IO.Compression.ZipArchive(strm))
            {
                // Zipファイルに含まれているファイルの一覧を表示する
                foreach (var entry in archive.Entries)
                {
                    System.Diagnostics.Debug.WriteLine(entry.FullName);
                }

                // Zipファイルに含まれているファイルをアプリケーション ローカル フォルダーへ保存する
                foreach (var entry in archive.Entries)
                {
                    // Zipファイルから特定のファイルを解凍して、アプリケーションローカルへ書き出す
                    var fileA = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(entry.FullName);
                    using (var unzipStrm = entry.Open())
                    using (var writer = await fileA.OpenStreamForWriteAsync())
                    {
                        await unzipStrm.CopyToAsync(writer);
                        await writer.FlushAsync();
                    }
                }
            }
        }
コード例 #2
0
 public static System.IO.Compression.ZipArchiveEntry CreateEntryFromFile(this System.IO.Compression.ZipArchive destination, string sourceFileName, string entryName, System.IO.Compression.CompressionLevel compressionLevel)
 {
     return(default(System.IO.Compression.ZipArchiveEntry));
 }
コード例 #3
0
ファイル: App.Bot.cs プロジェクト: sUmcont/Optimat.EO
        void ListeAutomaatZuusctandDiferenzScritScraibeNaacZipArchiveNaacVerzaicnisBerictNaacDataiMitNaame(
            IEnumerable <WertZuZaitpunktStruct <Bib3.RefNezDiferenz.SictZuNezSictDiferenzScritAbbild> > ListeAutomaatZuusctand,
            string ZiilDataiNaame)
        {
            var ZipArchiveStream = new MemoryStream();

            var SerializeSettings = new JsonSerializerSettings();

            SerializeSettings.DefaultValueHandling  = DefaultValueHandling.IgnoreAndPopulate;
            SerializeSettings.TypeNameHandling      = TypeNameHandling.Auto;
            SerializeSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;

            /*
             * 2014.04.05
             *
             * Cannot preserve reference to array or readonly list, or list created from a non-default constructor: Optimat.SictWertMitZait`1[Optimat.Anwendung.RefNezDiferenz.SictRefNezDiferenzScritSictJson][]. Path 'MengeAutomaatZuusctandDiferenzScritMitZait.$values', line 1, position 78.
             *
             * SerializeSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;
             * */

            using (var ZipArchive = new System.IO.Compression.ZipArchive(ZipArchiveStream, System.IO.Compression.ZipArchiveMode.Create, true))
            {
                if (null != ListeAutomaatZuusctand)
                {
                    foreach (var AutomaatZuusctandZuBericte in ListeAutomaatZuusctand)
                    {
                        if (null == AutomaatZuusctandZuBericte.Wert)
                        {
                            continue;
                        }

                        var AutomaatZuusctandZuBericteZaitSictKalenderString =
                            Bib3.Glob.SictwaiseKalenderString(Bib3.Glob.SictDateTimeVonStopwatchZaitMili(AutomaatZuusctandZuBericte.Zait), ".", 3);

                        var EntryNaame = "[ZAK=" + AutomaatZuusctandZuBericteZaitSictKalenderString + "]";

                        string EntrySictString = null;

                        try
                        {
                            var EntrySctrukt = SictVonAnwendungBerict.KonstruktFürAutomaatZuusctandDiferenzScrit(
                                AutomaatZuusctandZuBericte);

                            EntrySictString = JsonConvert.SerializeObject(EntrySctrukt, Formatting.None, SerializeSettings);
                        }
                        catch (System.Exception Exception)
                        {
                            EntrySictString = Optimat.Glob.ExceptionSictString(Exception);
                        }

                        var EntrySictUTF8 = Encoding.UTF8.GetBytes(EntrySictString);

                        var Entry = ZipArchive.CreateEntry(EntryNaame);

                        var EntryStream = Entry.Open();

                        EntryStream.Write(EntrySictUTF8, 0, EntrySictUTF8.Length);

                        EntryStream.Close();
                    }
                }
            }

            ZipArchiveStream.Seek(0, SeekOrigin.Begin);

            var ZipArchiveListeSegment = Optimat.Glob.VonStreamLeeseNaacListeArray(ZipArchiveStream, 0x10000);

            ZipArchiveStream.Dispose();

            ScraibeNaacDataiInSizungBerictVerzaicnisPfaad(ZiilDataiNaame, ZipArchiveListeSegment);
        }
コード例 #4
0
ファイル: RIRBase.cs プロジェクト: KDERazorback/nro_geoip
        public virtual FileInfo[] DecompressArchive(string rootDir, FileInfo archive, RirCompressionType type)
        {
            if (archive == null)
            {
                throw new ArgumentNullException(nameof(archive));
            }

            if (!archive.Exists || archive.Length < 1)
            {
                throw new IOException("The archive is either invalid or missing.");
            }

            DirectoryInfo targetDir = new DirectoryInfo(Path.Combine(CacheDirectory, rootDir));

            if (targetDir.Exists)
            {
                targetDir.Delete(true);
            }
            targetDir.Refresh();
            if (!targetDir.Exists)
            {
                targetDir.Create();
            }
            targetDir.Refresh();

            if (Settings.Current.VerboseOutput)
            {
                Log.WriteLine("Decompressing archive %@ as type %@...", LogLevel.Debug, archive.Name, type.ToString());
            }

            List <FileInfo> outputFiles = new List <FileInfo>();

            using (FileStream archiveStream = new FileStream(archive.FullName, FileMode.Open, FileAccess.Read, FileShare.None))
            {
                Stream decompressor = null;
                System.IO.Compression.ZipArchive zipArchive = null;
                switch (type)
                {
                case RirCompressionType.None:
                    decompressor = archiveStream;
                    break;

                case RirCompressionType.Gzip:
                    decompressor = new System.IO.Compression.GZipStream(archiveStream, System.IO.Compression.CompressionMode.Decompress, true);
                    break;

                case RirCompressionType.Zip:
                    zipArchive = new System.IO.Compression.ZipArchive(archiveStream, System.IO.Compression.ZipArchiveMode.Read, true);
                    break;

                case RirCompressionType.Deflate:
                    decompressor = new System.IO.Compression.DeflateStream(archiveStream, System.IO.Compression.CompressionMode.Decompress, true);
                    break;

                default:
                    throw new InvalidOperationException("Internal Error. Unknown compression algorithm.");
                }

                if (zipArchive != null)
                {
                    // Specific case for Zip archives
                    Log.WriteLine("Found %@ entries inside the Zip archive. Decompressing...", LogLevel.Debug, zipArchive.Entries.Count.ToString("N0"));
                    foreach (System.IO.Compression.ZipArchiveEntry entry in zipArchive.Entries)
                    {
                        Log.WriteLine("Decompressing file %@  %@ bytes...", LogLevel.Debug, entry.Name, entry.Length.ToString("N0"));
                        FileInfo targetFile = new FileInfo(Path.Combine(targetDir.FullName, entry.FullName));

                        if (!targetFile.Directory.Exists)
                        {
                            targetFile.Directory.Create();
                        }

                        using (Stream decompressedStream = targetFile.Open(FileMode.Open))
                            using (FileStream fsout = new FileStream(targetFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None))
                                decompressedStream.CopyTo(fsout);

                        targetFile.Refresh();
                        outputFiles.Add(targetFile);
                    }

                    Log.WriteLine("Archive decompression completed.", LogLevel.Debug);
                }
                else
                {
                    // Common case for single-file compressed streams
                    FileInfo targetFile = new FileInfo(Path.Combine(targetDir.FullName, Path.GetFileNameWithoutExtension(archive.Name)));

                    if (!targetFile.Directory.Exists)
                    {
                        targetFile.Directory.Create();
                    }

                    using (FileStream fsout = new FileStream(targetFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        Log.WriteLine("Decompressing file %@...", LogLevel.Debug, targetFile.Name);
                        decompressor.CopyTo(fsout);
                        Log.WriteLine("Done. %@ bytes written.", LogLevel.Debug, fsout.Position.ToString("N0"));
                    }

                    targetFile.Refresh();
                    outputFiles.Add(targetFile);
                }
            }

            return(outputFiles.ToArray());
        }
コード例 #5
0
ファイル: Update.cs プロジェクト: AlexS4v/ORB4
        public async Task ExtractFiles()
        {
            try
            {
                CancellationTokenSource.Token.ThrowIfCancellationRequested();

                if (Path[Path.Length - 1] != '\\')
                {
                    Path += "\\";
                }

                System.IO.Compression.ZipArchive archive = System.IO.Compression.ZipFile.Open(_tempFile, System.IO.Compression.ZipArchiveMode.Read);

                AddRollbackOperation(() =>
                {
                    archive.Dispose();
                });

                for (int i = 0; i < archive.Entries.Count; i++)
                {
                    string filename = string.Empty;
                    string dir      = string.Empty;
                    string rawDir   = string.Empty;

                    if (archive.Entries[i].FullName.Contains("/"))
                    {
                        bool gotSymbol = false;

                        for (int k = archive.Entries[i].FullName.Length - 1; k > -1; k--)
                        {
                            if (archive.Entries[i].FullName[k] == '/' && !gotSymbol)
                            {
                                dir      += '/';
                                filename  = Utils.Reverse(filename);
                                gotSymbol = true;
                                continue;
                            }

                            if (!gotSymbol)
                            {
                                filename += archive.Entries[i].FullName[k];
                            }
                            else
                            {
                                dir += archive.Entries[i].FullName[k];
                            }
                        }

                        if (dir != string.Empty)
                        {
                            dir = Utils.Reverse(dir);
                        }

                        rawDir = dir;

                        if (!System.IO.Directory.Exists(Path + dir))
                        {
                            System.IO.Directory.CreateDirectory(Path + dir);
                            _installedComponents.Add(Path + dir.Replace("/", "\\"), 255);

                            dir = System.IO.Path.Combine(Path + dir);

                            AddRollbackOperation(() =>
                            {
                                if (System.IO.Directory.Exists(dir))
                                {
                                    System.IO.Directory.Delete(dir, true);
                                }
                            });
                        }
                        else
                        {
                            dir = System.IO.Path.Combine(Path + dir);
                        }
                    }
                    else
                    {
                        filename = archive.Entries[i].FullName;
                        dir      = Path;
                    }

                    if (filename != string.Empty)
                    {
                        if (_filesToUpdate.Any(x => rawDir + x.ToLower() == archive.Entries[i].FullName.ToLower()))
                        {
                            if (System.IO.File.Exists(dir + filename))
                            {
                                string temp = System.IO.Path.GetTempFileName();

                                System.IO.File.Delete(temp);

                                System.IO.File.Copy(dir + filename, temp);
                                _backupFiles.Add(archive.Entries[i].FullName, temp);

                                AddRollbackOperation(() =>
                                {
                                    System.IO.File.Delete(dir + filename);
                                    System.IO.File.Copy(temp, dir + filename);
                                    System.IO.File.Delete(temp);
                                });
                            }

                            var fileStream = System.IO.File.Create(dir + filename);

                            Stream stream = archive.Entries[i].Open();
                            await stream.CopyToAsync(fileStream);

                            stream.Close();
                            fileStream.Close();

                            _installedComponents.Add((dir + filename).Replace("/", "\\"), 0);
                        }
                    }

                    Percentage = _previousPercentage + (int)((double)(i + 1) / (double)archive.Entries.Count * 2500);
                }

                System.IO.File.WriteAllText($"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\\ORB\\Version", _version, System.Text.Encoding.ASCII);

                AddRollbackOperation(() => System.IO.File.Delete($"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\\ORB\\Version"));

                Percentage = _previousPercentage + 2500;

                CancellationTokenSource.Token.ThrowIfCancellationRequested();
                archive.Dispose();
            }
            catch (System.OperationCanceledException)
            {
                await OperationsRollback();

                Environment.Exit(0);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show("Oops, that's so embarrassing... An error occurred: " + e.ToString(), "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                CurrentDescription = "Operations rollback...";
                await OperationsRollback();

                Environment.Exit(e.HResult);
            }
        }
コード例 #6
0
        public async Task CreateAsync(IEnumerable <TemporaryExposureKeyModel> keys)
        {
            var current = keys;

            while (current.Any())
            {
                var exportKeyModels = current.Take(MaxKeysPerFile).ToImmutableArray();
                var exportKeys      = exportKeyModels.Select(_ => _.ToKey());
                current = current.Skip(MaxKeysPerFile);

                var exportModel = await TekExportRepository.CreateAsync();

                exportModel.BatchSize      = exportKeyModels.Length;
                exportModel.StartTimestamp = exportKeyModels.Min(_ => _.Timestamp);
                exportModel.EndTimestamp   = exportKeyModels.Max(_ => _.Timestamp);
                exportModel.Region         = Region;

                var bin = new TemporaryExposureKeyExport();
                bin.Keys.AddRange(exportKeys);
                bin.BatchNum       = exportModel.BatchNum;
                bin.BatchSize      = exportModel.BatchSize;
                bin.Region         = exportModel.Region;
                bin.StartTimestamp = exportModel.StartTimestamp;
                bin.EndTimestamp   = exportModel.EndTimestamp;
                bin.SignatureInfos.Add(SigInfo);

                var sig = new TEKSignatureList();

                using var binStream = new MemoryStream();
                bin.WriteTo(binStream);
                await binStream.FlushAsync();

                binStream.Seek(0, SeekOrigin.Begin);
                var signature = CreateSignature(binStream, bin.BatchNum, bin.BatchSize);
                sig.Signatures.Add(signature);
                binStream.Seek(0, SeekOrigin.Begin);

                using var s = new MemoryStream();
                using (var z = new System.IO.Compression.ZipArchive(s))
                {
                    var binEntry = z.CreateEntry(ExportBinFileName);
                    using (var binFile = binEntry.Open())
                    {
                        await binStream.CopyToAsync(binFile);

                        await binFile.FlushAsync();
                    }

                    var sigEntry = z.CreateEntry(ExportSigFileName);
                    using (var sigFile = sigEntry.Open())
                    {
                        sig.WriteTo(sigFile);
                        await sigFile.FlushAsync();
                    }
                }
                s.Seek(0, SeekOrigin.Begin);

                await WriteToBlobAsync(s, exportModel, bin, sig);

                await TekExportRepository.UpdateAsync(exportModel);
            }
        }
コード例 #7
0
        public void Berecne(
            out System.Exception LaadeDataiException,
            int?VerwertungMengeDataiAnzaalScranke)
        {
            LaadeDataiException = null;

            var BerictVerzaicnisPfaad = this.BerictHauptVerzaicnisPfaad;
            var BerictWindowClientRasterVerzaicnisPfaad = this.BerictWindowClientRasterVerzaicnisPfaad;

            bool BerecneScritLezteListeDataiEnde = false;

            try
            {
                try
                {
                    if (!(VerwertungMengeDataiAnzaalScranke <= 0) &&
                        null != BerictVerzaicnisPfaad)
                    {
                        /*
                         * Ermitelt ob noie Dataie vorhande und verwertet diise gegeebenenfals.
                         * */

                        var BerictVerzaicnis = new DirectoryInfo(BerictVerzaicnisPfaad);

                        var MengeFile = BerictVerzaicnis.GetFiles();

                        int VerwertungMengeDataiAnzaalBisher = 0;

                        foreach (var File in MengeFile)
                        {
                            if (VerwertungMengeDataiAnzaalScranke <= VerwertungMengeDataiAnzaalBisher)
                            {
                                break;
                            }

                            var DataiPfaad = File.FullName;

                            var DataiNaame = System.IO.Path.GetFileName(DataiPfaad);

                            var DataiBeraitsVerwertet = Optimat.Glob.TAD(DictZuDataiPfaadDataiBeraitsVerwertet, DataiPfaad);

                            if (MengeFile.LastOrDefault() == File)
                            {
                                BerecneScritLezteListeDataiEnde = true;
                            }

                            if (DataiBeraitsVerwertet)
                            {
                                continue;
                            }

                            DictZuDataiPfaadDataiBeraitsVerwertet[DataiPfaad] = true;

                            var DataiInhalt = InhaltAusDataiMitPfaad(DataiPfaad);

                            if (null == DataiInhalt)
                            {
                                continue;
                            }

                            var NaacDekompresListeDataiNaameUndInhalt = new List <KeyValuePair <string, byte[]> >();

                            {
                                var ZipIdentString = "PK";

                                var ZipIdentListeOktet = Encoding.ASCII.GetBytes(ZipIdentString);

                                var AnnaameDataiIstZipArciiv = Bib3.Glob.SequenceEqualPerObjectEquals(ZipIdentListeOktet, DataiInhalt.Take(ZipIdentListeOktet.Length));

                                if (AnnaameDataiIstZipArciiv)
                                {
                                    using (var ZipArchive = new System.IO.Compression.ZipArchive(new MemoryStream(DataiInhalt), System.IO.Compression.ZipArchiveMode.Read))
                                    {
                                        var MengeEntry = ZipArchive.Entries;

                                        if (null != MengeEntry)
                                        {
                                            foreach (var Entry in MengeEntry)
                                            {
                                                var EntryIdent = new SictBerictDataiIdentInDsInfo(DataiPfaad, Entry.FullName);

                                                using (var EntryStream = Entry.Open())
                                                {
                                                    var EntryInhalt = Optimat.Glob.AusStreamLeese(EntryStream);

                                                    NaacDekompresListeDataiNaameUndInhalt.Add(new KeyValuePair <string, byte[]>(Entry.FullName, EntryInhalt));
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    NaacDekompresListeDataiNaameUndInhalt.Add(new KeyValuePair <string, byte[]>(null, DataiInhalt));
                                }
                            }

                            foreach (var NaacDekompresDataiNaameUndInhalt in NaacDekompresListeDataiNaameUndInhalt)
                            {
                                var NaacDekompresDataiInhalt = NaacDekompresDataiNaameUndInhalt.Value;

                                if (null == NaacDekompresDataiInhalt)
                                {
                                    continue;
                                }

                                var PfaadNaacBerictElement = new SictBerictDataiIdentInDsInfo(DataiPfaad, NaacDekompresDataiNaameUndInhalt.Key);

                                AingangBerictElement(PfaadNaacBerictElement, NaacDekompresDataiInhalt);
                            }

                            ++VerwertungMengeDataiAnzaalBisher;
                        }
                    }
                }
                catch (System.Exception Exception)
                {
                    LaadeDataiException = Exception;
                }

                {
                    //	Scatescpaicer Scranke apliziire.

                    DictZuDataiPfaadDataiInhalt.BescrankeEntferneLängerNitVerwendete(
                        null,
                        ScatenscpaicerBerictDataiKapazitäätScranke,
                        (DataiInhalt) => 1000 + ((null == DataiInhalt) ? 0 : DataiInhalt.LongLength));
                }

                {
                    ListeDataiAnzaal = DictZuDataiPfaadDataiBeraitsVerwertet.Count;
                }

                /*
                 * 2014.06.01
                 *
                 * KopiiAktualisiire();
                 * */
            }
            finally
            {
                this.BerecneScritLezteListeDataiEnde = BerecneScritLezteListeDataiEnde;
            }
        }
コード例 #8
0
 public static System.IO.Compression.ZipArchiveEntry GetEntry(System.IO.Compression.ZipArchive archive, string path)
 {
     throw null;
 }
コード例 #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SRTM.SRTMDataCell"/> class.
        /// </summary>
        /// <param name='filepath'>
        /// Filepath.
        /// </param>
        /// <exception cref='FileNotFoundException'>
        /// Is thrown when a file path argument specifies a file that does not exist.
        /// </exception>
        /// <exception cref='ArgumentException'>
        /// Is thrown when an argument passed to a method is invalid.
        /// </exception>
        public SRTMDataCell(string filepath)
        {
            if (!File.Exists(filepath))
            {
                throw new FileNotFoundException("File not found.", filepath);
            }

            var filename = Path.GetFileName(filepath);

            filename = filename.Substring(0, filename.IndexOf('.')).ToLower(); // Path.GetFileNameWithoutExtension(filepath).ToLower();
            var fileCoordinate = filename.Split(new[] { 'e', 'w' });

            if (fileCoordinate.Length != 2)
            {
                throw new ArgumentException("Invalid filename.", filepath);
            }

            fileCoordinate[0] = fileCoordinate[0].TrimStart(new[] { 'n', 's' });

            Latitude = int.Parse(fileCoordinate[0]);
            if (filename.Contains("s"))
            {
                Latitude *= -1;
            }

            Longitude = int.Parse(fileCoordinate[1]);
            if (filename.Contains("w"))
            {
                Longitude *= -1;
            }

            if (filepath.EndsWith(".zip"))
            {
                using (var stream = File.OpenRead(filepath))
                    using (var archive = new System.IO.Compression.ZipArchive(stream))
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var hgt = archive.Entries[0].Open())
                            {
                                hgt.CopyTo(memoryStream);
                                HgtData = memoryStream.ToArray();
                            }
                        }
            }
            else
            {
                HgtData = File.ReadAllBytes(filepath);
            }

            switch (HgtData.Length)
            {
            case 1201 * 1201 * 2:     // SRTM-3
                PointsPerCell = 1201;
                break;

            case 3601 * 3601 * 2:     // SRTM-1
                PointsPerCell = 3601;
                break;

            default:
                throw new ArgumentException("Invalid file size.", filepath);
            }
        }
コード例 #10
0
        private async void ButtonStartGame_Click(object sender, RoutedEventArgs e)
        {
            this.mainProgressBar.IsIndeterminate = true;
            if (this.cancelSrc != null)
            {
                this.cancelSrc.Dispose();
            }
            this.cancelSrc = new CancellationTokenSource();
            this.tabProgressing.IsSelected = true;
            this.mainProgressText.Text = "Checking client version";

            int width = 0, height = 0;
            bool localEmu = this.gameClient_LocaleEmu.IsChecked == true;

            if (!int.TryParse(this.gameClient_Width.Text, out width))
            {
                MessageBox.Show(this, $"Invalid game screen width.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (!int.TryParse(this.gameClient_Height.Text, out height))
            {
                MessageBox.Show(this, $"Invalid game screen height.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                var something = await this.apiClient.GetVersionAsync();
                var responseCode = something.RootElement.GetProperty("errornu").GetString();
                if (responseCode == "0")
                {
                    var packageObj = something.RootElement.GetProperty("base").GetProperty("package");
                    // var md5s = packageObj.GetProperty("md5").GetProperty("gwphone_windows").GetString();
                    var downloadUrl = packageObj.GetProperty("packageUrl").GetString();
                    var updateVersion = packageObj.GetProperty("tar_version").GetString();
                    if (!string.IsNullOrEmpty(updateVersion))
                    {
                        updateVersion = updateVersion.Trim();
                    }

                    if (!string.Equals(this.GetClientVersion(), updateVersion, StringComparison.OrdinalIgnoreCase))
                    {
                        bool isContinue = string.Equals(this.GetDownloadingClientVersion(), updateVersion, StringComparison.OrdinalIgnoreCase);

                        if (!isContinue)
                        {
                            await File.WriteAllTextAsync(Path.Combine(RuntimeVars.RootPath, "clsy.tmp.version"), updateVersion);
                        }

                        bool isCompleted = false;
                        string targetToDelete;
                        using (var fs = new FileStream(Path.Combine(RuntimeVars.RootPath, "clsy.tmp"), isContinue ? FileMode.OpenOrCreate : FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                        {
                            targetToDelete = fs.Name;
                            this.mainProgressBar.Value = 0;
                            this.mainProgressBar.IsIndeterminate = false;
                            this.mainProgressText.Text = $"Downloading client v{updateVersion}";
                            isCompleted = await this.apiClient.DownloadFile(new Uri(downloadUrl), isContinue ? fs.Length : 0, fs, this.ProgressBarThingie, this.cancelSrc.Token);
                            await fs.FlushAsync();

                            if (isCompleted)
                            {
                                this.mainProgressText.Text = $"Unpacking client v{updateVersion}";
                                await Task.Run(async () =>
                                {
                                    fs.Seek(0, SeekOrigin.Begin);
                                    using (var zip = new System.IO.Compression.ZipArchive(fs, System.IO.Compression.ZipArchiveMode.Read))
                                    {
                                        string destinationDir = Path.Combine(RuntimeVars.RootPath, "clsy");
                                        Directory.Delete(destinationDir, true);
                                        destinationDir = Directory.CreateDirectory(destinationDir).FullName;
                                        using (var pooledBuffer = MemoryPool<byte>.Shared.Rent(4096 * 2))
                                        {
                                            foreach (var entry in zip.Entries)
                                            {
                                                string thePath = Path.Combine(destinationDir, entry.FullName);
                                                Directory.CreateDirectory(Path.GetDirectoryName(thePath));
                                                using (var destFs = File.Open(thePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
                                                using (var stream = entry.Open())
                                                {
                                                    destFs.SetLength(entry.Length);
                                                    int read = await stream.ReadAsync(pooledBuffer.Memory);
                                                    while (read > 0)
                                                    {
                                                        await destFs.WriteAsync(pooledBuffer.Memory.Slice(0, read));
                                                        read = await stream.ReadAsync(pooledBuffer.Memory);
                                                    }
                                                    await destFs.FlushAsync();
                                                }
                                            }
                                        }
                                    }
                                });
                                await File.WriteAllTextAsync(Path.Combine(RuntimeVars.RootPath, "clsy.version"), updateVersion);
                            }
                        }
                        if (isCompleted)
                        {
                            try
                            {
                                File.Delete(targetToDelete);
                            }
                            catch { }

                            await LaunchGame(width, height, localEmu);
                        }
                    }
                    else
                    {
                        await LaunchGame(width, height, localEmu);
                    }
                }
                else
                {
                    MessageBox.Show(this, $"Server response with code {responseCode}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (TaskCanceledException)
            {

            }
            catch (InvalidGameScreenSize ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            this.tabMainMenu.IsSelected = true;
        }
コード例 #11
0
ファイル: SystemProcedures.cs プロジェクト: pwdlugosz/Horse
        public override void Invoke()
        {

            // Get the files //
            string archive_path = this._Parameters["@ARC_PATH"].Expression.Evaluate().valueSTRING;
            
            using (System.IO.Compression.ZipArchive arc = new System.IO.Compression.ZipArchive(File.Open(archive_path, FileMode.CreateNew)))
            {
                string path = this._Parameters["@DIR_PATH"].Expression.Evaluate().valueSTRING;
                arc.CreateEntry(path, System.IO.Compression.CompressionLevel.Optimal);
            }

        }
コード例 #12
0
ファイル: UpdateCheck.cs プロジェクト: Quit/SteveCannon
        protected void checkStream(Stream stream)
        {
            Console.WriteLine("Check Stream");
            // oook
            using (BinaryReader reader = new BinaryReader(stream))
            {
                // Try to identify the first few bytes.
                byte[] geoffers = reader.ReadBytes(4);
                int first = BitConverter.ToInt32(geoffers, 0);
                if (first == 0x04034b50)
                {
                    Console.WriteLine("Likely is... a zip?");
                    MemoryStream other = new MemoryStream();
                    other.Write(geoffers, 0, 4);
                    stream.CopyTo(other);
                    other.Seek(0, SeekOrigin.Begin);
                    stream.Dispose();

                    // Check for integrity
                    try
                    {
                        var entries = new System.IO.Compression.ZipArchive(other).Entries;
                        other.Seek(0, SeekOrigin.Begin);
                    }
                    catch (Exception ex)
                    {
                        throw new UpdateException(this, "Server likely replied with a zip; but ZipArchive failed: " + ex.Message, ex);
                    }

                    downloadFile(other);
                }
                else if (geoffers[0] == '{')
                {
                    Console.WriteLine("Likely is... a json?");
                    MemoryStream other = new MemoryStream();
                    other.Write(geoffers, 0, 4);
                    stream.CopyTo(other);
                    other.Seek(0, SeekOrigin.Begin);
                    stream.Dispose();
                    downloadJson(other);
                }
                else
                    throw new UpdateException(this, "No idea what " + (first) + " could indicate as file type.");
            }
        }
コード例 #13
0
        public void Berecne(
            Func <Int64, SictBerictDataiIdentInDsInfo> FunkZuBerictScritIndexDataiIdent,
            Func <string, byte[]> FunkZuDataiPfaadDataiInhalt,
            //	Func<Int64, SictWertMitZait<Optimat.Anwendung.RefNezDiferenz.SictRefNezDiferenzScritSictJson>> FunkZuBerictScritIndexBerictScritBerecne,
            Int64 BerecnungEndeAnwendungZaitMili)
        {
            while (true)
            {
                var ScritLezteAutomaatZuusctand = InternListeZuZaitAutomaatZuusctand.LastOrDefault().Wert;

                if (null != ScritLezteAutomaatZuusctand)
                {
                    if (BerecnungEndeAnwendungZaitMili <= ScritLezteAutomaatZuusctand.NuzerZaitMili)
                    {
                        break;
                    }
                }

                if (null == FunkZuBerictScritIndexDataiIdent)
                {
                    return;
                }

                if (null == FunkZuDataiPfaadDataiInhalt)
                {
                    return;
                }

                var ScritIndex = (ScritVerwertetLezteIndex + 1) ?? BeginBerictScritIndex;

                var BerictScritDataiIdent = FunkZuBerictScritIndexDataiIdent(ScritIndex);

                if (null == BerictScritDataiIdent.DataiPfaad)
                {
                    return;
                }

                var DataiInhalt = FunkZuDataiPfaadDataiInhalt(BerictScritDataiIdent.DataiPfaad);

                using (var ZipArchive = new System.IO.Compression.ZipArchive(new MemoryStream(DataiInhalt), System.IO.Compression.ZipArchiveMode.Read))
                {
                    var MengeEntry = ZipArchive.Entries;

                    if (null != MengeEntry)
                    {
                        foreach (var Entry in MengeEntry)
                        {
                            using (var EntryStream = Entry.Open())
                            {
                                var EntryInhalt = Optimat.Glob.AusStreamLeese(EntryStream);

                                var EntrySictUTF8 = Encoding.UTF8.GetString(EntryInhalt);

                                var EntrySictSctrukt = SictBerictAusDsAuswert.AusStringVonAnwendungBerictBerecne(EntrySictUTF8);

                                //	!!!! Hiir werd davon ausgegange das MengeAutomaatZuusctandSictSeriel jewails komplete Zuusctand (Diferenz von 0) enthalte.

                                var MengeAutomaatZuusctandSictSeriel =
                                    EntrySictSctrukt.MengeAutomaatZuusctandMitZait ??
                                    EntrySictSctrukt.MengeAutomaatZuusctandDiferenzScritMitZait;

                                if (null != MengeAutomaatZuusctandSictSeriel)
                                {
                                    foreach (var AutomaatZuusctandSictSerielMitZait in MengeAutomaatZuusctandSictSeriel)
                                    {
                                        var AutomaatZuusctandSictSeriel = AutomaatZuusctandSictSerielMitZait.Wert;

                                        var ScritIndexNulbar = AutomaatZuusctandSictSeriel.ScritIndex;

                                        if (!ScritIndexNulbar.HasValue)
                                        {
                                            continue;
                                        }

                                        if (ScritVerwertetLezteIndex.HasValue)
                                        {
                                            var AutomaatZuusctandBerictScritErwartetIndex = (ScritVerwertetLezteIndex + 1) ?? 0;

                                            if (!(AutomaatZuusctandBerictScritErwartetIndex == ScritIndexNulbar))
                                            {
                                                continue;
                                            }
                                        }

                                        ScritVerwertetLezteIndex = ScritIndexNulbar;

                                        Optimat.ScpezEveOnln.SictAutomatZuusctand AutomaatZuusctandKopii = null;

                                        try
                                        {
                                            var AutomaatZuusctandBerictScritDiferenz = AutomaatZuusctandSictSeriel;

                                            var ScritSume =
                                                BerictSictSume.BerecneScritSumeListeWurzelRefClrUndErfolg(
                                                    AutomaatZuusctandBerictScritDiferenz,
                                                    ZiilMemberExistentNictIgnoriire);

                                            if (null == ScritSume)
                                            {
                                                continue;
                                            }

                                            if (!ScritSume.Volsctändig)
                                            {
                                                continue;
                                            }

                                            var ScritSumeListeObjektReferenzClr = ScritSume.ListeWurzelRefClr;

                                            if (null == ScritSumeListeObjektReferenzClr)
                                            {
                                                continue;
                                            }

                                            var AutomaatZuusctand =
                                                (Optimat.ScpezEveOnln.SictAutomatZuusctand)
                                                ScritSumeListeObjektReferenzClr.FirstOrDefault();

                                            if (null == AutomaatZuusctand)
                                            {
                                                continue;
                                            }

                                            /*
                                             * 2015.00.04
                                             *
                                             * Kopii nit meer durc SictRefNezKopii mööglic da Dictionary<,> verwendet werd.
                                             *
                                             * AutomaatZuusctandKopii = SictRefNezKopii.ObjektKopiiErsctele(AutomaatZuusctand, null, null);
                                             * */

                                            /*
                                             * 2015.00.06
                                             *
                                             * Kopii wiider durc SictRefNezKopii mööglic da SictRefNezKopii naacgerüsct wurd um Verhalte von TypeBehandlungRictliinie RefNezDif zu verwende.
                                             *
                                             * AutomaatZuusctandKopii = RefNezDiferenz.SictRefNezSume.ObjektKopiiBerecne(AutomaatZuusctand,
                                             *      RefNezDiferenz.NewtonsoftJson.SictMengeTypeBehandlungRictliinieNewtonsoftJson.KonstruktSictParam());
                                             * */

                                            AutomaatZuusctandKopii = SictRefNezKopii.ObjektKopiiErsctele(AutomaatZuusctand, null, null);
                                        }
                                        finally
                                        {
                                            InternListeZuZaitAutomaatZuusctand.Add(
                                                new SictWertMitZait <Optimat.ScpezEveOnln.SictAutomatZuusctand>(
                                                    AutomaatZuusctandSictSerielMitZait.Zait, AutomaatZuusctandKopii));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #14
0
        public void Berecne(
            out System.Exception LaadeDataiException,
            int?VerwertungMengeDataiAnzaalScranke)
        {
            LaadeDataiException = null;

            var BerictVerzaicnisPfaad = this.BerictHauptVerzaicnisPfaad;
            var BerictWindowClientRasterVerzaicnisPfaad = this.BerictWindowClientRasterVerzaicnisPfaad;

            var MengeAutomaatZuusctandScnapscusAngefordertZaitMili = this.MengeAutomaatZuusctandScnapscusAngefordertZaitMili;

            var MengeAutomaatZuusctandScnapscusAngefordertAuswert = this.MengeAutomaatZuusctandScnapscusAngefordertAuswert;

            var WorkaroundAusBerictBeginListeScritAnzaalUnvolsctändigAnzaal = this.WorkaroundAusBerictBeginListeScritAnzaalUnvolsctändigAnzaal;

            var BerecneLezteListeAutomaatZuusctand = new List <KeyValuePair <Int64, Optimat.ScpezEveOnln.SictAutomatZuusctand> >();

            try
            {
                if (null != MengeAutomaatZuusctandScnapscusAngefordertZaitMili)
                {
                    var MengeAutomaatZuusctandScnapscusVorhandeZaitMili = DictVonAutomaatZaitMiliAutomaatZuusctand.MengeKeyBerecne();

                    var MengeAutomaatZuusctandScnapscusNocZuLaadeZaitMili =
                        MengeAutomaatZuusctandScnapscusAngefordertZaitMili
                        .Where((KandidaatNocZuLaade) => !MengeAutomaatZuusctandScnapscusVorhandeZaitMili.Contains(KandidaatNocZuLaade)).ToArray();

                    if (0 < MengeAutomaatZuusctandScnapscusNocZuLaadeZaitMili.Length)
                    {
                        var AutomaatZuusctandScnapscusNocZuLaadeZaitMili = MengeAutomaatZuusctandScnapscusNocZuLaadeZaitMili.OrderBy((t) => t).FirstOrDefault();

                        var BeginBerictScritIndex =
                            Math.Max(0,
                                     DictVonAnwendungBerictScritIndexPfaadZuAutomaatZuusctandInfo
                                     .LastOrDefault((Kandidaat) => Kandidaat.Value.Zait <= AutomaatZuusctandScnapscusNocZuLaadeZaitMili).Key -
                                     WorkaroundAusBerictBeginListeScritAnzaalUnvolsctändigAnzaal - 4);

                        var AuswertErhalte = false;

                        if (null != MengeAutomaatZuusctandScnapscusAngefordertAuswert)
                        {
                            var BeginScritDistanzVonBisherAuswert = BeginBerictScritIndex - MengeAutomaatZuusctandScnapscusAngefordertAuswert.ScritVerwertetLezteIndex;

                            if (MengeAutomaatZuusctandScnapscusAngefordertAuswert.ListeZuZaitAutomaatZuusctand.LastOrDefault().Zait < AutomaatZuusctandScnapscusNocZuLaadeZaitMili &&
                                BeginScritDistanzVonBisherAuswert < 10)
                            {
                                AuswertErhalte = true;
                            }
                        }

                        if (!AuswertErhalte)
                        {
                            this.MengeAutomaatZuusctandScnapscusAngefordertAuswert = MengeAutomaatZuusctandScnapscusAngefordertAuswert =
                                new SictBerictListeScritDiferenzAuswert(BeginBerictScritIndex, ZiilMemberExistentNictIgnoriire);
                        }

                        MengeAutomaatZuusctandScnapscusAngefordertAuswert.Berecne(
                            (ScritIndex) => Optimat.Glob.TAD(this.DictVonAnwendungBerictScritIndexPfaadZuAutomaatZuusctandInfo, ScritIndex).Wert,
                            InhaltAusDataiMitPfaad,
                            AutomaatZuusctandScnapscusNocZuLaadeZaitMili);
                    }
                }

                if (null != MengeAutomaatZuusctandScnapscusAngefordertAuswert)
                {
                    var ListeZuZaitAutomaatZuusctand = MengeAutomaatZuusctandScnapscusAngefordertAuswert.ListeZuZaitAutomaatZuusctand;

                    if (null != ListeZuZaitAutomaatZuusctand)
                    {
                        var ListeZuZaitAutomaatZuusctandVermuutungVolsctändig = ListeZuZaitAutomaatZuusctand;

                        if (0 < MengeAutomaatZuusctandScnapscusAngefordertAuswert.BeginBerictScritIndex)
                        {
                            ListeZuZaitAutomaatZuusctandVermuutungVolsctändig =
                                ListeZuZaitAutomaatZuusctand.Skip(WorkaroundAusBerictBeginListeScritAnzaalUnvolsctändigAnzaal);
                        }

                        foreach (var ZuZaitAutomaatZuusctand in ListeZuZaitAutomaatZuusctandVermuutungVolsctändig)
                        {
                            if (null != ZuZaitAutomaatZuusctand.Wert)
                            {
                                var AutomaatScritIdentZaitMili = (Int64?)ZuZaitAutomaatZuusctand.Wert.NuzerZaitMili;

                                if (!AutomaatScritIdentZaitMili.HasValue)
                                {
                                    continue;
                                }

                                DictVonAutomaatZaitMiliAutomaatZuusctand.AintraagErsctele(AutomaatScritIdentZaitMili.Value, ZuZaitAutomaatZuusctand.Wert);
                            }
                        }
                    }
                }

                try
                {
                    if (!(VerwertungMengeDataiAnzaalScranke <= 0) &&
                        null != BerictVerzaicnisPfaad)
                    {
                        /*
                         * Ermitelt ob noie Dataie vorhande und verwertet diise gegeebenenfals.
                         * */

                        var BerictVerzaicnis = new DirectoryInfo(BerictVerzaicnisPfaad);

                        var MengeFile = BerictVerzaicnis.GetFiles();

                        var ListeFile =
                            MengeFile
                            .OrderBy((KandidaatFile) => KandidaatFile.Name)
                            .ToArray();

                        int VerwertungMengeDataiAnzaalBisher = 0;

                        foreach (var File in ListeFile)
                        {
                            if (VerwertungMengeDataiAnzaalScranke <= VerwertungMengeDataiAnzaalBisher)
                            {
                                break;
                            }

                            var DataiPfaad = File.FullName;

                            var DataiBeraitsVerwertet = Optimat.Glob.TAD(DictZuDataiPfaadDataiVerwertungErfolg, DataiPfaad);

                            if (DataiBeraitsVerwertet)
                            {
                                continue;
                            }

                            int DataiVerwertungVersuucAnzaal = 0;

                            DictZuDataiPfaadDataiVerwertungVersuucAnzaal.TryGetValue(DataiPfaad, out DataiVerwertungVersuucAnzaal);

                            if (3 < DataiVerwertungVersuucAnzaal)
                            {
                                continue;
                            }

                            DictZuDataiPfaadDataiVerwertungVersuucAnzaal[DataiPfaad] = 1 + DataiVerwertungVersuucAnzaal;

                            var DataiInhalt = InhaltAusDataiMitPfaad(DataiPfaad);

                            if (null == DataiInhalt)
                            {
                                continue;
                            }

                            using (var ZipArchive = new System.IO.Compression.ZipArchive(new MemoryStream(DataiInhalt), System.IO.Compression.ZipArchiveMode.Read))
                            {
                                var MengeEntry = ZipArchive.Entries;

                                if (null != MengeEntry)
                                {
                                    foreach (var Entry in MengeEntry)
                                    {
                                        var EntryIdent = new SictBerictDataiIdentInDsInfo(DataiPfaad, Entry.FullName);

                                        using (var EntryStream = Entry.Open())
                                        {
                                            var EntryInhalt = Optimat.Glob.AusStreamLeese(EntryStream);

                                            var EntrySictUTF8 = Encoding.UTF8.GetString(EntryInhalt);

                                            var EntrySictSctrukt = AusStringVonAnwendungBerictBerecne(EntrySictUTF8);

                                            //	!!!! Hiir werd davon ausgegange das MengeAutomaatZuusctandSictSeriel jewails komplete Zuusctand (Diferenz von 0) enthalte.

                                            var MengeAutomaatZuusctandSictSeriel =
                                                EntrySictSctrukt.MengeAutomaatZuusctandMitZait ??
                                                EntrySictSctrukt.MengeAutomaatZuusctandDiferenzScritMitZait;

                                            if (null != MengeAutomaatZuusctandSictSeriel)
                                            {
                                                foreach (var AutomaatZuusctandSictSeriel in MengeAutomaatZuusctandSictSeriel)
                                                {
                                                    var ScritIndexNulbar = AutomaatZuusctandSictSeriel.Wert.ScritIndex;

                                                    if (!ScritIndexNulbar.HasValue)
                                                    {
                                                        continue;
                                                    }

                                                    var ScritIndex = ScritIndexNulbar.Value;

                                                    var AutomaatZuusctandBerictScritErwartetIndex = (AutomaatZuusctandBerictScritLezteIndex + 1) ?? 0;

                                                    if (!(AutomaatZuusctandBerictScritErwartetIndex == ScritIndex))
                                                    {
                                                        continue;
                                                    }

                                                    AutomaatZuusctandBerictScritLezteIndex = ScritIndex;

                                                    var AutomaatZuusctandBerictScritDiferenz = AutomaatZuusctandSictSeriel;

                                                    var ScritSume =
                                                        AutomaatZuusctandBerictSictSume.BerecneScritSumeListeWurzelRefClrUndErfolg(
                                                            AutomaatZuusctandBerictScritDiferenz.Wert,
                                                            ZiilMemberExistentNictIgnoriire);

                                                    if (null == ScritSume)
                                                    {
                                                        continue;
                                                    }

                                                    var ScritSumeListeObjekt = ScritSume.ListeWurzelRefClr;

                                                    //	!!!!	zu erseze durc entferne taatsäclic nit meer benöötigte.
                                                    AutomaatZuusctandBerictSictSume.MengeObjektInfoEntferneÄltere(ScritIndex - 44);

                                                    if (null == ScritSumeListeObjekt)
                                                    {
                                                        continue;
                                                    }

                                                    var AutomaatZuusctand =
                                                        (Optimat.ScpezEveOnln.SictAutomatZuusctand)
                                                        ScritSumeListeObjekt.FirstOrDefault();

                                                    if (null == AutomaatZuusctand)
                                                    {
                                                        continue;
                                                    }

                                                    var AutomaatScritIdentZaitMili = (Int64?)AutomaatZuusctand.NuzerZaitMili;

                                                    if (!AutomaatScritIdentZaitMili.HasValue)
                                                    {
                                                        continue;
                                                    }

                                                    /*
                                                     * 2015.00.04
                                                     *
                                                     * Kopii nit meer durc SictRefNezKopii mööglic da Dictionary<,> verwendet werd.
                                                     *
                                                     * var AutomaatZuusctandKopii = SictRefNezKopii.ObjektKopiiErsctele(AutomaatZuusctand, null, null);
                                                     * */

                                                    /*
                                                     * 2015.00.06
                                                     *
                                                     * Kopii wiider durc SictRefNezKopii mööglic da SictRefNezKopii naacgerüsct wurd um Verhalte von TypeBehandlungRictliinie RefNezDif zu verwende.
                                                     *
                                                     *              var AutomaatZuusctandKopii = RefNezDiferenz.SictRefNezSume.ObjektKopiiBerecne(AutomaatZuusctand,
                                                     *                      RefNezDiferenz.NewtonsoftJson.SictMengeTypeBehandlungRictliinieNewtonsoftJson.KonstruktSictParam());
                                                     * */
                                                    var AutomaatZuusctandKopii = SictRefNezKopii.ObjektKopiiErsctele(AutomaatZuusctand, null, null);

                                                    BerecneLezteListeAutomaatZuusctand.Add(new KeyValuePair <Int64, Optimat.ScpezEveOnln.SictAutomatZuusctand>(
                                                                                               AutomaatScritIdentZaitMili.Value,
                                                                                               AutomaatZuusctandKopii));

                                                    DictVonAnwendungBerictScritIndexPfaadZuAutomaatZuusctandInfo[ScritIndexNulbar.Value] =
                                                        new SictWertMitZait <SictBerictDataiIdentInDsInfo>(AutomaatScritIdentZaitMili.Value, EntryIdent);

                                                    ZuAutomaatZuusctandVonZaitMiliAblaitungScpaicere(
                                                        new SictWertMitZait <Optimat.ScpezEveOnln.SictAutomatZuusctand>(
                                                            AutomaatZuusctandSictSeriel.Zait, AutomaatZuusctandKopii));

                                                    if (DictVonAutomaatZaitMiliAutomaatZuusctand.Count < ScatenscpaicerScritZuusctandAnzaalScrankeMax)
                                                    {
                                                        DictVonAutomaatZaitMiliAutomaatZuusctand.AintraagErsctele(AutomaatScritIdentZaitMili.Value, AutomaatZuusctandKopii);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            DictZuDataiPfaadDataiVerwertungErfolg[DataiPfaad] = true;

                            ++VerwertungMengeDataiAnzaalBisher;
                        }
                    }
                }
                catch (System.Exception Exception)
                {
                    LaadeDataiException = Exception;
                }

                {
                    //	Scatescpaicer Scranke apliziire.

                    DictZuDataiPfaadDataiInhalt.BescrankeEntferneLängerNitVerwendete(
                        null,
                        ScatenscpaicerBerictDataiKapazitäätScranke,
                        (DataiInhalt) => 1000 + ((null == DataiInhalt) ? 0 : DataiInhalt.LongLength));

                    DictVonAutomaatZaitMiliAutomaatZuusctand.BescrankeEntferneLängerNitVerwendete(
                        ScatenscpaicerScritZuusctandAnzaalScrankeMax);
                }

                {
                    AnwendungMengeScnapscusZaitMili =
                        DictVonAnwendungBerictScritIndexPfaadZuAutomaatZuusctandInfo
                        .Select((t) => t.Value.Zait).ToArray();

                    ListeDataiAnzaal = DictZuDataiPfaadDataiVerwertungErfolg.Count;
                }
            }
            finally
            {
                this.BerecneLezteListeAutomaatZuusctand = BerecneLezteListeAutomaatZuusctand.ToArray();
            }
        }
コード例 #15
0
        Optimat.ScpezEveOnln.SictAutomatZuusctand AutomaatZuusctandZuZaitMiliLaade(
            Int64 ScnapcusAnwendungZaitMili)
        {
            var AutomaaZaitMiliUndPfaad =
                DictVonAnwendungBerictScritIndexPfaadZuAutomaatZuusctandInfo
                .FirstOrDefault((Kandidaat) => Kandidaat.Value.Zait == ScnapcusAnwendungZaitMili);

            var Pfaad = AutomaaZaitMiliUndPfaad.Value.Wert;

            if (null == Pfaad.DataiPfaad)
            {
                return(null);
            }

            var DataiInhalt = this.InhaltAusDataiMitPfaad(Pfaad.DataiPfaad);

            var SerializeSettings = new JsonSerializerSettings();

            SerializeSettings.DefaultValueHandling       = DefaultValueHandling.IgnoreAndPopulate;
            SerializeSettings.TypeNameHandling           = TypeNameHandling.Auto;
            SerializeSettings.ReferenceLoopHandling      = ReferenceLoopHandling.Serialize;
            SerializeSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;

            if (null == Pfaad.InArchiveEntryPfaad)
            {
                throw new NotImplementedException();
            }
            else
            {
                using (var ZipArchive = new System.IO.Compression.ZipArchive(new MemoryStream(DataiInhalt), System.IO.Compression.ZipArchiveMode.Read))
                {
                    var MengeEntry = ZipArchive.Entries;

                    if (null != MengeEntry)
                    {
                        foreach (var Entry in MengeEntry)
                        {
                            if (!string.Equals(Entry.FullName, Pfaad.InArchiveEntryPfaad))
                            {
                                continue;
                            }

                            using (var EntryStream = Entry.Open())
                            {
                                var EntryInhalt = Optimat.Glob.AusStreamLeese(EntryStream, null, 0x400000);

                                var EntrySictUTF8 = Encoding.UTF8.GetString(EntryInhalt);

                                var EntrySictSctrukt = AusStringVonAnwendungBerictBerecne(EntrySictUTF8);

                                var MengeAutomaatZuusctandSictDiferenzMitZait = EntrySictSctrukt.MengeAutomaatZuusctandMitZait;

                                if (null != MengeAutomaatZuusctandSictDiferenzMitZait)
                                {
                                    foreach (var AutomaatZuusctandSictDiferenzMitZait in MengeAutomaatZuusctandSictDiferenzMitZait)
                                    {
                                        if (AutomaatZuusctandSictDiferenzMitZait.Zait != ScnapcusAnwendungZaitMili)
                                        {
                                            continue;
                                        }

                                        var AutomaatZuusctandSictDiferenz = AutomaatZuusctandSictDiferenzMitZait.Wert;

                                        if (null == AutomaatZuusctandSictDiferenz)
                                        {
                                            continue;
                                        }

                                        var AutomaatZuusctand =
                                            (Optimat.ScpezEveOnln.SictAutomatZuusctand)
                                            Bib3.RefNezDiferenz.Extension.ListeWurzelDeserialisiire(AutomaatZuusctandSictDiferenz)
                                            .FirstOrDefaultNullable();

                                        return(AutomaatZuusctand);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(null);
        }
コード例 #16
0
        //internal static void GetCellStringValues(this WorkbookPart workbookPart,
        //    IEnumerable<Cell> cells, Action<string> values)
        //{
        //    foreach (var cell in cells)
        //    {
        //        values(TryGetStringFromCell(workbookPart, cell));
        //    }
        //}

        //internal static void GetCellStringValues(this WorkbookPart workbookPart,
        //    IEnumerable<Cell> cells, Action<string, Cell> values)
        //{
        //    foreach (var cell in cells)
        //    {
        //        values(TryGetStringFromCell(workbookPart, cell), cell);
        //    }
        //}

        // based on http://ericwhite.com/blog/handling-invalid-hyperlinks-openxmlpackageexception-in-the-open-xml-sdk/
        public static void FixInvalidUri(System.IO.Stream fs, Func <string, Uri> invalidUriHandler)
        {
            System.Xml.Linq.XNamespace relNs = "http://schemas.openxmlformats.org/package/2006/relationships";
            using (var za = new System.IO.Compression.ZipArchive(fs, System.IO.Compression.ZipArchiveMode.Update))
            {
                foreach (var entry in za.Entries.ToList())
                {
                    if (!entry.Name.EndsWith(".rels"))
                    {
                        continue;
                    }
                    bool replaceEntry = false;
                    System.Xml.Linq.XDocument entryXDoc = null;
                    using (var entryStream = entry.Open())
                    {
                        try
                        {
                            entryXDoc = System.Xml.Linq.XDocument.Load(entryStream);
                            if (entryXDoc.Root != null && entryXDoc.Root.Name.Namespace == relNs)
                            {
                                var urisToCheck = entryXDoc
                                                  .Descendants(relNs + "Relationship")
                                                  .Where(r => r.Attribute("TargetMode") != null && (string)r.Attribute("TargetMode") == "External");
                                foreach (var rel in urisToCheck)
                                {
                                    var target = (string)rel.Attribute("Target");
                                    if (target != null)
                                    {
                                        try
                                        {
                                            Uri uri = new Uri(target);
                                        }
                                        catch (UriFormatException)
                                        {
                                            Uri newUri = invalidUriHandler(target);
                                            rel.Attribute("Target").Value = newUri.ToString();
                                            replaceEntry = true;
                                        }
                                    }
                                }
                            }
                        }
                        catch (System.Xml.XmlException)
                        {
                            continue;
                        }
                    }
                    if (replaceEntry)
                    {
                        var fullName = entry.FullName;
                        entry.Delete();
                        var newEntry = za.CreateEntry(fullName);
                        using (var writer = new System.IO.StreamWriter(newEntry.Open()))
                            using (var xmlWriter = System.Xml.XmlWriter.Create(writer))
                            {
                                entryXDoc.WriteTo(xmlWriter);
                            }
                    }
                }
            }
        }
コード例 #17
0
        public async Task CreateAsync(ulong startTimestamp, ulong endTimestamp, string region, IEnumerable <TemporaryExposureKeyModel> keys)
        {
            Logger.LogInformation($"start {nameof(CreateAsync)}");
            var current = keys;

            while (current.Any())
            {
                var exportKeyModels = current.Take(MaxKeysPerFile).ToArray();
                var exportKeys      = exportKeyModels.Select(_ => _.ToKey()).ToArray();
                current = current.Skip(MaxKeysPerFile);

                var signatureInfo = SignatureService.Create();
                await SignService.SetSignatureAsync(signatureInfo);

                var exportModel = await TekExportRepository.CreateAsync();

                exportModel.BatchSize      = exportKeyModels.Length;
                exportModel.StartTimestamp = startTimestamp;
                exportModel.EndTimestamp   = endTimestamp;
                exportModel.Region         = region;
                exportModel.SignatureInfos = new SignatureInfo[] { signatureInfo };

                var bin = new TemporaryExposureKeyExport();
                bin.Keys.AddRange(exportKeys);
                bin.BatchNum       = exportModel.BatchNum;
                bin.BatchSize      = exportModel.BatchSize;
                bin.Region         = exportModel.Region;
                bin.StartTimestamp = exportModel.StartTimestamp;
                bin.EndTimestamp   = exportModel.EndTimestamp;
                bin.SignatureInfos.Add(signatureInfo);

                var sig = new TEKSignatureList();

                using var binStream = new MemoryStream();
                bin.WriteTo(binStream);
                await binStream.FlushAsync();

                binStream.Seek(0, SeekOrigin.Begin);
                var signature = await CreateSignatureAsync(binStream, bin.BatchNum, bin.BatchSize);

                signature.SignatureInfo = signatureInfo;
                sig.Signatures.Add(signature);

                using (var s = new MemoryStream())
                {
                    using (var z = new System.IO.Compression.ZipArchive(s, System.IO.Compression.ZipArchiveMode.Create, true))
                    {
                        var binEntry = z.CreateEntry(ExportBinFileName);
                        using (var binFile = binEntry.Open())
                        {
                            binStream.Seek(0, SeekOrigin.Begin);
                            await binStream.CopyToAsync(binFile);

                            await binFile.FlushAsync();
                        }

                        var sigEntry = z.CreateEntry(ExportSigFileName);
                        using (var sigFile = sigEntry.Open())
                        {
                            sig.WriteTo(sigFile);
                            await sigFile.FlushAsync();
                        }
                    }
                    s.Seek(0, SeekOrigin.Begin);
                    await BlobService.WriteToBlobAsync(s, exportModel, bin, sig);
                }
                await TekExportRepository.UpdateAsync(exportModel);
            }
        }
コード例 #18
0
 public static void ExtractToDirectory(this System.IO.Compression.ZipArchive source, string destinationDirectoryName, bool overwriteFiles) => throw null;
コード例 #19
0
        public async Task CreateAsync(ulong startTimestamp,
                                      ulong endTimestamp,
                                      string region,
                                      int batchNum,
                                      IEnumerable <TemporaryExposureKeyModel> keys)
        {
            Logger.LogInformation($"start {nameof(CreateAsync)}");
            var current = keys;

            while (current.Any())
            {
                var exportKeyModels = current.Take(MaxKeysPerFile).ToArray();
                var exportKeys      = exportKeyModels.Select(_ => _.ToKey()).ToArray();
                current = current.Skip(MaxKeysPerFile);

                var signatureInfo = SignatureService.Create();
                await SignService.SetSignatureAsync(signatureInfo);

                var exportModel = new TemporaryExposureKeyExportModel();
                exportModel.id           = batchNum.ToString();
                exportModel.PartitionKey = region;
                // TODO: not support apple
                //exportModel.BatchNum = batchNum;
                exportModel.BatchNum = 1;
                exportModel.Region   = region;
                // TODO: not support apple
                //exportModel.BatchSize = exportKeyModels.Length;
                exportModel.BatchSize                  = 1;
                exportModel.StartTimestamp             = startTimestamp;
                exportModel.EndTimestamp               = endTimestamp;
                exportModel.TimestampSecondsSinceEpoch = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                exportModel = await TekExportRepository.CreateAsync(exportModel);

                var bin = new TemporaryExposureKeyExport();
                bin.Keys.AddRange(exportKeys);
                bin.BatchNum       = exportModel.BatchNum;
                bin.BatchSize      = exportModel.BatchSize;
                bin.Region         = exportModel.Region;
                bin.StartTimestamp = exportModel.StartTimestamp;
                bin.EndTimestamp   = exportModel.EndTimestamp;
                bin.SignatureInfos.Add(signatureInfo);

                var sig = new TEKSignatureList();

                using var binStream = new MemoryStream();
                await binStream.WriteAsync(FixedHeader, 0, FixedHeaderWidth);

                using var binStreamCoded = new CodedOutputStream(binStream, true);
                bin.WriteTo(binStreamCoded);
                binStreamCoded.Flush();
                await binStream.FlushAsync();

                var signature = await CreateSignatureAsync(binStream, bin.BatchNum, bin.BatchSize);

                signature.SignatureInfo = signatureInfo;
                sig.Signatures.Add(signature);

                using (var s = new MemoryStream())
                {
                    using (var z = new System.IO.Compression.ZipArchive(s, System.IO.Compression.ZipArchiveMode.Create, true))
                    {
                        var binEntry = z.CreateEntry(ExportBinFileName);
                        using (var binFile = binEntry.Open())
                        {
                            binStream.Seek(0, SeekOrigin.Begin);
                            await binStream.CopyToAsync(binFile);

                            await binFile.FlushAsync();
                        }

                        var sigEntry = z.CreateEntry(ExportSigFileName);
                        using (var sigFile = sigEntry.Open())
                            using (var output = new CodedOutputStream(sigFile))
                            {
                                sig.WriteTo(output);
                                output.Flush();
                                await sigFile.FlushAsync();
                            }
                    }
                    s.Seek(0, SeekOrigin.Begin);
                    await BlobService.WriteToBlobAsync(s, exportModel, bin, sig);
                }
                await TekExportRepository.UpdateAsync(exportModel);
            }
        }
コード例 #20
0
 private static void InplaceUpdate(string destpath, string filename, string[] excludes)
 {
     destpath = System.IO.Path.GetFullPath(destpath);
     using (var file = System.IO.File.OpenRead(filename))
         using (var archive = new System.IO.Compression.ZipArchive(file, System.IO.Compression.ZipArchiveMode.Read)) {
             var    entries  = archive.Entries.OrderBy(ent => ent.FullName);
             var    root     = entries.First();
             string rootpath = "";
             if (root.FullName.EndsWith("/") &&
                 entries.All(ent => ent.FullName.StartsWith(root.FullName)))
             {
                 rootpath = root.FullName;
             }
             foreach (var ent in entries)
             {
                 var path = System.IO.Path.Combine(destpath, ent.FullName.Substring(rootpath.Length).Replace('\\', '/'));
                 if (ent.FullName.EndsWith("/"))
                 {
                     var info = System.IO.Directory.CreateDirectory(path);
                     try {
                         info.LastWriteTime = ent.LastWriteTime.DateTime;
                     }
                     catch (System.IO.IOException) {
                     }
                 }
                 else
                 {
                     try {
                         System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
                         using (var dst = System.IO.File.Create(path))
                             using (var src = ent.Open()) {
                                 src.CopyTo(dst);
                             }
                         var info = new System.IO.FileInfo(path);
                         try {
                             info.LastWriteTime = ent.LastWriteTime.DateTime;
                         }
                         catch (System.IO.IOException) {
                         }
                     }
                     catch (System.IO.IOException) {
                         if (!excludes.Contains(ent.Name))
                         {
                             throw;
                         }
                     }
                 }
             }
             var oldentries = Glob(destpath).ToArray();
             var newentries = entries
                              .Select(ent => ent.FullName)
                              .Where(ent => !ent.EndsWith("/"))
                              .Select(ent => System.IO.Path.Combine(destpath, ent.Substring(rootpath.Length).Replace('\\', '/')))
                              .ToArray();
             foreach (var old in oldentries.Except(newentries))
             {
                 try {
                     System.IO.File.Delete(old);
                 }
                 catch (System.IO.IOException) {
                 }
             }
         }
 }
コード例 #21
0
        private void ImportCoordsBtn_Click(object sender, RoutedEventArgs e)
        {
            // File Input Dialog
            //Microsoft.Win32.OpenFileDialog fileDialog = new Microsoft.Win32.OpenFileDialog();
            //fileDialog.Title = "Select file to Import";
            //fileDialog.Filter = "Supported files (*.xml, *.json)|*.xml; *.json|All files (*.*)|*.*";
            //fileDialog.ShowDialog();

            Microsoft.Win32.OpenFileDialog fileDialog = new Microsoft.Win32.OpenFileDialog
            {
                Title       = "Select file to Import",
                Filter      = "Supported files (*.cf, *.json)|*.cf; *.json|All files (*.*)|*.*",
                Multiselect = false
            };



            if (fileDialog.ShowDialog() == true)
            {
                // Handle CF File (from Combat Flite)
                if (fileDialog.SafeFileName.EndsWith("cf"))
                {
                    System.IO.Compression.ZipArchive cfFile = System.IO.Compression.ZipFile.Open(fileDialog.FileName, System.IO.Compression.ZipArchiveMode.Read);
                    foreach (System.IO.Compression.ZipArchiveEntry entry in cfFile.Entries)
                    {
                        if (entry.Name.ToUpper().EndsWith(".XML"))
                        {
                            System.IO.Compression.ZipArchiveEntry zipEntry = cfFile.GetEntry(entry.Name);

                            using (System.IO.StreamReader sr = new System.IO.StreamReader(zipEntry.Open()))
                            {
                                // Handle XML file
                                //var xml = XDocument.Load(fileDialog.FileName);
                                var xml = XDocument.Parse(sr.ReadToEnd());

                                IEnumerable <XElement> waypoints = xml.Root.Descendants("Waypoints").Elements();
                                foreach (var wp in waypoints)
                                {
                                    Console.WriteLine(wp);

                                    string xmlName = wp.Element("Name").Value;
                                    string xmlLat  = wp.Element("Lat").Value;
                                    string xmlLon  = wp.Element("Lon").Value;
                                    string xmlAlt  = wp.Element("Altitude").Value;

                                    //Console.WriteLine(xmlLat);
                                    //Console.WriteLine(xmlLon);
                                    //Console.WriteLine(xmlAlt);

                                    DDMCoord lat = new DDMCoord();
                                    DDMCoord lon = new DDMCoord();

                                    lat.fromDD(double.Parse(xmlLat, System.Globalization.CultureInfo.InvariantCulture));
                                    lon.fromDD(double.Parse(xmlLon, System.Globalization.CultureInfo.InvariantCulture));

                                    // Crate new Coordinate
                                    Coordinate tempCoord = new Coordinate();
                                    tempCoord.id         = newCoordId.Text;
                                    tempCoord.name       = xmlName;
                                    tempCoord.latitude   = string.Format("2{0:D2}{1:D2}{2:D3}", lat.deg, (int)lat.dec, (int)((lat.dec - (int)lat.dec) * 1000));
                                    tempCoord.longditude = string.Format("6{0:D3}{1:D2}{2:D3}", lon.deg, (int)lon.dec, (int)((lon.dec - (int)lon.dec) * 1000));
                                    tempCoord.elevation  = string.Format("{0:F0}", xmlAlt);

                                    // Add coordinate to the DataGrid
                                    DataGridCoords.Items.Add(tempCoord);

                                    // Autoincrement the ID
                                    newCoordId.Text = Convert.ToString(Convert.ToInt16(newCoordId.Text) + 1);
                                }
                            }
                        }
                    }
                }
                else if (fileDialog.SafeFileName.EndsWith("json"))
                // Handle JSON file (From mdc.hoelweb.com)
                {
                    using (JsonDocument missionJson = JsonDocument.Parse(File.ReadAllText(fileDialog.FileName), new JsonDocumentOptions {
                        AllowTrailingCommas = true
                    }))
                    {
                        var waypoints = missionJson.RootElement.GetProperty("waypoints").EnumerateArray();

                        foreach (JsonElement wp in waypoints)
                        {
                            //Console.WriteLine(wp.GetProperty("wp"));

                            string wpName = wp.GetProperty("wp").GetString();
                            string wpLat  = wp.GetProperty("lat").GetString();
                            string wpLon  = wp.GetProperty("lon").GetString();
                            string wpAlt  = wp.GetProperty("alt").GetString();

                            DDMCoord lat = new DDMCoord();
                            DDMCoord lon = new DDMCoord();

                            lat.fromDD(double.Parse(wpLat, System.Globalization.CultureInfo.InvariantCulture));
                            lon.fromDD(double.Parse(wpLon, System.Globalization.CultureInfo.InvariantCulture));

                            // Create Coordinate
                            Coordinate tempCoord = new Coordinate();
                            tempCoord.id         = newCoordId.Text;
                            tempCoord.name       = wpName;
                            tempCoord.latitude   = string.Format("2{0:D2}{1:D2}{2:D3}", lat.deg, (int)lat.dec, (int)((lat.dec - (int)lat.dec) * 1000));
                            tempCoord.longditude = string.Format("6{0:D3}{1:D2}{2:D3}", lon.deg, (int)lon.dec, (int)((lon.dec - (int)lon.dec) * 1000));
                            tempCoord.elevation  = string.Format("{0:F0}", wpAlt);

                            //Console.WriteLine(tempCoord.latitude);
                            //Console.WriteLine(tempCoord.longditude);
                            //Console.WriteLine(tempCoord.elevation);

                            // Add coordinate to the DataGrid
                            DataGridCoords.Items.Add(tempCoord);

                            // Autoincrement the ID
                            newCoordId.Text = Convert.ToString(Convert.ToInt16(newCoordId.Text) + 1);
                        }
                    }
                }
            }
        }
コード例 #22
0
        public bool InvokeMasterlistupdate(ref string message)
        {
            try
            {
                HtmlWeb      hw          = new HtmlWeb();
                HtmlDocument doc         = hw.Load(ConfigurationSettings.AppSettings["CSCAMasterlist"]);
                string       relativeUrl = string.Empty;
                foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
                {
                    string href = link.Attributes["href"].Value;
                    if (href.Contains("GermanMasterList.zip"))
                    {
                        relativeUrl = href;
                        break;
                    }
                }
                if (relativeUrl == "")
                {
                    message = "No valid url with CSCA found";
                    return(false);
                }
                else
                {
                    string aboluteUrl = "https://bsi.bund.de" + relativeUrl;
                    using (WebClient client = new WebClient())
                    {
                        client.DownloadFile(aboluteUrl, ConfigurationSettings.AppSettings["JavaReaderPath"] + "CSCAMasterlist.zip");
                        callback.CSCADownloaded("CSCAMasterlist.zip");
                    }

                    System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(new FileStream(ConfigurationSettings.AppSettings["JavaReaderPath"] + "CSCAMasterlist.zip", FileMode.Open), System.IO.Compression.ZipArchiveMode.Read);
                    foreach (System.IO.Compression.ZipArchiveEntry zae in zip.Entries)
                    {
                        System.IO.Compression.DeflateStream ds = (System.IO.Compression.DeflateStream)zae.Open();

                        MemoryStream ms = new MemoryStream();
                        ds.CopyTo(ms);

                        File.WriteAllBytes(ConfigurationSettings.AppSettings["JavaReaderPath"] + "CSCAMasterlist.ml", ms.ToArray());
                        callback.CSCAUnzipped("CSCAMasterlist.ml");
                        break;
                    }

                    bool res = ParseMasterlist();
                    if (res)
                    {
                        callback.CSCAParsed("masterlist-content-current.data");
                        message = "Certificates extracted";
                    }
                    else
                    {
                        message = "Error extracting certificates";
                    }

                    return(true);
                }
            }
            catch (Exception ex)
            {
                message = "Error updating masterlist: " + ex.Message;
                return(false);
            }
        }
コード例 #23
0
        public void DoSetup()
        {
            string vmdir    = MainDir;
            string datadir  = MainDir;
            string modeldir = MainDir;
            string vmns     = MainNs + ".ViewModels";
            string datans   = MainNs;
            string modelns  = MainNs;

            if (ProjectType == ProjectTypeEnum.Single)
            {
                Directory.CreateDirectory($"{MainDir}\\Models");
                Directory.CreateDirectory($"{MainDir}\\ViewModels\\HomeVMs");
                vmdir = MainDir + "\\ViewModels";
            }
            else
            {
                Directory.CreateDirectory($"{MainDir}.ViewModel\\HomeVMs");
                Directory.CreateDirectory($"{MainDir}.Model");
                Directory.CreateDirectory($"{MainDir}.DataAccess");
                vmdir    = MainDir + ".ViewModel";
                datadir  = MainDir + ".DataAccess";
                modeldir = MainDir + ".Model";
                vmns     = MainNs + ".ViewModel";
                datans   = MainNs + ".DataAccess";
                modelns  = MainNs + ".Model";
                File.WriteAllText($"{modeldir}\\{modelns}.csproj", GetResource("Proj.txt"));
                File.WriteAllText($"{vmdir}\\{vmns}.csproj", GetResource("Proj.txt"));
                File.WriteAllText($"{datadir}\\{datans}.csproj", GetResource("Proj.txt"));
            }
            Directory.CreateDirectory($"{MainDir}\\Areas");
            Directory.CreateDirectory($"{MainDir}\\Controllers");
            Directory.CreateDirectory($"{MainDir}\\Views\\Home");
            Directory.CreateDirectory($"{MainDir}\\Views\\Login");
            Directory.CreateDirectory($"{MainDir}\\Views\\Shared");
            Directory.CreateDirectory($"{MainDir}\\wwwroot");

            File.WriteAllText($"{MainDir}\\appsettings.json", GetResource("Appsettings.txt")
                              .Replace("$cs$", CS ?? "")
                              .Replace("$dbtype$", DbType.ToString())
                              .Replace("$cookiepre$", CookiePre ?? "")
                              .Replace("$enablelog$", EnableLog.ToString().ToLower())
                              .Replace("$logexception$", LogExceptionOnly.ToString().ToLower())
                              .Replace("$rpp$", Rpp == null ? "" : Rpp.ToString())
                              .Replace("$filemode$", FileMode.ToString())
                              .Replace("$uploaddir$", UploadDir ?? "")
                              );
            File.WriteAllText($"{datadir}\\DataContext.cs", GetResource("DataContext.txt").Replace("$ns$", datans));
            File.WriteAllText($"{MainDir}\\Controllers\\HomeController.cs", GetResource("HomeController.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));
            File.WriteAllText($"{MainDir}\\Controllers\\LoginController.cs", GetResource("LoginController.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));
            File.WriteAllText($"{MainDir}\\Views\\_ViewStart.cshtml", GetResource("ViewStart.txt"));
            File.WriteAllText($"{MainDir}\\Views\\Home\\Index.cshtml", GetResource("home.Index.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));
            File.WriteAllText($"{MainDir}\\Views\\Login\\ChangePassword.cshtml", GetResource("home.ChangePassword.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));
            File.WriteAllText($"{MainDir}\\Views\\Home\\Header.cshtml", GetResource("home.Header.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));
            File.WriteAllText($"{MainDir}\\Views\\Login\\Login.cshtml", GetResource("home.Login.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));
            File.WriteAllText($"{MainDir}\\Views\\Home\\Menu.cshtml", GetResource("home.Menu.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));
            File.WriteAllText($"{MainDir}\\Views\\Home\\PIndex.cshtml", GetResource("home.PIndex.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));
            File.WriteAllText($"{vmdir}\\HomeVMs\\ChangePasswordVM.cs", GetResource("vms.ChangePasswordVM.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));
            File.WriteAllText($"{vmdir}\\HomeVMs\\IndexVM.cs", GetResource("vms.IndexVM.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));
            File.WriteAllText($"{vmdir}\\HomeVMs\\LoginVM.cs", GetResource("vms.LoginVM.txt").Replace("$ns$", MainNs).Replace("$vmns$", vmns));

            if (UI == UIEnum.LayUI)
            {
                File.WriteAllText($"{MainDir}\\Views\\Shared\\_Layout.cshtml", GetResource("layui.Layout.txt").Replace("$ns$", MainNs));
                File.WriteAllText($"{MainDir}\\Views\\Shared\\_PLayout.cshtml", GetResource("layui.PLayout.txt").Replace("$ns$", MainNs));
                File.WriteAllText($"{MainDir}\\Program.cs", GetResource("layui.Program.txt").Replace("$ns$", MainNs));
                File.WriteAllText($"{MainDir}\\Views\\_ViewImports.cshtml", GetResource("layui.ViewImports.txt"));
                File.WriteAllText($"{MainDir}\\Areas\\_ViewImports.cshtml", GetResource("layui.ViewImports.txt"));
                Assembly assembly = Assembly.GetExecutingAssembly();
                var      sr       = assembly.GetManifestResourceStream($"WalkingTec.Mvvm.Mvc.SetupFiles.layui.layui.zip");
                System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(sr);
                foreach (var entry in zip.Entries)
                {
                    if (entry.FullName.EndsWith("/"))
                    {
                        Directory.CreateDirectory($"{MainDir}\\wwwroot\\{entry.FullName}");
                    }
                    else
                    {
                        var f = File.OpenWrite($"{MainDir}\\wwwroot\\{entry.FullName}");
                        var z = entry.Open();
                        z.CopyTo(f);
                        f.Flush();
                        f.Dispose();
                        z.Dispose();
                    }
                }
                sr.Dispose();
            }
            if (ProjectType == ProjectTypeEnum.Single)
            {
                var proj = File.ReadAllText($"{MainDir}\\{MainNs}.csproj");
                if (proj.IndexOf("WalkingTec.Mvvm.TagHelpers.LayUI") < 0)
                {
                    proj = proj.Replace("</Project>", $@"
  <ItemGroup>
    <PackageReference Include=""WalkingTec.Mvvm.TagHelpers.LayUI"" Version=""{version}"" />
    <PackageReference Include=""WalkingTec.Mvvm.Mvc.Admin"" Version=""{version}"" />
  </ItemGroup >
</Project>
");
                    File.WriteAllText($"{MainDir}\\{MainNs}.csproj", proj);
                }
            }
            if (ProjectType == ProjectTypeEnum.Multi)
            {
                var proj = File.ReadAllText($"{MainDir}\\{MainNs}.csproj");
                if (proj.IndexOf("WalkingTec.Mvvm.TagHelpers.LayUI") < 0)
                {
                    proj = proj.Replace("</Project>", $@"
  <ItemGroup>
    <PackageReference Include=""WalkingTec.Mvvm.TagHelpers.LayUI"" Version=""{version}"" />
    <PackageReference Include=""WalkingTec.Mvvm.Mvc.Admin"" Version=""{version}"" />
    <ProjectReference Include=""..\{modelns}\{modelns}.csproj"" />
    <ProjectReference Include=""..\{datans}\{datans}.csproj"" />
    <ProjectReference Include=""..\{vmns}\{vmns}.csproj"" />
 </ItemGroup >
</Project>
");
                    File.WriteAllText($"{MainDir}\\{MainNs}.csproj", proj);
                }
                //修改modelproject
                var modelproj = File.ReadAllText($"{modeldir}\\{modelns}.csproj");
                if (modelproj.IndexOf("WalkingTec.Mvvm.Core") < 0)
                {
                    modelproj = modelproj.Replace("</Project>", $@"
  <ItemGroup>
    <PackageReference Include=""WalkingTec.Mvvm.Core"" Version=""{version}"" />
  </ItemGroup >
</Project>
");
                    File.WriteAllText($"{modeldir}\\{modelns}.csproj", modelproj);
                }
                //修改dataproject
                var dataproj = File.ReadAllText($"{datadir}\\{datans}.csproj");
                if (dataproj.IndexOf($"{modelns}.csproj") < 0)
                {
                    dataproj = dataproj.Replace("</Project>", $@"
  <ItemGroup>
    <ProjectReference Include=""..\{modelns}\{modelns}.csproj"" />
  </ItemGroup >
</Project>
");
                    File.WriteAllText($"{datadir}\\{datans}.csproj", dataproj);
                }
                //修改viewmodelproject
                var vmproj = File.ReadAllText($"{vmdir}\\{vmns}.csproj");
                if (vmproj.IndexOf($"{modelns}.csproj") < 0)
                {
                    vmproj = vmproj.Replace("</Project>", $@"
  <ItemGroup>
    <ProjectReference Include=""..\{modelns}\{modelns}.csproj"" />
  </ItemGroup >
</Project>
");
                    File.WriteAllText($"{vmdir}\\{vmns}.csproj", vmproj);
                }
                var solution = File.ReadAllText($"{Directory.GetParent(MainDir)}\\{MainNs}.sln");
                if (solution.IndexOf($"{modelns}.csproj") < 0)
                {
                    Guid g1 = Guid.NewGuid();
                    Guid g2 = Guid.NewGuid();
                    Guid g3 = Guid.NewGuid();
                    solution = solution.Replace("EndProject", $@"EndProject
Project(""{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}"") = ""{modelns}"", ""{modelns}\{modelns}.csproj"", ""{{{g1}}}""
EndProject
Project(""{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}"") = ""{datans}"", ""{datans}\{datans}.csproj"", ""{{{g2}}}""
EndProject
Project(""{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}"") = ""{vmns}"", ""{vmns}\{vmns}.csproj"", ""{{{g3}}}""
EndProject
");
                    solution = solution.Replace(".Release|Any CPU.Build.0 = Release|Any CPU", $@".Release|Any CPU.Build.0 = Release|Any CPU
		{{{g1}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{{{g1}}}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{{{g1}}}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{{{g1}}}.Release|Any CPU.Build.0 = Release|Any CPU
		{{{g2}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{{{g2}}}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{{{g2}}}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{{{g2}}}.Release|Any CPU.Build.0 = Release|Any CPU
		{{{g3}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{{{g3}}}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{{{g3}}}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{{{g3}}}.Release|Any CPU.Build.0 = Release|Any CPU"        );
                    File.WriteAllText($"{Directory.GetParent(MainDir)}\\{MainNs}.sln", solution);
                }
            }
            if (File.Exists($"{MainDir}\\Startup.cs"))
            {
                File.Delete($"{MainDir}\\Startup.cs");
            }
        }
コード例 #24
0
            public File(string path)
            {
                using var stream = new FileStream(path, FileMode.Open);
                var archive = new System.IO.Compression.ZipArchive(stream);

                foreach (var entry in archive.Entries)
                {
                    switch (entry.FullName)
                    {
                    case "docProps/core.xml":
                    {
                        var xml = new XmlDocument();
                        xml.LoadXml(new StreamReader(entry.Open()).ReadToEnd());

                        if (xml.DocumentElement == null)
                        {
                            continue;
                        }
                        foreach (var element in xml.DocumentElement.ChildNodes)
                        {
                            if (element != null)
                            {
                                switch ((element as XmlElement)?.LocalName)
                                {
                                case "title":
                                    Title = ((XmlElement)element).InnerText;
                                    break;

                                case "creator":
                                    Author = ((XmlElement)element).InnerText;
                                    break;
                                }
                            }
                        }

                        break;
                    }

                    case "meta.xml":
                    {
                        var xml = new XmlDocument();
                        xml.LoadXml(new StreamReader(entry.Open()).ReadToEnd());

                        if (xml.DocumentElement == null)
                        {
                            continue;
                        }
                        foreach (var element in xml.DocumentElement.ChildNodes[0].ChildNodes)
                        {
                            if (element != null)
                            {
                                switch ((element as XmlElement)?.LocalName)
                                {
                                case "title":
                                    Title = (element as XmlElement).InnerText;
                                    break;

                                case "creator":
                                    Author = (element as XmlElement).InnerText;
                                    break;
                                }
                            }
                        }

                        break;
                    }
                    }
                }
            }
コード例 #25
0
 public static System.IO.Compression.ZipArchiveEntry CreateEntryFromFile(this System.IO.Compression.ZipArchive destination, string sourceFileName, string entryName, System.IO.Compression.CompressionLevel compressionLevel)
 {
     throw null;
 }
コード例 #26
0
ファイル: DatabaseIFC.cs プロジェクト: TomH22/GeometryGymIFC
        public bool WriteFile(string filename)
        {
            StreamWriter sw = null;


            FolderPath = Path.GetDirectoryName(filename);
            string fn = Path.GetFileNameWithoutExtension(filename);

            char[] chars = Path.GetInvalidFileNameChars();
            foreach (char c in chars)
            {
                fn = fn.Replace(c, '_');
            }
            FileName = Path.Combine(FolderPath, fn + Path.GetExtension(filename));
            if (filename.EndsWith("xml"))
            {
                WriteXMLFile(FileName);
                return(true);
            }
#if (!NOIFCJSON)
            else if (FileName.EndsWith("json"))
            {
                ToJSON(FileName);
                return(true);
            }
#endif
#if (!NOIFCZIP)
            bool zip = FileName.EndsWith(".ifczip");
            System.IO.Compression.ZipArchive za = null;
            if (zip)
            {
                if (System.IO.File.Exists(FileName))
                {
                    System.IO.File.Delete(FileName);
                }
                za = System.IO.Compression.ZipFile.Open(FileName, System.IO.Compression.ZipArchiveMode.Create);
                System.IO.Compression.ZipArchiveEntry zae = za.CreateEntry(System.IO.Path.GetFileNameWithoutExtension(FileName) + ".ifc");
                sw = new StreamWriter(zae.Open());
            }
            else
#endif
            sw = new StreamWriter(FileName);
            CultureInfo current = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            sw.Write(getHeaderString(filename) + "\r\n");
            foreach (BaseClassIfc e in this)
            {
                if (e != null)
                {
                    try
                    {
                        string str = e.ToString();
                        if (!string.IsNullOrEmpty(str))
                        {
                            sw.WriteLine(str);
                        }
                    }
                    catch (Exception) { }
                }
            }
            sw.Write(getFooterString());
            sw.Close();
            Thread.CurrentThread.CurrentUICulture = current;
#if (!NOIFCZIP)
            if (zip)
            {
                za.Dispose();
            }
#endif
            return(true);
        }
コード例 #27
0
        static void Main(string[] args)
        {
            string searchPattern = "*LI.jpg";
            string video         = ".mp4";

            string folder = null;

            if (args.Length == 0)
            {
                Console.WriteLine("No directory given to process" + System.Environment.NewLine);

                Console.WriteLine("First argument is the folder i.e. \"c:\\somewhere with spaces\\\"");
                Console.WriteLine("Second optional agument is the search pattern, i.e. default of " + searchPattern);
                Console.WriteLine("Third optional agument is the search pattern for video file, where file ends with i.e. default of " + video);
                Console.WriteLine(System.Environment.NewLine);
                Console.WriteLine("You can 1) type (or paste) in a folder now - without quotes and press <ENTER>");
                Console.WriteLine("        2) press <ENTER> to exit");
                var possibleFolder = Console.ReadLine();
                if (System.IO.Directory.Exists(possibleFolder))
                {
                    folder = possibleFolder;
                }
                else
                {
                    return;
                }
            }
            else
            {
                folder = args[0];
                if (args.Length > 1)
                {
                    searchPattern = args[1];
                }
                if (args.Length > 2)
                {
                    video = args[2];
                }
            }
            var imageFiles = System.IO.Directory.GetFiles(folder, searchPattern);

            Console.WriteLine("poo supprise now lets get going with the number of files found " + imageFiles.Length);

            foreach (var imageFile in imageFiles)
            {
                Console.WriteLine("Processing " + imageFile);
                //var zipFile = Ionic.Zip.ZipFile.Read(imageFile);
                try
                {
                    using (var zipfs = System.IO.File.OpenRead(imageFile))
                    {
                        System.Console.Write("opened file " + imageFile);
                        var z = new System.IO.Compression.ZipArchive(zipfs);
                        foreach (var item in z.Entries)
                        {
                            if (item.Name.EndsWith(video))
                            {
                                System.Console.Write(" found video");
                                using (var zm4 = item.Open())
                                {
                                    var newFile = System.IO.Path.Combine(folder, System.IO.Path.GetFileNameWithoutExtension(imageFile) + video);
                                    using (var fs = System.IO.File.OpenWrite(newFile))
                                    {
                                        fs.Seek(0, System.IO.SeekOrigin.Begin);
                                        System.Console.Write(" unzipping");
                                        zm4.CopyTo(fs);
                                    }
                                    System.Console.WriteLine(" Success");
                                }
                                continue;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("not " + e.Message);
                }
            }
        }
コード例 #28
0
        public static ActionResult InstallFfmpeg(Session session)
        {
            //System.Diagnostics.Debugger.Launch();

            const string actionName = "InstallFfmpegAction";

            bool   showUi     = false;
            string tempFolder = null;

            try
            {
                session.Log("Begin InstallFfmpeg");

                showUi = 5 >= int.Parse(session.CustomActionData["UILevel"]);

                tempFolder = session.CustomActionData["TEMPFOLDER"].TrimEnd('/', '\\') + "\\" + Path.GetRandomFileName();

                string afxFfmpegFolder = session.CustomActionData["AFX_FFMPEGFOLDER"].TrimEnd('/', '\\');
                string downloadUrl     = session.CustomActionData["AFX_FFMPEGURL"];
                string targetHash      = session.CustomActionData["AFX_FFMPEGSUM"];
                bool   is64BitOs       = System.Environment.Is64BitOperatingSystem;

                string locInstallFfmpegConnect           = session.CustomActionData["InstallFfmpegConnect"];
                string locInstallFfmpegConnect_Template  = session.CustomActionData["InstallFfmpegConnect_Template"];
                string locInstallFfmpegDownload          = session.CustomActionData["InstallFfmpegDownload"];
                string locInstallFfmpegDownload_Template = session.CustomActionData["InstallFfmpegDownload_Template"];
                string locInstallFfmpegChecksum          = session.CustomActionData["InstallFfmpegChecksum"];
                string locInstallFfmpegChecksum_Template = session.CustomActionData["InstallFfmpegChecksum_Template"];
                string locInstallFfmpegExtract           = session.CustomActionData["InstallFfmpegExtract"];
                string locInstallFfmpegExtract_Template  = session.CustomActionData["InstallFfmpegExtract_Template"];

                string fileName = "ffmpeg.zip";

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

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                Progress progress = new Progress(session);

                if (MessageResult.Cancel == progress.Init(actionName, locInstallFfmpegConnect, locInstallFfmpegConnect_Template, 1))
                {
                    return(ActionResult.UserExit);
                }

                System.Net.WebRequest.DefaultWebProxy             = System.Net.WebRequest.GetSystemWebProxy();
                System.Net.WebRequest.DefaultWebProxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downloadUrl);

                long downloadSize = 0;

                using (FileStream download = new FileStream(tempFolder + "\\" + fileName, FileMode.Create))
                {
                    int    read       = 0;
                    byte[] buffer     = new byte[1000];
                    long   length     = -1;
                    long   lengthRead = 0;

                    WebResponse response = request.GetResponse();

                    length = response.ContentLength;

                    if (MessageResult.Cancel == progress.SetAbsTick(1, 1, 1))
                    {
                        return(ActionResult.UserExit);
                    }

                    if (MessageResult.Cancel == progress.Init(actionName, locInstallFfmpegDownload, locInstallFfmpegDownload_Template, ticksFfmpegDownload))
                    {
                        return(ActionResult.UserExit);
                    }

                    using (Stream stream = response.GetResponseStream())
                    {
                        while ((read = stream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            lengthRead += read;
                            download.Write(buffer, 0, read);

                            if (0 < length && length <= int.MaxValue)
                            {
                                progress.SetAbsTick((long)Math.Round(lengthRead * (double)ticksFfmpegDownload / length), lengthRead, length);
                            }
                        }

                        stream.Close();
                    }

                    download.Close();

                    if (MessageResult.Cancel == progress.SetAbsTick(ticksFfmpegDownload, lengthRead, length))
                    {
                        return(ActionResult.UserExit);
                    }

                    downloadSize = lengthRead;
                }

                //

                if (MessageResult.Cancel == progress.Init(actionName, locInstallFfmpegChecksum, locInstallFfmpegChecksum_Template, ticksFfmpegChecksum))
                {
                    return(ActionResult.UserExit);
                }

                if (null != targetHash)
                {
                    using (FileStream fs = File.OpenRead(tempFolder + "\\" + fileName))
                    {
                        HashAlgorithm sha512 = new SHA512CryptoServiceProvider();
                        string        hash   = BitConverter.ToString(sha512.ComputeHash(fs)).ToLower().Replace("-", "");
                        if (0 != hash.CompareTo(targetHash))
                        {
                            throw new ApplicationException("SHA512 hash mismatch.");
                        }
                    }
                }

                if (MessageResult.Cancel == progress.SetAbsTick(ticksFfmpegDownload, downloadSize, downloadSize))
                {
                    return(ActionResult.UserExit);
                }

                //

                using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(new FileStream(
                                                                                                       tempFolder + "\\" + fileName,
                                                                                                       FileMode.Open), System.IO.Compression.ZipArchiveMode.Read))
                {
                    int entryNr = 0;

                    if (MessageResult.Cancel == progress.Init(actionName, locInstallFfmpegExtract, locInstallFfmpegExtract_Template, ticksFfmpegExctract))
                    {
                        return(ActionResult.UserExit);
                    }

                    foreach (System.IO.Compression.ZipArchiveEntry entry in zip.Entries)
                    {
                        // Strip out root directory

                        string[] split = entry.FullName.Trim(new char[] { '/', '\\' }).Split(new char[] { '/', '\\' });

                        if (1 <= split.Length)
                        {
                        }
                        else
                        {
                            throw new ApplicationException("Unexpected ZIP contents.");
                        }

                        string orgName      = string.Join("\\", split, 1, split.Length - 1);
                        string fullName     = afxFfmpegFolder + "\\" + orgName;
                        string fullPath     = Path.GetFullPath(fullName);
                        string parentFolder = 2 <= split.Length ? string.Join("\\", split, 1, split.Length - 2) : "";
                        string ownName      = string.Join("\\", split, split.Length - 1, 1);

                        if (!(fullPath.IndexOf(afxFfmpegFolder) == 0))
                        {
                            throw new ApplicationException("Bogous ZIP directory structure.");
                        }

                        bool isFile = !(null == entry.Name || 0 == entry.Name.Length);

                        if (isFile)
                        {
                            using (Stream entryStream = entry.Open())
                            {
                                using (FileStream outEntryStream = new FileStream(fullPath, FileMode.Create))
                                {
                                    int    read       = 0;
                                    byte[] buffer     = new byte[1000];
                                    long   length     = entry.Length;
                                    long   lengthRead = 0;

                                    while ((read = entryStream.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        lengthRead += read;
                                        outEntryStream.Write(buffer, 0, read);
                                    }

                                    outEntryStream.Close();
                                }

                                entryStream.Close();
                            }
                        }
                        else
                        {
                            if (!Directory.Exists(fullPath))
                            {
                                Directory.CreateDirectory(fullPath);
                            }
                        }

                        ++entryNr;

                        if (MessageResult.Cancel == progress.SetAbsTick((long)Math.Round(entryNr * (double)ticksFfmpegExctract / zip.Entries.Count), entryNr, zip.Entries.Count))
                        {
                            return(ActionResult.UserExit);
                        }
                    }

                    if (MessageResult.Cancel == progress.SetAbsTick(ticksFfmpegExctract, entryNr, zip.Entries.Count))
                    {
                        return(ActionResult.UserExit);
                    }
                }

                return(ActionResult.Success);
            }
            catch (Exception e)
            {
                session.Log("Error: " + e.ToString());
            }
            finally
            {
                try
                {
                    if (null != tempFolder)
                    {
                        Directory.Delete(tempFolder, true);
                    }
                }
                catch (Exception e2)
                {
                    session.Log("Error deleting temporary ffmpeg directory: " + e2.ToString());
                }
            }

            return(ActionResult.Failure);
        }
コード例 #29
0
        public string BuildFullGamePath(string GamesFolder, string GamePath)
        {
            string path      = string.Empty;
            string extension = string.Empty;

            // check whether relative or absolute path has been set in the database for this game
            if (RomPath.StartsWith("."))
            {
                // path is relative (rom autoimported from defined path) - build path
                path = GamesFolder + GamePath.TrimStart('.');
            }
            else
            {
                // rom or disk has been manually added with full path - return just full path
                path = GamePath;
            }

            // create cache directory if it does not exist
            string cacheDir = AppDomain.CurrentDomain.BaseDirectory + "Data\\Cache";

            Directory.CreateDirectory(cacheDir);

            /* now do archive processing */
            if (path.Contains("*/"))
            {
                // this is an archive file with a direct reference to a ROM inside
                string[] arr         = path.Split(new string[] { "*/" }, StringSplitOptions.None);
                string   archivePath = arr[0];
                string   archiveFile = arr[1];

                // copy specific rom from archive to cache folder and get cache rom path
                string cacheRom = Archive.ExtractFile(archivePath, archiveFile, cacheDir); //Archiving.SetupArchiveChild(archivePath, archiveFile, cacheDir);

                if (cacheRom != string.Empty)
                {
                    return(ParseSMD(cacheRom, cacheDir));
                }
            }
            else if (path.ToLower().Contains(".7z") || path.ToLower().Contains(".zip"))
            {
                // This is a standard archive with no defined link
                extension = System.IO.Path.GetExtension(path).ToLower();

                if (extension == ".zip") //zip
                {
                    // this should be a zip file with a single rom inside - pass directly to mednafen as is
                    using (System.IO.Compression.ZipArchive ar = System.IO.Compression.ZipFile.OpenRead(path))
                    {
                        foreach (System.IO.Compression.ZipArchiveEntry entry in ar.Entries)
                        {
                            if (entry.FullName.EndsWith(".smd", StringComparison.OrdinalIgnoreCase))
                            {
                                entry.Archive.ExtractToDirectory(cacheDir, true);
                                return(ParseSMD(Path.Combine(cacheDir, entry.FullName), cacheDir));
                            }
                        }
                    }

                    return(path);
                }

                else if (extension == ".7z")
                {
                    /* archive detected - extract contents to cache directory and modify path variable accordingly
                     * this is a legacy option really - in case people have a single rom in a .7z file in their library that
                     * has not been directly referenced in the gamepath */

                    // inspect the archive
                    Archive arch = new Archive(path);
                    var     res  = arch.ProcessArchive(null);

                    // iterate through
                    List <CompressionResult> resList = new List <CompressionResult>();
                    foreach (var v in res.Results)
                    {
                        if (GSystem.IsFileAllowed(v.RomName, SystemId))
                        {
                            resList.Add(v);
                        }
                    }

                    if (resList.Count == 0)
                    {
                        return(path);
                    }

                    // there should only be one result - take the first one
                    var resFinal = resList.FirstOrDefault();

                    // extract the rom to the cache
                    string cacheFile = Archive.ExtractFile(path, resFinal.InternalPath, cacheDir);

                    /*
                     * // check whether file already exists in cache
                     * string cacheFile = cacheDir + "\\" + resFinal.FileName;
                     * if (File.Exists(cacheFile))
                     * {
                     *  // file exists - check size
                     *  long length = new System.IO.FileInfo(cacheFile).Length;
                     *
                     *  if (length != filesize)
                     *  {
                     *      arch.ExtractArchive(cacheDir);
                     *  }
                     * }
                     * else
                     * {
                     *  // extract contents of archive to cache folder
                     *  arch.ExtractArchive(cacheDir);
                     * }
                     */

                    // return the new path to the rom
                    return(ParseSMD(cacheFile, cacheDir));
                }

                else if (extension == ".zip") //zip
                {
                    // this should be a zip file with a single rom inside - pass directly to mednafen as is (unless its an smd file)

                    using (System.IO.Compression.ZipArchive ar = System.IO.Compression.ZipFile.OpenRead(path))
                    {
                        foreach (System.IO.Compression.ZipArchiveEntry entry in ar.Entries)
                        {
                            if (entry.FullName.EndsWith(".smd", StringComparison.OrdinalIgnoreCase))
                            {
                                entry.Archive.ExtractToDirectory(cacheDir, true);
                                return(ParseSMD(Path.Combine(cacheDir, entry.FullName), cacheDir));
                            }
                        }
                    }

                    return(path);
                }
            }


            return(ParseSMD(path, cacheDir));
        }
コード例 #30
0
        static public void Main(String[] args)
        {
            // If there is an error or the help command is passed
            if (ParseArguments(args) == false)
            {
                //Show the help message
                OutputHelp();
                return;
            }

            XboxLiveTrace.TraceAnalyzer analyzer = new TraceAnalyzer(m_isInternal, m_allEndpoints);

            try
            {
                analyzer.OutputDirectory = m_outputDirectory;
                analyzer.CustomUserAgent = m_customUserAgent;

                analyzer.LoadData(m_dataFilePath);

                if (String.IsNullOrEmpty(m_rulesFilePath) == false)
                {
                    analyzer.LoadRules(m_rulesFilePath);
                }

                analyzer.LoadDefaultRules();

                if (m_defaults)
                {
                    analyzer.LoadDefaultURIMap();
                    analyzer.RunUriConverterOnData();

                    analyzer.AddRule(new StatsRecorder {
                        Endpoint = "*"
                    });
                    analyzer.AddRule(new CallRecorder {
                        Endpoint = "*"
                    });
                    analyzer.AddRule(new XR049Rule {
                        Endpoint = "userpresence.xboxlive.com"
                    });
                    analyzer.AddReport(new PerEndpointJsonReport(m_jsonOnly));
                    analyzer.AddReport(new CallReport(m_jsonOnly));
                    analyzer.AddReport(new StatsReport(m_jsonOnly));
                    analyzer.AddReport(new CertWarningReport(m_jsonOnly));

                    if (!m_jsonOnly)
                    {
                        String tempZipPath = Path.Combine(m_outputDirectory, "html-report.zip");

                        var assembly = Assembly.GetExecutingAssembly();
                        using (var htmlReport = assembly.GetManifestResourceStream("XboxLiveTrace.html-report.zip"))
                        {
                            using (var outputFile = new System.IO.Compression.ZipArchive(htmlReport))
                            {
                                foreach (var entry in outputFile.Entries.Where(e => e.Name.Contains('.')))
                                {
                                    bool create_subDir = analyzer.ConsoleList.Count() > 1;
                                    foreach (var console in analyzer.ConsoleList)
                                    {
                                        String path = m_outputDirectory;
                                        if (create_subDir)
                                        {
                                            path = Path.Combine(path, console);
                                        }

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

                                        if (!Directory.Exists(Path.Combine(path, "css")))
                                        {
                                            Directory.CreateDirectory(Path.Combine(path, "css"));
                                        }
                                        if (!Directory.Exists(Path.Combine(path, "img")))
                                        {
                                            Directory.CreateDirectory(Path.Combine(path, "img"));
                                        }
                                        if (!Directory.Exists(Path.Combine(path, "js")))
                                        {
                                            Directory.CreateDirectory(Path.Combine(path, "js"));
                                        }

                                        using (var temp = entry.Open())
                                        {
                                            using (var reportFile = new FileStream(Path.Combine(path, entry.FullName), FileMode.Create))
                                            {
                                                temp.CopyTo(reportFile);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        System.IO.File.Delete(tempZipPath);
                    }
                }

                analyzer.LoadPlugins("plugins");

                foreach (var report in m_reports)
                {
                    analyzer.AddReport(report, m_outputDirectory);
                }

                analyzer.Run();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                //Show the help message
                OutputHelp();
                return;
            }
        }
コード例 #31
0
 public static void ExtractToDirectory(this System.IO.Compression.ZipArchive source, string destinationDirectoryName)
 {
 }
コード例 #32
0
        public HttpResponseMessage Upload()
        {
            HttpContext context = HttpContext.Current;

            // Verify Folder
            var folderPath = string.Format("{0}\\Albatros\\Balises\\{1}\\Upload", PortalSettings.HomeDirectoryMapPath, UserInfo.UserID);
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            // Save File
            HttpPostedFile file = context.Request.Files[0];
            if (file.FileName.ToLower().EndsWith(".igc"))
            {
                var igcText = "";
                using (var s = new StreamReader(file.InputStream))
                {
                    igcText = s.ReadToEnd();
                }
                return Request.CreateResponse(HttpStatusCode.OK, IgcController.AddFlightToUser(
                        PortalSettings.PortalId,
                        UserInfo.UserID,
                        igcText,
                        BalisesModuleContext.Settings.BeaconPassDistanceMeters));
            }
            else if (file.FileName.ToLower().EndsWith(".zip"))
            {
                var res = new List<Flight>();
                using (var zip = new System.IO.Compression.ZipArchive(file.InputStream))
                {
                    foreach (var entry in zip.Entries)
                    {
                        if (entry.Name.ToLower().EndsWith(".igc") & entry.Length > 0)
                        {
                            using (var stream = entry.Open())
                            {
                                var igcText = "";
                                using (var s = new StreamReader(stream))
                                {
                                    igcText = s.ReadToEnd();
                                }
                                try
                                {
                                    res.Add(IgcController.AddFlightToUser(
                                        PortalSettings.PortalId,
                                        UserInfo.UserID,
                                        igcText,
                                        BalisesModuleContext.Settings.BeaconPassDistanceMeters));
                                }
                                catch (System.Exception)
                                {
                                }
                            }
                        }
                    }
                }
                return Request.CreateResponse(HttpStatusCode.OK, res);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, "Bad file");
            }
        }