Пример #1
0
        public MemoryStream GetCurrentStateAsZip(string courseSubdirectoryInRepo = null)
        {
            log.Info($"Start load '{repoDirName}' to zip");
            var dir = reposBaseDir.GetSubdirectory(repoDirName).FullName;

            dir = courseSubdirectoryInRepo == null ? dir : Path.Combine(dir, courseSubdirectoryInRepo);
            var zip = ZipUtils.CreateZipFromDirectory(new List <string> {
                dir
            }, new List <string> {
                ".git/"
            }, null, Encoding.UTF8);

            log.Info($"Successfully load '{repoDirName}' to zip");
            return(zip);
        }
Пример #2
0
        public NameValueCollection SiteTemplateDownload(string downloadUrl, string directoryName, string userKeyPrefix)
        {
            var cacheTotalCountKey   = userKeyPrefix + CacheTotalCount;
            var cacheCurrentCountKey = userKeyPrefix + CacheCurrentCount;
            var cacheMessageKey      = userKeyPrefix + CacheMessage;

            CacheUtils.Insert(cacheTotalCountKey, "5");       //存储需要的页面总数
            CacheUtils.Insert(cacheCurrentCountKey, "0");     //存储当前的页面总数
            CacheUtils.Insert(cacheMessageKey, string.Empty); //存储消息

            //返回“运行结果”和“错误信息”的字符串数组
            NameValueCollection retval;

            try
            {
                CacheUtils.Insert(cacheCurrentCountKey, "1");
                CacheUtils.Insert(cacheMessageKey, "开始下载模板压缩包,可能需要几分钟,请耐心等待");

                var filePath = PathUtility.GetSiteTemplatesPath(directoryName + ".zip");
                FileUtils.DeleteFileIfExists(filePath);
                WebClientUtils.SaveRemoteFileToLocal(downloadUrl, filePath);

                CacheUtils.Insert(cacheCurrentCountKey, "4");
                CacheUtils.Insert(cacheMessageKey, "模板压缩包下载成功,开始解压缩");

                var directoryPath = PathUtility.GetSiteTemplatesPath(directoryName);
                if (!DirectoryUtils.IsDirectoryExists(directoryPath))
                {
                    ZipUtils.UnpackFiles(filePath, directoryPath);
                }

                CacheUtils.Insert(cacheCurrentCountKey, "5");
                CacheUtils.Insert(cacheMessageKey, string.Empty);

                retval = AjaxManager.GetProgressTaskNameValueCollection("站点模板下载成功,请到站点模板管理中查看。", string.Empty);
            }
            catch (Exception ex)
            {
                retval = AjaxManager.GetProgressTaskNameValueCollection(string.Empty,
                                                                        $@"<br />下载失败!<br />{ex.Message}");
            }

            CacheUtils.Remove(cacheTotalCountKey);   //取消存储需要的页面总数
            CacheUtils.Remove(cacheCurrentCountKey); //取消存储当前的页面总数
            CacheUtils.Remove(cacheMessageKey);      //取消存储消息

            return(retval);
        }
Пример #3
0
        //加载基础信息
        private bool LoadBaseInfo()
        {
            bool hasDefFile = false;

            //在zip中加载LevelDef
            ZipInputStream zip = ZipUtils.OpenZipFile(FilePath);
            ZipEntry       theEntry;

            while ((theEntry = zip.GetNextEntry()) != null)
            {
                if (theEntry.Name == "/LevelDef.xml" || theEntry.Name == "LevelDef.xml")
                {
                    hasDefFile = true;
                    LoadLevelDefInZip(zip, theEntry);
                }
                else if (theEntry.Name == "/" + Logo || theEntry.Name == Logo)
                {
                    LoadLogoInZip(zip, theEntry);
                }
            }
            zip.Close();
            zip.Dispose();

            if (!hasDefFile)
            {
                GameLogger.Error(TAG, "加载模组包失败,未找到 LevelDef.xml");
                GameErrorManager.LastError = GameError.InitializationFailed;

                LoadStatus = GameModStatus.InitializeFailed;
                LoadError  = "未找到 ModDef.xml";

                return(false);
            }

            //检查兼容性
            if (LevelCompatibilityInfo.MinVersion > GameConst.GameBulidVersion)
            {
                GameLogger.Error(TAG, "加载模组包失败,关卡与游戏版本不兼容");
                GameErrorManager.LastError = GameError.BadMod;

                LoadStatus = GameModStatus.BadMod;
                LoadError  = "关卡与游戏版本不兼";

                return(false);
            }

            return(true);
        }
