Beispiel #1
0
        ///// <summary>
        ///// Changes the config file value.
        ///// </summary>
        ///// <param name="name">
        ///// The name.
        ///// </param>
        ///// <param name="newvalue">
        ///// The new value.
        ///// </param>
        ///// <returns>
        ///// A value indicating weather the change was successful or not.
        ///// </returns>
        //public static bool ChangeConfigFileValue(string name, string newvalue)
        //{
        //    try
        //    {
        //        XmlDocument xmlDoc = new XmlDocument();

        //        xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

        //        foreach (XmlElement element in xmlDoc.DocumentElement)
        //        {
        //            if (element.Name.Equals("applicationSettings"))
        //            {
        //                foreach (XmlNode node in element.ChildNodes)
        //                {
        //                    foreach (XmlNode node2 in node.ChildNodes)
        //                    {
        //                        if (node2.Attributes.Count > 0 && node2.Attributes[0].Value.Equals(name))
        //                        {
        //                            foreach (XmlNode node3 in node2.ChildNodes)
        //                            {
        //                                if (node3.Name == "value")
        //                                {
        //                                    node3.InnerText = newvalue;
        //                                    xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

        //                                    ConfigurationManager.RefreshSection("applicationSettings");
        //                                    return true;
        //                                }
        //                            }

        //                            XmlElement newelement2 = xmlDoc.CreateElement("value");
        //                            newelement2.InnerText = newvalue;
        //                            node2.AppendChild(newelement2);
        //                            xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

        //                            ConfigurationManager.RefreshSection("applicationSettings");
        //                            return true;
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        FileOperation.LogError(ex, FileOperation.MaxLogFileSize);
        //    }

        //    return false;
        //}

        /// <summary>
        /// Compresses the file to ZIP.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="fileToCompress">
        /// The file to compress.
        /// </param>
        /// <param name="compressedFileName">
        /// Name of the compressed file.
        /// </param>
        /// <returns>
        /// A boolean indicating that the file was zipped was successful.
        /// </returns>
        public static bool CompressFileToZIP(string path, string fileToCompress, string compressedFileName)
        {
            string srcFile = path.EndsWith("\\") ? path + fileToCompress : path + "\\" + fileToCompress;
            string dstFile = path.EndsWith("\\") ? path + compressedFileName : path + "\\" + compressedFileName;

            try
            {
                var zipfile = new ZipFile(dstFile);
                zipfile.CompressionLevel  = Ionic.Zlib.CompressionLevel.Default;
                zipfile.CompressionMethod = CompressionMethod.Deflate;

                if (zipfile.ContainsEntry(srcFile))
                {
                    zipfile.RemoveEntry(srcFile);
                    zipfile.AddFile(srcFile);
                }
                else
                {
                    zipfile.AddFile(srcFile, string.Empty);
                }

                zipfile.Save();
                zipfile = null;
                return(true);
            }
            catch (Exception ex)
            {
                FileOperation.LogError(ex, FileOperation.MaxLogFileSize);
            }

            return(false);
        }
Beispiel #2
0
        private void ExportSiteMembership(Site rootSiteExported, Site site, ZipFile zipFile, bool includeSubSites)
        {
            site = site.AsActual();

            if (!string.IsNullOrEmpty(site.Membership))
            {
                if (site.Parent == null || (site.Parent != null &&
                                            !site.Parent.AsActual().Membership.EqualsOrNullEmpty(site.Membership, StringComparison.CurrentCultureIgnoreCase)))
                {
                    MemoryStream ms = new MemoryStream();

                    _membershipProvider.Export(site.GetMembership(), ms);

                    if (ms.Length > 0)
                    {
                        ms.Position = 0;

                        var entryName = GetSiteRelatedEntryName(rootSiteExported, site, MembershipFileName);

                        if (zipFile.ContainsEntry(entryName))
                        {
                            zipFile.RemoveEntry(entryName);
                        }
                        zipFile.AddEntry(entryName, ms);
                    }
                }
            }
            if (includeSubSites)
            {
                foreach (var childSite in ChildSites(site))
                {
                    ExportSiteMembership(rootSiteExported, childSite, zipFile, includeSubSites);
                }
            }
        }
        public virtual BundleManifest Load(string path)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            if (Regex.IsMatch(path, @"(jar:file:///)|(\.jar)|(\.apk)|(\.obb)|(\.zip)", RegexOptions.IgnoreCase))
            {
                using (ZipFile zip = new ZipFile(this.GetCompressedFileName(path)))
                {
                    string entryName = this.GetCompressedEntryName(path);
                    if (!zip.ContainsEntry(entryName))
                    {
                        if (log.IsErrorEnabled)
                        {
                            log.ErrorFormat("Not found the BundleManifest '{0}'.", path);
                        }
                        return(null);
                    }

                    ZipEntry entry  = zip[entryName];
                    byte[]   buffer = new byte[entry.UncompressedSize];
                    using (Stream input = entry.OpenReader())
                    {
                        input.Read(buffer, 0, buffer.Length);
                    }
                    return(BundleManifest.Parse(Encoding.UTF8.GetString(buffer)));
                }
            }
            return(BundleManifest.Parse(File.ReadAllText(path, Encoding.UTF8)));