Пример #4
0
        public static Dictionary <string, EpubItem> FakeAbsolutePathIndex(XDocument doc, string ncxFileName)
        {
            var    index     = new Dictionary <string, EpubItem>();
            string ncxFolder = ncxFileName.GetZipPath();

            foreach (var e in doc.Root.Descendants(Epub.ncxNs + "content"))
            {
                string relativePath = e.Attribute("src").Value;
                string absolute     = ZipUtils.RelativePathToAbsolute(ncxFolder, relativePath);
                index[absolute] = new EpubItem()
                {
                    AbsolutePath = absolute
                };
            }
            return(index);
        }
Пример #5
0
        public NotificationData ToData(string applicationUserId)
        {
            var obj = JsonConvert.SerializeObject(this);

            var data = new NotificationData
            {
                Id                = Guid.NewGuid().ToString(),
                Created           = DateTimeOffset.UtcNow,
                ApplicationUserId = applicationUserId,
                NotificationType  = NotificationType,
                Blob              = ZipUtils.Zip(obj),
                Seen              = false
            };

            return(data);
        }
Пример #6
0
 /// <summary>
 /// Creates an <see cref="ArchiveReader"/> from a valid storage path.
 /// </summary>
 /// <param name="path">A file or folder path resolving the archive content.</param>
 /// <returns>A reader giving access to the archive's content.</returns>
 private ArchiveReader getReaderFrom(string path)
 {
     if (ZipUtils.IsZipArchive(path))
     {
         return(new ZipArchiveReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read), Path.GetFileName(path)));
     }
     if (Directory.Exists(path))
     {
         return(new LegacyDirectoryArchiveReader(path));
     }
     if (File.Exists(path))
     {
         return(new LegacyFileArchiveReader(path));
     }
     throw new InvalidFormatException($"{path} is not a valid archive");
 }
Пример #7
0
        private NotificationViewModel ToViewModel(NotificationData data)
        {
            var handler = GetHandler(data.NotificationType);

            if (handler is null)
            {
                return(null);
            }
            var notification = JsonConvert.DeserializeObject(ZipUtils.Unzip(data.Blob), handler.NotificationBlobType);
            var obj          = new NotificationViewModel {
                Id = data.Id, Created = data.Created, Seen = data.Seen
            };

            handler.FillViewModel(notification, obj);
            return(obj);
        }
Пример #8
0
        /// <summary>
        /// Creates an <see cref="ArchiveReader"/> from a stream.
        /// </summary>
        /// <param name="stream">A seekable stream containing the archive content.</param>
        /// <returns>A reader giving access to the archive's content.</returns>
        private ArchiveReader getReaderFrom(Stream stream)
        {
            if (!(stream is MemoryStream memoryStream))
            {
                // This isn't used in any current path. May need to reconsider for performance reasons (ie. if we don't expect the incoming stream to be copied out).
                memoryStream = new MemoryStream(stream.ReadAllBytesToArray());
                stream.Dispose();
            }

            if (ZipUtils.IsZipArchive(memoryStream))
            {
                return(new ZipArchiveReader(memoryStream, Path));
            }

            return(new LegacyByteArrayReader(memoryStream.ToArray(), Path));
        }
Пример #9
0
        static void Main(string[] args)
        {
            IList <SourceFile> list = new List <SourceFile>();

            list.Add(new SourceFile {
                Extension = "pdf",
                Name      = FileNameNormalizer.Normalize("N.CREDITO VENDITA_12/01/2018_877_VD"),
                FileBytes = File.ReadAllBytes(@"c:\Temp\EsCC.pdf")
            });
            list.Add(new SourceFile
            {
                Extension = "pdf",
                Name      = "pippo1/",
                FileBytes = File.ReadAllBytes(@"c:\Temp\EsFattura.pdf")
            });
            list.Add(new SourceFile
            {
                Extension = "pdf",
                Name      = "pippo2;",
                FileBytes = File.ReadAllBytes(@"c:\Temp\EsDocumentoI.pdf")
            });
            list.Add(new SourceFile
            {
                Extension = ".pdf",
                Name      = "pippo3",
                FileBytes = File.ReadAllBytes(@"c:\Temp\EsCC.pdf")
            });
            list.Add(new SourceFile
            {
                Extension = "pdf",
                Name      = "pippo4",
                FileBytes = File.ReadAllBytes(@"c:\Temp\EsFattura.pdf")
            });
            list.Add(new SourceFile
            {
                Extension = "pdf",
                Name      = "pippo5",
                FileBytes = File.ReadAllBytes(@"c:\Temp\EsDocumentoI.pdf")
            });

            var res = ZipUtils.Compress(list);

            File.WriteAllBytes(@"c:\Temp\Doc.zip", res);

            Console.WriteLine("Compressione avvenuta!");
            Console.ReadKey();
        }