#elif UNITY_WEBGL && !UNITY_EDITOR
            throw new NotSupportedException("Because WebGL is single-threaded, this method is not supported,please use LoadAsync instead.");
#else
            return(BundleManifest.Parse(File.ReadAllText(path, Encoding.UTF8)));
#endif
        }
Beispiel #4
0
        protected override void LoadContent()
        {
            const string terrainPath = "Content/terrain.png";

            if (File.Exists(terrainPath))
            {
                _terrain = Texture2D.FromStream(GraphicsDevice, File.Open(terrainPath, FileMode.Open));
            }
            else
            {
                if (File.Exists(Path.Combine(MinecraftUtilities.DotMinecraft, "bin", "minecraft.jar")))
                {
                    using (var file = new ZipFile(Path.Combine(MinecraftUtilities.DotMinecraft, "bin", "minecraft.jar")))
                    {
                        if (file.ContainsEntry("terrain.png"))
                        {
                            var ms = new MemoryStream();
                            file["terrain.png"].Extract(ms);
                            ms.Seek(0, SeekOrigin.Begin);
                            _terrain = Texture2D.FromStream(GraphicsDevice, ms);
                        }
                        else
                        {
                            throw new FileNotFoundException("Missing terrain.png!");
                        }
                    }
                }
                else
                {
                    throw new FileNotFoundException("Missing terrain.png!");
                }
            }

            InitializeEffect();
        }
Beispiel #5
0
        internal static void AddZipToZip(ZipFile zip, string directoryInDestination, MemoryStream zipStream, string password)
        {
            zipStream.Position = 0;
            using (var zipToAdd = ZipFile.Read(zipStream))
            {
                zip.Password = password;

                int            zipToAddEntriesCount = zipToAdd.Entries.Count;
                MemoryStream[] msArray = new MemoryStream[zipToAddEntriesCount];
                for (int i = 0; i < zipToAddEntriesCount; i++)
                {
                    ZipEntry     zipToAddEntry   = zipToAdd[i];
                    MemoryStream zipMemoryStream = msArray[i] = new MemoryStream();
                    string       filePathInZip   = Path.Combine(directoryInDestination, zipToAddEntry.FileName);

                    if (zip.ContainsEntry(filePathInZip))
                    {
                        ZipEntry zipEntry = zip[filePathInZip];
                        filePathInZip = zipEntry.FileName;
                        zip.RemoveEntry(filePathInZip);
                        zipToAddEntry.Extract(zipMemoryStream);
                        zipMemoryStream.Position = 0;
                        zip.AddEntry(filePathInZip, zipMemoryStream);

                        ZipEntry modifiedZipEntry = zip[filePathInZip];
                        CopyZipEntryAttributes(zipEntry, modifiedZipEntry);
                    }
                    else
                    {
                        Logger.Debug($"AddZipToZip does not contain filePathInZip=[{filePathInZip}]");
                    }
                }
            }
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="ARealmReversed" /> class.
        /// </summary>
        /// <param name="gameDirectory">Directory of the game installation.</param>
        /// <param name="storeFile">File used for storing definitions and history.</param>
        /// <param name="language">Initial language to use.</param>
        /// <param name="libraFile">Location of the Libra Eorzea database file, or <c>null</c> if it should not be used.</param>
        public ARealmReversed(DirectoryInfo gameDirectory, FileInfo storeFile, Language language, FileInfo libraFile)
        {
            // Fix for being referenced in a .Net Core 2.1+ application (https://stackoverflow.com/questions/50449314/ibm437-is-not-a-supported-encoding-name => https://stackoverflow.com/questions/44659499/epplus-error-reading-file)
            // PM> dotnet add package System.Text.Encoding.CodePages
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            _GameDirectory = gameDirectory;
            _Packs         = new PackCollection(Path.Combine(gameDirectory.FullName, "game", "sqpack"));
            _GameData      = new XivCollection(Packs, libraFile)
            {
                ActiveLanguage = language
            };

            _GameVersion         = File.ReadAllText(Path.Combine(gameDirectory.FullName, "game", "ffxivgame.ver"));
            _StateFile           = storeFile;
            _GameData.Definition = ReadDefinition();

            using (ZipFile zipFile = new ZipFile(StateFile.FullName, ZipEncoding)) {
                if (!zipFile.ContainsEntry(VersionFile))
                {
                    Setup(zipFile);
                }
            }

            _GameData.Definition.Compile();
        }
Beispiel #7
0
        private bool TryGetDefinitionVersion(ZipFile zip, string version, out RelationDefinition definition, out DateTime lastMod)
        {
            var    storedVersionEntry = zip[VersionFile];
            string storedVersion;

            using (var s = storedVersionEntry.OpenReader()) {
                using (var r = new StreamReader(s))
                    storedVersion = r.ReadToEnd();
            }

            if (storedVersion != version)
            {
                var existingDefPath = string.Format("{0}/{1}", version, DefinitionFile);
                if (zip.ContainsEntry(existingDefPath))
                {
                    ZipCopy(zip, existingDefPath, DefinitionFile);
                    UpdateVersion(zip);
                    zip.Save();

                    definition = ReadDefinition(zip, DefinitionFile, out lastMod);
                    return(true);
                }

                definition = null;
                lastMod    = DateTime.MinValue;
                return(false);
            }

            definition = ReadDefinition(zip, DefinitionFile, out lastMod);
            return(true);
        }
        /// <summary>Removes the specified file from the Kmz archive.</summary>
        /// <param name="path">
        /// The file, including directory information, to locate in the archive.
        /// </param>
        /// <returns>
        /// true if the specified file was found in the archive and successfully
        /// removed; otherwise, false.
        /// </returns>
        /// <exception cref="ObjectDisposedException">
        /// <see cref="Dispose"/> has been called on this instance.
        /// </exception>
        public bool RemoveFile(string path)
        {
            this.ThrowIfDisposed();

            if (!string.IsNullOrEmpty(path))
            {
                // By default RemoveEntry throws an ArgumentException if the file's
                // not found, so check first to avoid the exception
                if (_zip.ContainsEntry(path))
                {
                    _zip.RemoveEntry(path);
                    return(true);
                }
            }
            return(false);
        }
Beispiel #9
0
        private void ExportSiteRepository(Site rootSiteExported, Site site, ZipFile zipFile, bool includeSubSites)
        {
            site = site.AsActual();

            if (!string.IsNullOrEmpty(site.Repository))
            {
                if (site.Parent == null || (site.Parent != null &&
                                            !site.Parent.AsActual().Repository.EqualsOrNullEmpty(site.Repository, StringComparison.CurrentCultureIgnoreCase)))
                {
                    MemoryStream ms = new MemoryStream();

                    Kooboo.CMS.Content.Services.ServiceFactory.RepositoryManager.Export(site.Repository, ms);

                    ms.Position = 0;

                    var entryName = GetSiteRelatedEntryName(rootSiteExported, site, ContentDatabaseFileName);

                    if (zipFile.ContainsEntry(entryName))
                    {
                        zipFile.RemoveEntry(entryName);
                    }
                    zipFile.AddEntry(entryName, ms);
                }
            }
            if (includeSubSites)
            {
                foreach (var childSite in ChildSites(site))
                {
                    ExportSiteRepository(rootSiteExported, childSite, zipFile, includeSubSites);
                }
            }
        }
Beispiel #10
0
 public static void ImportData <T>(Site site, ISiteElementProvider <T> provider, string fileName, Stream zipStream, bool @override)
     where T : ISiteObject, IFilePersistable, IPersistable, IIdentifiable
 {
     using (ZipFile zipFile = ZipFile.Read(zipStream))
     {
         if (zipFile.ContainsEntry(fileName))
         {
             using (MemoryStream ms = new MemoryStream())
             {
                 var entry = zipFile[fileName];
                 entry.Extract(ms);
                 ms.Position = 0;
                 var list = Deserialize <List <T> >(ms, null);
                 foreach (var item in list)
                 {
                     item.Site = site;
                     var o = provider.Get(item);
                     if (o != null && @override)
                     {
                         provider.Update(item, o);
                     }
                     if (o == null)
                     {
                         provider.Add(item);
                     }
                 }
             }
         }
     }
 }
Beispiel #11
0
        private static void Addlibg(string apkname)
        {
            ZipFile file = new ZipFile(apkname);

            if (file.ContainsEntry("lib/x86/libg.so"))
            {
                file.RemoveEntry("lib/x86/libg.so");
            }
            file.AddFile("lib\\x86\\libg.so", "lib/x86");
            if (file.ContainsEntry("lib/armeabi-v7a/libg.so"))
            {
                file.RemoveEntry("lib/armeabi-v7a/libg.so");
            }
            file.AddFile("lib\\armeabi-v7a\\libg.so", "lib/armeabi-v7a");
            file.Save();
        }
Beispiel #12
0
    public void UpdateAudioFile(int resourceId)
    {
        Resource res = AppManager.Instance.ResourcesManager.GetResource(resourceId);

        Debug.Log("Updating Audio File " + res.Name);

        string content = res.BPM + "/" + res.BPB + "/" + res.BeginLoop + "/" + res.EndLoop;

        content += Environment.NewLine + res.nextTransitionId + ":";

        for (int i = 0; i < res.Transitions.Count; ++i)
        {
            content += "(" + res.Transitions[i].id + ";" + res.Transitions[i].value + ")";
        }

        ZipFile zip = ZipFile.Read(scenarioUrl);

        if (!zip.ContainsEntry(resourceId.ToString() + "_setup"))
        {
            Debug.LogError("Couldnt find " + resourceId + "in zip.");
            zip.Dispose();
            return;
        }

        zip.UpdateEntry(resourceId.ToString() + "_setup", content);
        zip.Save(scenarioUrl);
        zip.Dispose();

        Debug.Log("Updated Audio File " + res.Name + " ( " + resourceId + " )");
    }
        public string ReadEntry(string entryName)
        {
            if (string.IsNullOrEmpty(entryName))
            {
                throw new ArgumentException("entryName");
            }

            using (ZipFile zipFile = ZipFile.Read(this.mFileName))
            {
                if (!zipFile.ContainsEntry(entryName))
                {
                    throw new FileNotFoundException(entryName);
                }

                ZipEntry entry = zipFile[entryName];

                using (var stream = entry.OpenReader())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            }
        }
Beispiel #14
0
 private bool HasZipEntry(string filename)
 {
     using (var file = new ZipFile(_zipFile))
     {
         return(file.ContainsEntry(filename));
     }
 }
Beispiel #15
0
 /// <summary>
 /// Load a referenced file, from apackage or from the original location
 ///
 /// </summary>
 /// <param name="file">The file.</param>
 /// <returns></returns>
 /// <exception cref="System.IO.FileNotFoundException"></exception>
 public Stream GetFileStream(string file)
 {
     if (File.Exists(file))
     {
         return(File.OpenRead(file));
     }
     if (File.Exists(Package))
     {
         using (ZipFile zip = new ZipFile(Package))
         {
             MemoryStream reader  = new MemoryStream();
             var          zipFile = "files\\" + Path.GetFileName(file);
             if (zip.ContainsEntry(zipFile))
             {
                 zip[zipFile].Extract(reader);
                 reader.Seek(0, SeekOrigin.Begin);
                 return(reader);
             }
         }
     }
     if (File.Exists(Path.Combine(Settings.Instance.WorkflowFolder, Id, Path.GetFileName(file))))
     {
         return(File.OpenRead(Path.Combine(Settings.Instance.WorkflowFolder, Id, Path.GetFileName(file))));
     }
     throw new FileNotFoundException("", file);
 }
        /// <summary>
        /// Gets the string contents of a text based file inside a zip file
        /// </summary>
        /// <param name="zip">The zipfile to extract the entry from</param>
        /// <param name="archivedFilename">The archive path to the entry</param>
        /// <param name="password">The password to use when extracting the entry. Leave blank for no password</param>
        /// <returns></returns>
        public static string GetStringFromZip(ZipFile zip, string archivedFilename, string password = "")
        {
            //make sure the entry exists in the stream first
            if (!zip.ContainsEntry(archivedFilename))
            {
                Logging.Error("entry {0} does not exist in given zip file", archivedFilename);
                return(null);
            }

            using (MemoryStream ms = new MemoryStream()
            {
                Position = 0
            })
                using (StreamReader sr = new StreamReader(ms))
                {
                    ZipEntry e = zip[archivedFilename];

                    //if a password is provided, then use it for extraction
                    if (!string.IsNullOrWhiteSpace(password))
                    {
                        e.ExtractWithPassword(ms, password);
                    }
                    else
                    {
                        e.Extract(ms);
                    }

                    //read stream
                    ms.Position = 0;
                    return(sr.ReadToEnd());
                }
        }
Beispiel #17
0
        private void LoadTGATextures(ZipFile pk3)
        {
            foreach (Texture tex in Textures)
            {
                // The size of the new Texture2D object doesn't matter. It will be replaced (including its size) with the data from the texture that's getting pulled from the pk3 file.
                if (pk3.ContainsEntry(tex.Name + ".tga"))
                {
                    Texture2D readyTex = new Texture2D(4, 4);
                    ZipEntry  entry    = pk3[tex.Name + ".tga"];
                    using (CrcCalculatorStream stream = entry.OpenReader())
                    {
                        MemoryStream ms = new MemoryStream();
                        entry.Extract(ms);
                        readyTex = TGALoader.LoadTGA(ms);
                    }

                    readyTex.name       = tex.Name;
                    readyTex.filterMode = FilterMode.Trilinear;
                    readyTex.Compress(true);

                    if (readyTextures.ContainsKey(tex.Name))
                    {
                        Debug.Log("Updating texture with name " + tex.Name + ".tga");
                        readyTextures[tex.Name] = readyTex;
                    }
                    else
                    {
                        readyTextures.Add(tex.Name, readyTex);
                    }
                }
            }
        }
        private void DownloadAllZipped(int message_id, HttpContext context)
        {
            var mail_box_manager = new MailBoxManager(0);

            var attachments = mail_box_manager.GetMessageAttachments(TenantId, Username, message_id);

            if (attachments.Any())
            {
                using (var zip = new ZipFile())
                {
                    zip.CompressionLevel       = CompressionLevel.Level3;
                    zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                    zip.AlternateEncoding      = Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage);

                    foreach (var attachment in attachments)
                    {
                        using (var file = AttachmentManager.GetAttachmentStream(attachment))
                        {
                            var filename = file.FileName;

                            if (zip.ContainsEntry(filename))
                            {
                                var counter   = 1;
                                var temp_name = filename;
                                while (zip.ContainsEntry(temp_name))
                                {
                                    temp_name = filename;
                                    var suffix = " (" + counter + ")";
                                    temp_name = 0 < temp_name.IndexOf('.')
                                                   ? temp_name.Insert(temp_name.LastIndexOf('.'), suffix)
                                                   : temp_name + suffix;

                                    counter++;
                                }
                                filename = temp_name;
                            }

                            zip.AddEntry(filename, file.FileStream.GetCorrectBuffer());
                        }
                    }

                    context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(ArchiveName));

                    zip.Save(context.Response.OutputStream);
                }
            }
        }