Пример #10
0
        /// <inheritdoc/>
        public override List <string> GetEmptyFolders()
        {
            List <string> empties = new List <string>();

            try
            {
                Zip       zf = new Zip();
                ZipReturn zr = zf.ZipFileOpen(this.Filename, -1, true);
                if (zr != ZipReturn.ZipGood)
                {
                    throw new Exception(ZipUtils.ZipErrorMessageText(zr));
                }

                List <(string, bool)> zipEntries = new List <(string, bool)>();
                for (int i = 0; i < zf.LocalFilesCount(); i++)
                {
                    zipEntries.Add((zf.Filename(i), zf.IsDirectory(i)));
                }

                zipEntries = zipEntries.OrderBy(p => p.Item1, new NaturalReversedComparer()).ToList();
                string lastZipEntry = null;
                foreach ((string, bool)entry in zipEntries)
                {
                    // If the current is a superset of last, we skip it
                    if (lastZipEntry != null && lastZipEntry.StartsWith(entry.Item1))
                    {
                        // No-op
                    }
                    // If the entry is a directory, we add it
                    else
                    {
                        if (entry.Item2)
                        {
                            empties.Add(entry.Item1);
                        }
                        lastZipEntry = entry.Item1;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(empties);
        }
Пример #11
0
        public void ImportContentsByZipFile(ChannelInfo nodeInfo, string zipFilePath, bool isOverride, int importStart, int importCount, bool isChecked, int checkedLevel)
        {
            var siteContentDirectoryPath = PathUtils.GetTemporaryFilesPath("contents");

            DirectoryUtils.DeleteDirectoryIfExists(siteContentDirectoryPath);
            DirectoryUtils.CreateDirectoryIfNotExists(siteContentDirectoryPath);

            ZipUtils.UnpackFiles(zipFilePath, siteContentDirectoryPath);

            var tableName = ChannelManager.GetTableName(_siteInfo, nodeInfo);

            var taxis = DataProvider.ContentDao.GetMaxTaxis(tableName, nodeInfo.Id, false);

            ImportContents(nodeInfo, siteContentDirectoryPath, isOverride, taxis, importStart, importCount, isChecked, checkedLevel);

            DataProvider.ChannelDao.UpdateContentNum(_siteInfo);
        }
Пример #12
0
 void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
 {
     try
     {
         ZipUtils.UnZip(zipFile);
         DirectoryInfo di = new DirectoryInfo(unZipFolder);
         di.Attributes = FileAttributes.Hidden;
         File.Delete(zipFile);
         pbProgress.Invoke(new MethodInvoker(() => { pbProgress.Value = 100; }));
         this.Invoke(new MethodInvoker(() =>
         {
             this.DialogResult = System.Windows.Forms.DialogResult.OK;
             this.Close();
         }));
     }
     catch { }
 }
Пример #13
0
        /// <summary>
        /// Signs the provided APK using APK Signature Scheme v2 and returns the APK Signing Block containing the signature.
        /// </summary>
        /// <param name="beforeCentralDir"></param>
        /// <param name="centralDir"></param>
        /// <param name="eocd"></param>
        /// <param name="signerConfig"></param>
        /// <returns></returns>
        public static byte[] GenerateApkSigningBlock(Stream beforeCentralDir, Stream centralDir, Stream eocd,
                                                     SignerConfig signerConfig)
        {
            // Figure out which digest(s) to use for APK contents.
            ISet <ContentDigestAlgorithm> contentDigestAlgorithms = new HashSet <ContentDigestAlgorithm>();

            contentDigestAlgorithms.Add(signerConfig.SignatureAlgorithm.ContentDigestAlgorithm);

            // Ensure that, when digesting, ZIP End of Central Directory record's Central Directory
            // offset field is treated as pointing to the offset at which the APK Signing Block will
            // start.
            var centralDirOffsetForDigesting = beforeCentralDir.Length;
            var eocdBuf = new MemoryStream(new byte[(int)eocd.Length], true);

            eocd.CopyTo(eocdBuf);
            eocdBuf.Position = 0;

            ZipUtils.SetZipEocdCentralDirectoryOffset(eocdBuf, centralDirOffsetForDigesting);

            // Compute digests of APK contents.
            IDictionary <ContentDigestAlgorithm, byte[]> contentDigests; // digest algorithm ID -> digest

            try
            {
                contentDigests =
                    ComputeContentDigests(
                        contentDigestAlgorithms,
                        new[]
                {
                    beforeCentralDir,
                    centralDir,
                    eocdBuf
                });
            }
            catch (IOException e)
            {
                throw new IOException("Failed to read APK being signed", e);
            }
            catch (CryptographicException e)
            {
                throw new CryptographicException("Failed to compute digests of APK", e);
            }

            // Sign the digests and wrap the signatures and signer info into an APK Signing Block.
            return(GenerateApkSigningBlock(signerConfig, contentDigests));
        }
Пример #14
0
        private ArchiveReader getReaderFrom(Stream stream)
        {
            if (!(stream is MemoryStream memoryStream))
            {
                // This isn't used in any current path. May need to reconsider for performance reasons (ie. if we don't expect the incoming stream to be copied out).
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, (int)stream.Length);
                memoryStream = new MemoryStream(buffer);
            }

            if (ZipUtils.IsZipArchive(memoryStream))
            {
                return(new ZipArchiveReader(memoryStream, Path));
            }

            return(new LegacyByteArrayReader(memoryStream.ToArray(), Path));
        }
Пример #15
0
        /// <summary>
        /// 解压并读取icon图片
        /// </summary>
        /// <param name="apkInfo"></param>
        private static void ParseIcon(ref ApkInfo apkInfo)
        {
            if (apkInfo == null ||
                string.IsNullOrEmpty(apkInfo.ApkFilePath) ||
                apkInfo.IconDic == null ||
                apkInfo.IconDic.Count <= 0)
            {
                return;
            }

            string icon = null;
            int    i    = 0;

            // 在多张尺寸的ICON里选择尺寸为240
            foreach (KeyValuePair <string, string> kv in apkInfo.IconDic)
            {
                if (kv.Key.Contains("240"))
                {
                    icon             = kv.Value;
                    apkInfo.IconName = Path.GetFileName(icon);
                    break;
                }
                if (i == apkInfo.IconDic.Count - 1)
                {
                    icon             = kv.Value;
                    apkInfo.IconName = Path.GetFileName(icon);
                    break;
                }
                i++;
            }

            // 指定解压目录
            string unZipPath = PathUtils.GetPath(Constants.DIR_TEMP_ICON);

            // 清空解压目录
            FileUtils.ClearDir(unZipPath);

            // 解压指定的icon图片文件
            ZipUtils.UnZip(apkInfo.ApkFilePath, unZipPath, icon);

            // 读取解压出来的图片文件
            string iconPath = PathUtils.JoinPath(unZipPath, icon);

            apkInfo.Icon = new Bitmap(iconPath);
        }
Пример #16
0
        private static void ProcessMedia(HttpContext context, bool isUpload, Database scriptDb, string itemParam, bool unpackZip, bool skipExisting)
        {
            var request = context.Request;

            if (isUpload)
            {
                if (ZipUtils.IsZipContent(request.InputStream) && unpackZip)
                {
                    PowerShellLog.Debug("The uploaded asset will be extracted to Media Library.");
                    using (var packageReader = new ZipArchive(request.InputStream))
                    {
                        itemParam = Path.GetDirectoryName(itemParam.TrimEnd('\\', '/'));
                        foreach (var zipEntry in packageReader.Entries)
                        {
                            // ZipEntry does not provide an IsDirectory or IsFile property.
                            if (!(zipEntry.FullName.EndsWith("/") && zipEntry.Name == "") && zipEntry.Length > 0)
                            {
                                ProcessMediaUpload(zipEntry.Open(), scriptDb, $"{itemParam}/{zipEntry.FullName}",
                                                   skipExisting);
                            }
                        }
                    }
                }
                else if (request.Files.AllKeys.Length > 0)
                {
                    foreach (string fileName in request.Files.Keys)
                    {
                        var file = request.Files[fileName];
                        if (file != null)
                        {
                            ProcessMediaUpload(file.InputStream, scriptDb, $"{itemParam}/{file.FileName}",
                                               skipExisting);
                        }
                    }
                }
                else
                {
                    ProcessMediaUpload(request.InputStream, scriptDb, itemParam, skipExisting);
                }
            }
            else
            {
                ProcessMediaDownload(context, scriptDb, itemParam);
            }
        }
Пример #17
0
        public NameValueCollection PluginDownload(string downloadUrl, string userKeyPrefix)
        {
            var cacheTotalCountKey   = userKeyPrefix + CacheTotalCount;
            var cacheCurrentCountKey = userKeyPrefix + CacheCurrentCount;
            var cacheMessageKey      = userKeyPrefix + CacheMessage;

            CacheUtils.Insert(cacheTotalCountKey, "5");       //存储需要的页面总数
            CacheUtils.Insert(cacheCurrentCountKey, "0");     //存储当前的页面总数
            CacheUtils.Insert(cacheMessageKey, string.Empty); //存储消息

            //返回“运行结果”和“错误信息”的字符串数组
            NameValueCollection retval;

            try
            {
                CacheUtils.Insert(cacheCurrentCountKey, "1");
                CacheUtils.Insert(cacheMessageKey, "开始下载插件压缩包,可能需要几分钟,请耐心等待");

                var fileName = PageUtils.GetFileNameFromUrl(downloadUrl);
                var filePath = PathUtils.GetPluginPath(fileName);
                FileUtils.DeleteFileIfExists(filePath);
                WebClientUtils.SaveRemoteFileToLocal(downloadUrl, filePath);

                CacheUtils.Insert(cacheCurrentCountKey, "4");
                CacheUtils.Insert(cacheMessageKey, "插件压缩包下载成功,开始安装");

                ZipUtils.UnpackFiles(filePath, PathUtils.GetPluginPath(fileName.Substring(0, fileName.IndexOf(".", StringComparison.Ordinal))));

                CacheUtils.Insert(cacheCurrentCountKey, "5");
                CacheUtils.Insert(cacheMessageKey, string.Empty);

                retval = AjaxManager.GetProgressTaskNameValueCollection("插件安装成功,请刷新页面查看。", string.Empty);
            }
            catch (Exception ex)
            {
                retval = AjaxManager.GetProgressTaskNameValueCollection(string.Empty,
                                                                        $@"<br />下载失败!<br />{ex.Message}");
            }

            CacheUtils.Remove(cacheTotalCountKey);   //取消存储需要的页面总数
            CacheUtils.Remove(cacheCurrentCountKey); //取消存储当前的页面总数
            CacheUtils.Remove(cacheMessageKey);      //取消存储消息

            return(retval);
        }
Пример #18
0
        public bool ExportContents(string filePath, List <ContentInfo> contentInfoList)
        {
            var siteContentDirectoryPath = PathUtils.Combine(DirectoryUtils.GetDirectoryPath(filePath), PathUtils.GetFileNameWithoutExtension(filePath));

            FileUtils.DeleteFileIfExists(filePath);
            DirectoryUtils.DeleteDirectoryIfExists(siteContentDirectoryPath);
            DirectoryUtils.CreateDirectoryIfNotExists(siteContentDirectoryPath);

            var contentIe = new ContentIe(_siteInfo, siteContentDirectoryPath);
            var isExport  = contentIe.ExportContents(_siteInfo, contentInfoList);

            if (isExport)
            {
                ZipUtils.CreateZip(filePath, siteContentDirectoryPath);
                DirectoryUtils.DeleteDirectoryIfExists(siteContentDirectoryPath);
            }
            return(isExport);
        }
Пример #19
0
        public MemoryStream GetZipMemoryStreamForStudent()
        {
            var excluded = (PathsToExcludeForStudent ?? new string[0])
                           .Concat(initialPatterns)
                           .Concat(wrongAnswerPatterns)
                           .Concat(solutionPatterns)
                           .Concat(new[] { "/checking/", "/bin/", "/obj/", ".idea/", ".vs/" })
                           .ToList();

            var toUpdate = ReplaceWithInitialFiles().ToList();

            var zipMemoryStream = ZipUtils.CreateZipFromDirectory(new List <string> {
                ExerciseDirectory.FullName
            }, excluded, toUpdate, Encoding.UTF8);

            log.Info($"Собираю zip-архив для студента: zip-архив собран, {zipMemoryStream.Length} байтов");
            return(zipMemoryStream);
        }
Пример #20
0
        private void LoadLogoInZip(ZipInputStream zip, ZipEntry theEntry)
        {
            try
            {
                Texture2D    texture2D = new Texture2D(128, 128);
                MemoryStream ms        = ZipUtils.ReadZipFileToMemory(zip);
                texture2D.LoadImage(ms.ToArray());
                ms.Close();
                ms.Dispose();

                LevelLogo = Sprite.Create(texture2D, new Rect(Vector2.zero, new Vector2(texture2D.width, texture2D.height)), new Vector2(0.5f, 0.5f));
            }
            catch (Exception e)
            {
                LevelLogo = null;
                GameLogger.Error(TAG, "在加载关卡的 Logo {0} 失败\n错误信息:{1}", Logo, e.ToString());
            }
        }
Пример #21
0
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        string UnZipFile(string file)
        {
            string path = "";

            if (String.Compare(Path.GetExtension(file), ".zip", true) == 0)
            {
                path = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file));
                if (Directory.Exists(path))
                {
                    DirectoryInfo dir = new DirectoryInfo(path);
                    We7Helper.DeleteFileTree(dir);
                }

                FileStream s = File.OpenRead(file);
                ZipUtils.ExtractZip((Stream)s, path);
            }
            return(path);
        }