Beispiel #19
0
        /// <summary>
        ///     Perform first-time setup on the archive.
        /// </summary>
        /// <param name="zip"><see cref="ZipFile" /> used for storage.</param>
        /// <returns>Returns the initial <see cref="RelationDefinition" /> object.</returns>
        private RelationDefinition Setup(ZipFile zip)
        {
            RelationDefinition zipDef = null;
            DateTime           zipMod = DateTime.MinValue;

            if (!TryGetDefinitionFromFileSystem(out var fsDef, out var fsMod))
            {
                fsDef = null;
            }

            if (zip.ContainsEntry(DefinitionFile) || zip.ContainsEntry(OldDefinitionFile))
            {
                zipDef = ReadDefinition(zip, DefinitionFile, out zipMod);
            }

            if (fsDef == null && zipDef == null)
            {
                throw new InvalidOperationException();
            }

            RelationDefinition def;

            if (fsMod > zipMod)
            {
                def = fsDef;
            }
            else
            {
                def = zipDef;
            }

            if (def.Version != GameVersion)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Definition and game version mismatch ({0} != {1})", def.Version, GameVersion));
            }

            def.Version = GameVersion;
            StoreDefinition(zip, def, string.Format("{0}/{1}", def.Version, DefinitionFile));
            StoreDefinition(zip, def, DefinitionFile);
            StorePacks(zip);
            UpdateVersion(zip);

            zip.Save();

            return(def);
        }
Beispiel #20
0
 private bool HasFile(string fileName)
 {
     if (!_isCompressed)
     {
         return(File.Exists(Path.Combine(FullPath, fileName)));
     }
     return(_zipFile.ContainsEntry(fileName));
 }
Beispiel #21
0
 protected SampleRepository(ZipFile archive)
 {
     this.archive = archive;
     if (archive.ContainsEntry("index.xml"))
     {
         index = ((ICollection <SampleDesc>)IndexSerializer.Deserialize(archive["index.xml"].OpenReader())).ToDictionary(sd => sd.ID, sd => sd);
     }
 }
Beispiel #22
0
        /// <summary>
        /// Create a new PebbleBundle from a .pwb file and parse its metadata.
        /// </summary>
        /// <param name="path">The relative or full path to the file.</param>
        public PebbleBundle(string path)
        {
            Stream jsonStream;

            FullPath = Path.GetFullPath(path);
            _Bundle  = ZipFile.Read(FullPath);

            if (_Bundle.ContainsEntry("manifest.json"))
            {
                jsonStream = _Bundle["manifest.json"].OpenReader();
            }
            else
            {
                throw new ArgumentException("manifest.json not found in archive - not a Pebble bundle.");
            }

            var serializer = new DataContractJsonSerializer(typeof(BundleManifest));


            _Manifest = (BundleManifest)serializer.ReadObject(jsonStream);
            jsonStream.Close();

            HasResources = (_Manifest.Resources.Size != 0);

            if (_Manifest.Type == "firmware")
            {
                BundleType = BundleTypes.Firmware;
            }
            else
            {
                BundleType = BundleTypes.Application;
                Stream binStream;
                if (_Bundle.ContainsEntry(_Manifest.Application.Filename))
                {
                    binStream = _Bundle[_Manifest.Application.Filename].OpenReader();
                }
                else
                {
                    throw new Exception(string.Format("App file {0} not found in archive", _Manifest.Application.Filename));
                }

                AppMetadata = Util.ReadStruct <ApplicationMetadata>(binStream);
                binStream.Close();
            }
            _Bundle.Dispose();
        }