Пример #22
0
        public bool ExportContents(string filePath, int channelId, List <int> contentIdArrayList, bool isPeriods, string dateFrom, string dateTo, ETriState checkedState)
        {
            var siteContentDirectoryPath = PathUtils.Combine(DirectoryUtils.GetDirectoryPath(filePath), PathUtils.GetFileNameWithoutExtension(filePath));

            FileUtils.DeleteFileIfExists(filePath);
            DirectoryUtils.DeleteDirectoryIfExists(siteContentDirectoryPath);
            DirectoryUtils.CreateDirectoryIfNotExists(siteContentDirectoryPath);

            var contentIe = new ContentIe(_siteInfo, siteContentDirectoryPath);
            var isExport  = contentIe.ExportContents(_siteInfo, channelId, contentIdArrayList, isPeriods, dateFrom, dateTo, checkedState);

            if (isExport)
            {
                ZipUtils.PackFiles(filePath, siteContentDirectoryPath);
                DirectoryUtils.DeleteDirectoryIfExists(siteContentDirectoryPath);
            }
            return(isExport);
        }
Пример #23
0
        public MemoryStream GetZipForChecker()
        {
            log.Info($"Собираю zip-архив для проверки: курс {CourseId}, слайд «{Slide?.Title}» ({Slide?.Id})");
            var excluded = (PathsToExcludeForChecker ?? new string[0])
                           .Concat(new[] { "/bin/", "/obj/", ".idea/", ".vs/" })
                           .ToList();

            var toUpdate = GetAdditionalFiles(excluded).ToList();

            log.Info($"Собираю zip-архив для проверки: дополнительные файлы [{string.Join(", ", toUpdate.Select(c => c.Path))}]");

            var ms = ZipUtils.CreateZipFromDirectory(new List <string> {
                ExerciseFolder.FullName
            }, excluded, toUpdate, Encoding.UTF8);

            log.Info($"Собираю zip-архив для проверки: zip-архив собран, {ms.Length} байтов");
            return(ms);
        }