Beispiel #23
0
        /// <summary>
        /// Works like UMFAsset.LoadTexture2D, except it isn't dependent on System.Drawing. Returns null if the texture was not found.
        /// </summary>
        public static Texture2D LoadTexture2D(string file, bool shared = false)
        {
            string modName  = shared ? "Shared" : Assembly.GetCallingAssembly().GetName().Name;
            string filePath = Path.Combine(Path.Combine(UMFData.AssetsPath, modName), file);

            if (cachedTexes.ContainsKey(filePath))
            {
                return(cachedTexes[filePath]);
            }
            string assetPath = Path.Combine(Path.Combine("Assets", modName), file);

            if (cachedTexes.ContainsKey(Path.Combine(UMFData.TempPath, assetPath)))
            {
                return(cachedTexes[Path.Combine(UMFData.TempPath, assetPath)]);
            }
            if (!File.Exists(filePath) && GadgetCore.CoreLib != null)
            {
                filePath = Path.Combine(UMFData.TempPath, assetPath);
                string[] umfmods = Directory.GetFiles(UMFData.ModsPath, (shared ? "" : modName) + "*.umfmod");
                string[] zipmods = Directory.GetFiles(UMFData.ModsPath, (shared ? "" : modName) + "*.zip");
                string[] mods    = new string[umfmods.Length + zipmods.Length];
                Array.Copy(umfmods, mods, umfmods.Length);
                Array.Copy(zipmods, 0, mods, umfmods.Length, zipmods.Length);
                foreach (string mod in mods)
                {
                    using (ZipFile modZip = new ZipFile(mod))
                    {
                        if (mod.EndsWith(".umfmod"))
                        {
                            GadgetCore.CoreLib.DecryptUMFModFile(modZip);
                        }
                        if (modZip.ContainsEntry(assetPath))
                        {
                            modZip[assetPath].Extract(UMFData.TempPath, ExtractExistingFileAction.OverwriteSilently);
                        }
                    }
                }
            }
            if (File.Exists(filePath))
            {
                byte[] fileData;
                fileData = File.ReadAllBytes(filePath);
                Texture2D tex = new Texture2D(2, 2);
                tex.LoadImage(fileData);
                tex.filterMode = FilterMode.Point;
                cachedTexes.Add(filePath, tex);
                if (filePath.StartsWith(UMFData.TempPath))
                {
                    File.Delete(filePath);
                    GadgetUtils.RecursivelyDeleteDirectory(UMFData.TempPath);
                }
                return(tex);
            }
            else
            {
                return(null);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Create a new PebbleBundle from a .pwb file and parse its metadata.
        /// </summary>
        /// <param name="path">The relative or full path to the file.</param>

        public PebbleBundle(String path)
        {
            Stream jsonstream;

            FullPath = Path.GetFullPath(path);
            Bundle   = ZipFile.Read(FullPath);

            if (Bundle.ContainsEntry("manifest.json"))
            {
                jsonstream = Bundle["manifest.json"].OpenReader();
            }
            else
            {
                throw new ArgumentException("manifest.json not found in archive - not a Pebble bundle.");
            }

            var serializer = new DataContractJsonSerializer(typeof(BundleManifest));


            Manifest = serializer.ReadObject(jsonstream) as BundleManifest;
            jsonstream.Close();

            HasResources = (Manifest.Resources.Size != 0);

            if (Manifest.Type == "firmware")
            {
                BundleType = BundleTypes.Firmware;
            }
            else
            {
                BundleType = BundleTypes.Application;
                if (!Bundle.ContainsEntry(Manifest.Application.Filename))
                {
                    String format = "App file {0} not found in archive";
                    throw new ArgumentException(String.Format(format, Manifest.Application.Filename));
                }

                Binary      = ReadBinary(Manifest.Application.Filename);
                Application = Util.ReadStruct <ApplicationMetadata>(Binary);
                if (HasResources)
                {
                    ResourcesBinary = ReadBinary(Manifest.Resources.Filename);
                }
            }
        }
Beispiel #25
0
        public override void ExecuteResult(ControllerContext context)
        {
            using (ZipFile zf = new ZipFile(System.Text.Encoding.GetEncoding("cp866")))
            {
                zf.CompressionLevel = (CompressionLevel)this._compressionLevel;

                foreach (var file in _files)
                {
                    string val = file.Value;

                    int step = 1;
                    
                    while(zf.ContainsEntry(val))
                    {
                        val = step + "_" + val;

                        step++;
                    }

                    zf.AddFile(file.Key).FileName = val;
                }

                foreach (var dir in _directories)
                {
                    string val = dir.Value;

                    int step = 1;

                    while (zf.ContainsEntry(val))
                    {
                        val = step + "_" + val;

                        step++;
                    }
                    
                    zf.AddDirectory(dir.Key, val);
                }
                
                context.HttpContext
                    .Response.ContentType = "application/zip";
                context.HttpContext
                    .Response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
                zf.Save(context.HttpContext.Response.OutputStream);
            }
        }
Beispiel #26
0
        public bool OpenDeserialize(byte[] bytes)
        {
            // Copy the bytes to a stream
            zipStream = new MemoryStream();
            zipStream.Write(bytes, 0, bytes.Length);
            zipStream.Position = 0;
            try {
                zip = ZipFile.Read(zipStream);
            } catch (Exception e) {
                // Catches exceptions when an invalid zip file is found
                Debug.LogError("Caught exception when loading from zip\n" + e);

                zipStream.Dispose();
                return(false);
            }

            if (zip.ContainsEntry("meta" + jsonExt))
            {
                meta = DeserializeMeta(zip["meta" + jsonExt]);
            }
            else if (zip.ContainsEntry("meta" + binaryExt))
            {
                meta = DeserializeBinaryMeta(zip["meta" + binaryExt]);
            }
            else
            {
                throw new Exception("No metadata found in serialized data.");
            }

            if (FullyDefinedVersion(meta.version) > FullyDefinedVersion(AstarPath.Version))
            {
                Debug.LogWarning("Trying to load data from a newer version of the A* Pathfinding Project\nCurrent version: " + AstarPath.Version + " Data version: " + meta.version +
                                 "\nThis is usually fine as the stored data is usually backwards and forwards compatible." +
                                 "\nHowever node data (not settings) can get corrupted between versions (even though I try my best to keep compatibility), so it is recommended " +
                                 "to recalculate any caches (those for faster startup) and resave any files. Even if it seems to load fine, it might cause subtle bugs.\n");
            }
            else if (FullyDefinedVersion(meta.version) < FullyDefinedVersion(AstarPath.Version))
            {
                Debug.LogWarning("Trying to load data from an older version of the A* Pathfinding Project\nCurrent version: " + AstarPath.Version + " Data version: " + meta.version +
                                 "\nThis is usually fine, it just means you have upgraded to a new version." +
                                 "\nHowever node data (not settings) can get corrupted between versions (even though I try my best to keep compatibility), so it is recommended " +
                                 "to recalculate any caches (those for faster startup) and resave any files. Even if it seems to load fine, it might cause subtle bugs.\n");
            }
            return(true);
        }
Beispiel #27
0
 /// <summary>
 /// Removes the specified entry from this zip if it existed in the first place.
 /// </summary>
 /// <returns>True if an entry was removed.</returns>
 public bool RemoveFile(string entry)
 {
     if (!zipFile.ContainsEntry(entry))
     {
         return(false);
     }
     zipFile.RemoveEntry(entry);
     return(true);
 }
Beispiel #28
0
        /** Deserializes nodes.
         * Nodes can be saved to enable loading a full scanned graph from memory/file without scanning the graph first.
         * \note Node info is stored in files named "graph#_nodes.binary" where # is the graph number.
         * \note Connectivity info is stored in files named "graph#_conns.binary" where # is the graph number.
         */
        public void DeserializeNodes()
        {
            for (int i = 0; i < graphs.Length; i++)
            {
                if (zip.ContainsEntry("graph" + i + "_nodes" + binaryExt))
                {
                    //Create nodes
                    graphs[i].nodes = graphs[i].CreateNodes(meta.nodeCounts[i]);
                }
                else
                {
                    graphs[i].nodes = graphs[i].CreateNodes(0);
                }
            }

            for (int i = 0; i < graphs.Length; i++)
            {
                ZipEntry entry = zip["graph" + i + "_nodes" + binaryExt];
                if (entry == null)
                {
                    continue;
                }

                MemoryStream str = new MemoryStream();

#if DEBUG
                Debug.Log("Loading graph " + i + "'s nodes");
#endif

                entry.Extract(str);
                str.Position = 0;
                BinaryReader reader = new BinaryReader(str);

                DeserializeNodes(i, reader);
            }

            for (int i = 0; i < graphs.Length; i++)
            {
                ZipEntry entry = zip["graph" + i + "_conns" + binaryExt];
                if (entry == null)
                {
                    continue;
                }

#if DEBUG
                Debug.Log("Loading graph " + i + "'s connections");
#endif
                MemoryStream str = new MemoryStream();

                entry.Extract(str);
                str.Position = 0;
                BinaryReader reader = new BinaryReader(str);

                DeserializeNodeConnections(i, reader);
            }
        }
Beispiel #29
0
        internal static void ExtractTextureEP(ZipFile zip, string modelFolder, string textureToExtract, string extractionDir, bool dontUseFolderStructure)
        {
            string fullPath = "";

            zip.FlattenFoldersOnExtract = dontUseFolderStructure;
            ZipEntry e = new ZipEntry();

            if (zip.ContainsEntry(fullPath = modelFolder + "/txt16/" + textureToExtract))
            {
                e = zip[fullPath];
            }
            else if (zip.ContainsEntry(fullPath = modelFolder + "/txt/" + textureToExtract))
            {
                e = zip[fullPath];
            }

            e.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
            e.Extract(extractionDir);
        }
Beispiel #30
0
        public BSPMap(string filename, bool loadFromPK3)
        {
            filename = Path.Combine("maps/", filename);

            // Look through all available .pk3 files to find the map.
            // The first map will be used, which doesn't match Q3 behavior, as it would use the last found map, but eh.
            if (loadFromPK3)
            {
                foreach (FileInfo info in new DirectoryInfo(Application.streamingAssetsPath).GetFiles())
                {
                    if (info.Name.EndsWith(".PK3") || info.Name.EndsWith(".pk3"))
                    {
                        using (ZipFile pk3 = ZipFile.Read(info.FullName))
                        {
                            if (pk3.ContainsEntry(filename))
                            {
                                ZipEntry entry = pk3[filename];
                                using (CrcCalculatorStream mapstream = pk3[filename].OpenReader())
                                {
                                    MemoryStream ms = new MemoryStream();
                                    entry.Extract(ms);
                                    BSP = new BinaryReader(ms);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                BSP = new BinaryReader(File.Open(filename, FileMode.Open));
            }


            // Read our header and lumps
            ReadHeader();
            ReadEntities();
            ReadTextures();
            ReadVertexes();
            ReadFaces();
            ReadMeshVerts();
            ReadLightmaps();

            // Comb through all of the available .pk3 files and load in any textures needed by the current map.
            // Textures in higher numbered .pk3 files will be used over ones in lower ones.
            foreach (FileInfo info in new DirectoryInfo(Application.streamingAssetsPath).GetFiles())
            {
                if (info.Name.EndsWith(".pk3") || info.Name.EndsWith(".PK3"))
                {
                    textureLump.PullInTextures(info.Name);
                }
            }

            BSP.Close();
        }
Beispiel #31
0
        bool LoadMod(string path)
        {
            try
            {
                ZipFile zf = ZipFile.Read(path);
                string  modInfoJsonText = "";
                Image   modIcon         = null;

                if (zf.ContainsEntry("modinfo.json"))
                {
                    modInfoJsonText = Zip.ReadText(zf["modinfo.json"]);
                }

                if (zf.ContainsEntry("modicon.png"))
                {
                    CrcCalculatorStream crc = zf["modicon.png"].OpenReader();
                    modIcon = Image.FromStream(crc);
                    crc.Close();
                }
                zf.Dispose();

                ModInfo modInfo = new ModInfo(path, modInfoJsonText, modIcon);

                if (!ModIDs.Contains(modInfo.ToString()))
                {
                    Mods.Add(modInfo);
                    ModIDs.Add(modInfo.ToString());
                    LF_ModList();
                    return(true);
                }
                else
                {
                    this.latestException = new Exception("This mod is already loaded. If you want to update it, remove the old version first.");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                this.latestException = ex;
                return(false);
            }
        }