Пример #24
0
        public IDataExtension Deserialize(Type type, byte[] data)
        {
            string content;

            if (data[0] == '<')
            {
                content = Encoding.UTF8.GetString(data);
            }
            else
            {
                content = ZipUtils.Unzip(data);
            }

            var result = XmlUtils.DefaultXmlDeserialize <LIB>(content);

            AfterDeserialize(result);
            return(result);
        }
Пример #25
0
        public static InvoiceEntity GetBlob(this Data.InvoiceData invoiceData, BTCPayNetworkProvider networks)
        {
            var entity = NBitcoin.JsonConverters.Serializer.ToObject <InvoiceEntity>(ZipUtils.Unzip(invoiceData.Blob), null);

            entity.Networks = networks;
            if (entity.Metadata is null)
            {
                if (entity.Version < InvoiceEntity.GreenfieldInvoices_Version)
                {
                    entity.MigrateLegacyInvoice();
                }
                else
                {
                    entity.Metadata = new InvoiceMetadata();
                }
            }
            return(entity);
        }
 public static StreamReader GetParameterFileStream(string fileName)
 {
     if (fileName.ToLower().EndsWith(".zip"))
     {
         if (ZipUtils.HasFile(fileName, m => m.ToLower().EndsWith(".out")))
         {
             return(ZipUtils.OpenFile(fileName, m => m.ToLower().Equals("sequest.params")));
         }
         else
         {
             return(ZipUtils.OpenFile(fileName, m => m.ToLower().EndsWith(".outs")));
         }
     }
     else
     {
         return(new StreamReader(fileName));
     }
 }
Пример #27
0
        internal static IEnumerable <IInstallationStep> GetInstallationProcedure(params string[] args)
        {
            // create tmp folder
            var tmpFolder = Path.GetTempPath();

            var    cmdArgs = new Utils.CmdLineArgs(args);
            bool   bSilent = cmdArgs.CheckArg("silent");
            string xToken  = cmdArgs.GetArgValue("xToken");

            InitializeEventService(args);
            yield return(new GenerateInstallMachineIds());

            yield return(new CreatePartnerInfoStep(args));

            yield return(new DownloadStep(tmpFolder, TimeSpan.FromMinutes(DownloadStep.InstallTimeout), DownloadStep.InstallRetry, args)
            {
                Validator = x => ZipUtils.IsZipValid(x)
            });

            yield return(new UnzipStep(Path.Combine(tmpFolder, "Spareio.zip"), InstallUtils.GetInstallFolder()));

            yield return(new InstallService(InstallUtils.GetWcRunFolder()));

            yield return(new ExecuteCommandStep("sc.exe", new[] { "start", InstallService.ServiceName, xToken })
            {
                HideWindow = true
            });

            yield return(new UninstallInfoStep());

            yield return(new UpdateInstalledRegistry(true));

            yield return(new RunSpareio(Path.Combine(InstallUtils.GetWcRunFolder(), "Spareio.exe"))
            {
                silent = bSilent, install = true, InitMessage = "Applying Selected Configuration ..."
            });

            yield return(new RunSpareio(Path.Combine(InstallUtils.GetWcRunFolder(), "Spareio.exe"))
            {
                silent = bSilent, afterinstall = true, WaitForExit = false
            });

            yield return(new ReportInstallationResultStep(ReportInstallationResultStep.InstallState.Ok, "CompleteInstall"));
        }
Пример #28
0
        public bool Open(string filename)
        {
            Close();

            if (filename.ToLower().EndsWith(".zip"))
            {
                this.sr = ZipUtils.OpenFile(filename);
            }
            else
            {
                this.sr = new StreamReader(filename);
            }
            bool bStart = false;

            while ((this.lastLine = this.sr.ReadLine()) != null)
            {
                if (this.lastLine.StartsWith("OUTFILE_COUNT="))
                {
                    String[] parts = this.lastLine.Split('=');
                    this.outFileCount = int.Parse(parts[1]);
                    continue;
                }

                if (this.lastLine.Equals("[SEQUEST_OUT_FILES]"))
                {
                    bStart = true;
                    continue;
                }

                if (!bStart)
                {
                    continue;
                }

                if (this.lastLine.EndsWith(".out"))
                {
                    this.hasNext      = true;
                    this.nextFilename = this.lastLine.Trim();
                    break;
                }
            }

            return(this.hasNext);
        }
Пример #29
0
        public static NotificationViewModel ViewModel(this NotificationData data)
        {
            var baseType = typeof(BaseNotification);

            var fullTypeName = baseType.FullName.Replace(nameof(BaseNotification), data.NotificationType, StringComparison.OrdinalIgnoreCase);
            var parsedType   = baseType.Assembly.GetType(fullTypeName);

            var casted = (BaseNotification)JsonConvert.DeserializeObject(ZipUtils.Unzip(data.Blob), parsedType);
            var obj    = new NotificationViewModel
            {
                Id      = data.Id,
                Created = data.Created,
                Seen    = data.Seen
            };

            casted.FillViewModel(ref obj);

            return(obj);
        }
 static void ZipFileToServer(string serverPath)
 {
     string[] files = Directory.GetFiles(AssetOutPath);
     for (int i = 0; i < files.Length; i++)
     {
         string fileName = Path.GetFileName(files [i]);
         if (fileName.IndexOf(AssetHeplerEditor.GetPlatformName()) >= 0 || fileName.IndexOf(".meta") >= 0 || fileName.IndexOf(".manifest") >= 0 || !BundleNames.Contains(fileName))
         {
             //文件夹名称的AssetBundle排除
             continue;
         }
         if (fileName == ResInfoName)
         {
             continue;
         }
         string dp = FileTools.CombinePath(serverPath, fileName);
         ZipUtils.CompressFile(files[i], dp);
     }
 }