Exemplo n.º 1
0
		public static ZipDirectory FromArchive(IArchive archive)
		{
			ZipDirectory root = new ZipDirectory();

			Dictionary<string, ZipDirectory> directories = new Dictionary<string, ZipDirectory>
			{
				{"", root}
			};

			foreach (IArchiveEntry entry in archive.Entries)
			{
				string entryKey = entry.Key.Trim('/');

				string directoryPath = entryKey.Substring(0, entryKey.LastIndexOf('/') + 1);
				string entryName = entryKey.Substring(entryKey.LastIndexOf('/') + 1);

				ZipDirectory container = directories[directoryPath];

				if (entry.IsDirectory)
				{
					ZipDirectory newDirectory = new ZipDirectory();

					container.Directories.Add(entryName, newDirectory);
					directories.Add(entry.Key, newDirectory);
				}
				else
				{
					container.Files.Add(entryName, entry);
				}
			}

			return root;
		}
Exemplo n.º 2
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public StudentSubmission(
     ClassroomMembership student,
     IArchive contents)
 {
     Student = student;
     Contents = contents;
 }
 public Archive(Stream fs, string password = null)
 {
     fs.Seek(0, SeekOrigin.Begin);
     if (ZipArchive.IsZipFile(fs))
     {
         fs.Seek(0, SeekOrigin.Begin);
         _arch = (IArchive)ZipArchive.Open(fs, password);
     }
     else if (RarArchive.IsRarFile(fs))
     {
         fs.Seek(0, SeekOrigin.Begin);
         _arch = (IArchive)RarArchive.Open(fs);
     }
     else if (TarArchive.IsTarFile(fs))
     {
         fs.Seek(0, SeekOrigin.Begin);
         _arch = (IArchive)TarArchive.Open(fs);
     }
     else if (SevenZipArchive.IsSevenZipFile(fs))
     {
         fs.Seek(0, SeekOrigin.Begin);
         _arch = (IArchive)SevenZipArchive.Open(fs);
     }
     else if (GZipArchive.IsGZipFile(fs))
     {
         fs.Seek(0, SeekOrigin.Begin);
         _arch = (IArchive)GZipArchive.Open(fs);
     }
     else
     {
         throw new InvalidOperationException("Not a valid archive (stream was " + fs.Length + " bytes long).");
     }
 }
		/// <summary>
		/// Writes the contents of a submission to an archive.
		/// </summary>
		private async Task WriteSubmissionToArchiveAsync(
			ZipArchive archive,
			Project project,
			ClassroomMembership student,
			IArchive templateContents,
			IArchive submissionContents)
		{
			var studentFolder = $"EclipseProjects\\{student.GitHubTeam}";

			// The project will contain all non-immutable submission files, 
			// plus all immutable and private files from the template project.

			var projectContents = submissionContents.Files
				.Where
				(
					entry => project.GetFileType(entry) == FileType.Public
				)
				.Concat
				(
					templateContents.Files.Where
					(
						entry => project.GetFileType(entry) != FileType.Public
					)
				)
				.ToList();

			foreach (var entry in projectContents)
			{
				if (ExcludeEntry(project, entry))
					continue;

				var contents = _transformer.GetFileContents(project, student, entry);

				var archiveFilePath = entry.FullPath;
				var archiveFileFolder = archiveFilePath.Contains("/")
					? archiveFilePath.Substring(0, archiveFilePath.LastIndexOf("/"))
					: archiveFilePath;

				var localFileFolder = $"{studentFolder}\\{archiveFileFolder}";
				var fileName = archiveFilePath.Substring(archiveFilePath.LastIndexOf("/") + 1);
				var localFilePath = $"{localFileFolder}\\{fileName}";

				// Add the file to the student project folder.
				var projectFolderEntry = archive.CreateEntry(localFilePath);
				using (Stream stream = projectFolderEntry.Open())
				{
					await stream.WriteAsync(contents, offset: 0, count: contents.Length);
				}

				// Add the file to the folder containing all files, if applicable.
				if (fileName.EndsWith(".java") && project.GetFileType(entry) == FileType.Public)
				{
					var allFilesEntry = archive.CreateEntry($"AllFiles\\{student.GitHubTeam}-{fileName}");
					using (Stream stream = allFilesEntry.Open())
					{
						await stream.WriteAsync(contents, offset: 0, count: contents.Length);
					}
				}
			}
		}
		/// <summary>
		/// Builds a submission archive containing the submissions of
		/// all students.
		/// </summary>
		public async Task<Stream> BuildSubmissionArchiveAsync(
			Project project,
			IArchive templateContents,
			IList<StudentSubmission> submissions)
		{
			var stream = _fileSystem.CreateNewTempFile();

			using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
			{
				foreach (var result in submissions)
				{
					await WriteSubmissionToArchiveAsync
					(
						archive,
						project,
						result.Student,
						templateContents,
						result.Contents
					);

					result.Contents.Dispose();
				}
			}

			stream.Position = 0;
			return stream;
		}
Exemplo n.º 6
0
 public void SendArchive(IArchive archive)
 {
     var archSize = archive.SizeOfArchive();
     Send(BitConverter.GetBytes(archSize));
     using (var br = new BinaryReader(File.Open(archive.Path, FileMode.Open, FileAccess.Read)))
         for (var i =0; i < archSize; i+=PacketSize)
             Send(br.ReadBytes(PacketSize));
 }
Exemplo n.º 7
0
 public void JoinArchive(string name, IArchive archive, IVersion version = null)
 {
     if (version != null)
         throw new GitHubException("Method JoinArchive with version NotImplemented", new NotImplementedException());
     var path = FullPath(name);
     version = LastVersion(path).AddVersion(1);
     archive.SaveTo(Path.Combine(path, version+".zip"));
 }
 private async Task CreateExtractorAsync() {
     try {
         _extractor = await Task.Run(() => CreateExtractor(Filename, Password));
     } catch (PasswordException) {
         IsPasswordRequired = true;
         DisposeHelper.Dispose(ref _extractor);
     }
 }
        public CompressedFileImageManager(string filePath)
        {
            _filePath = filePath;
            var fileExtension = Path.GetExtension(filePath).ToLower();
            _archive = SharpCompress.Archive.ArchiveFactory.Open(filePath);

            LoadEntries();
        }
Exemplo n.º 10
0
		public ArchiveThumbEditor(Form parent)
		{
			InitializeComponent();
			mParent = parent;
			mArchive = null;
			KeyPreview = true;
			mThumbResampled = false;
			mLargeFileThreshold = 1024 * 1024 * 1024; // 1GB
		}
Exemplo n.º 11
0
        public HomeController()
        {
            //_posty = new PostDAL();
            //_tagi = new TagDAL();
            _komentarze = new KomentarzDAL();

            _postTag = new PostTagDAL();
            _ustawienia = new UstawieniaServices();
            _archiwum = new ArchiveDAL();

            utworzArchiwum();
        }
Exemplo n.º 12
0
        /// <summary>
        /// Creates a new AbstractFileMonitor with the default archive and a collection of non-default archives that should be registered
        /// </summary>
        /// <param name="baseDirectory">The folder where this monitor stores it archives</param>
        /// <param name="defaultArchive">The default archive</param>
        /// <param name="otherArchives">A list of other archives that should be registered via <see cref="RegisterArchive(IArchive)"/></param>
        protected AbstractFileMonitor(string baseDirectory, IArchive defaultArchive, params IArchive[] otherArchives) {
            this.MonitorStoragePath = baseDirectory;
            this.registeredArchives = new HashSet<IArchive>();
            this.archiveMap = new Dictionary<string, IArchive>(StringComparer.InvariantCultureIgnoreCase);
            this.numberOfWorkingArchives = 0;
            this.monitorIsReady = true;
            this.UseAsyncMethods = false;

            RegisterArchive(defaultArchive, true);
            foreach(var archive in otherArchives) {
                this.RegisterArchive(archive, false);
            }
        }
 public void Init()
 {
     try
     {
         fileStream = File.OpenRead(archivePath);
         extractor = ArchiveFactory.Open(fileStream, SharpCompress.Common.Options.None);
         if (extractor.Entries != null)
             Files = extractor.Entries.Where(e => !e.IsDirectory).Select(e => e.FilePath).ToList();
     }
     catch (Exception ex)
     {
         Logger.LogError("Extractor: Failed top open archive '{0}', {1}", archivePath, ex);
     }
 }
Exemplo n.º 14
0
        private async Task <List <ImportFileItem> > GetFilesInArchive(SkyDriveItemType parentType, IStorageFile file)
        {
            List <ImportFileItem> listItems = new List <ImportFileItem>();

            if (file != null)
            {
                IRandomAccessStream accessStream = await file.OpenReadAsync();

                Stream s = accessStream.AsStreamForRead((int)accessStream.Size);

                //get list of file
                IArchive archive = null;

                if (parentType == SkyDriveItemType.Rar)
                {
                    archive = SharpCompress.Archive.Rar.RarArchive.Open(s);
                }
                else if (parentType == SkyDriveItemType.Zip)
                {
                    archive = SharpCompress.Archive.Zip.ZipArchive.Open(s);
                }
                else if (parentType == SkyDriveItemType.SevenZip)
                {
                    archive = SharpCompress.Archive.SevenZip.SevenZipArchive.Open(s);
                }

                foreach (var entry in archive.Entries)
                {
                    if (!entry.IsDirectory)
                    {
                        Stream data = new MemoryStream();
                        entry.WriteTo(data);
                        data.Position = 0;
                        String name = entry.FilePath;

                        SkyDriveItemType type = SkyDriveItemType.File;
                        int dotIndex          = -1;
                        if ((dotIndex = name.LastIndexOf('.')) != -1)
                        {
                            String substrName = name.Substring(dotIndex).ToLower();
                            type = SkyDriveImportPage.GetSkyDriveItemType(substrName);
                        }

                        if (type == SkyDriveItemType.File)
                        {
                            data.Close();
                            continue;
                        }

                        ImportFileItem listItem = new ImportFileItem()
                        {
                            Name   = name,
                            Type   = type,
                            Stream = data
                        };

                        listItems.Add(listItem);
                    }
                }

                //close the zip stream since we have the stream of each item inside it already
                s.Close();
                s = null;
            }

            return(listItems);
        }
Exemplo n.º 15
0
        public void UpdateArchiveRelationExtendValues(IArchive archive)
        {
            int siteId = archive.Category.Site.Id;
            //============ 更新 ============
            IDictionary<int, string> extendValues = new Dictionary<int, string>();
            IExtendField field;
            foreach (IExtendValue value in archive.ExtendValues)
            {
                field = this.GetExtendFieldById(siteId, value.Field.Id);

                //如果为默认数据,也要填写进去,以免模板获取不到
                if (value.Value != null)
                    extendValues.Add(value.Field.Id,
                    //value.Value == field.DefaultValue ? String.Empty : value.Value);
                    value.Value);
            }

            this.extendDAL.InsertDataExtendFields(ExtendRelationType.Archive, archive.Id, extendValues);

            /*
            foreach (DataExtendField f in this.GetExtendFileds(relationID))
            {
                if (extendData.ContainsKey(f.AttrId))
                {
                    dal.UpdateDataExtendFieldValue(relationID, f.AttrId, extendData[f.AttrId]);

                    extendData.Remove(f.AttrId);
                }
            }

            //=========== 增加 ===========
            dal.InsertDataExtendFields(relationID, extendData);
               */
        }
Exemplo n.º 16
0
 public UnknownFile(IArchive fileContainer) : base(fileContainer)
 {
 }
Exemplo n.º 17
0
 public static IArchiveEntry RetreiveUniqueFileFromArchiveEndingWith(IArchive archive, string fileNameEnd)
 {
     return(archive.Entries.SingleOrDefault(e =>
                                            e.Key != null &&
                                            e.Key.EndsWith(fileNameEnd, StringComparison.InvariantCultureIgnoreCase)));
 }
 public static bool TryOpen(string filePath, ReaderOptions options, ArchiveTypeMask archiveTypes, out IArchive archive)
 {
     filePath.CheckNotNullOrEmpty("filePath");
     return(TryOpen(new FileInfo(filePath), options, archiveTypes, out archive));
 }
 public static bool TryOpen(Stream stream, ReaderOptions readerOptions, ArchiveTypeMask archiveTypes, out IArchive archive)
 {
     stream.CheckNotNull("stream");
     if (!stream.CanRead || !stream.CanSeek)
     {
         throw new ArgumentException("Stream should be readable and seekable");
     }
     readerOptions = readerOptions ?? new ReaderOptions();
     if (archiveTypes.HasFlag(ArchiveTypeMask.Zip) && ZipArchive.IsZipFile(stream, null))
     {
         stream.Seek(0, SeekOrigin.Begin);
         archive = ZipArchive.Open(stream, readerOptions);
         return(true);
     }
     stream.Seek(0, SeekOrigin.Begin);
     if (archiveTypes.HasFlag(ArchiveTypeMask.SevenZip) && SevenZipArchive.IsSevenZipFile(stream))
     {
         stream.Seek(0, SeekOrigin.Begin);
         archive = SevenZipArchive.Open(stream, readerOptions);
         return(true);
     }
     stream.Seek(0, SeekOrigin.Begin);
     if (archiveTypes.HasFlag(ArchiveTypeMask.GZip) && GZipArchive.IsGZipFile(stream))
     {
         stream.Seek(0, SeekOrigin.Begin);
         archive = GZipArchive.Open(stream, readerOptions);
         return(true);
     }
     stream.Seek(0, SeekOrigin.Begin);
     if (archiveTypes.HasFlag(ArchiveTypeMask.Rar) && RarArchive.IsRarFile(stream, readerOptions))
     {
         stream.Seek(0, SeekOrigin.Begin);
         archive = RarArchive.Open(stream, readerOptions);
         return(true);
     }
     stream.Seek(0, SeekOrigin.Begin);
     if (archiveTypes.HasFlag(ArchiveTypeMask.Tar) && TarArchive.IsTarFile(stream))
     {
         stream.Seek(0, SeekOrigin.Begin);
         archive = TarArchive.Open(stream, readerOptions);
         return(true);
     }
     archive = null;
     return(false);
 }
Exemplo n.º 20
0
        private List <SDCardListItem> GetFilesInArchive(SDCardListItem item)
        {
            List <SDCardListItem> listItems = new List <SDCardListItem>();


            if (item.Stream != null)
            {
                //fix SD card stream bug
                Stream s = new MemoryStream();
                item.Stream.CopyTo(s);
                s.Position = 0;
                item.Stream.Close();// close because we copy it to s already
                item.Stream = null;

                //get list of file
                IArchive archive = null;

                if (item.Type == SkyDriveItemType.Rar)
                {
                    archive = SharpCompress.Archive.Rar.RarArchive.Open(s);
                }
                else if (item.Type == SkyDriveItemType.Zip)
                {
                    archive = SharpCompress.Archive.Zip.ZipArchive.Open(s);
                }
                else if (item.Type == SkyDriveItemType.SevenZip)
                {
                    archive = SharpCompress.Archive.SevenZip.SevenZipArchive.Open(s);
                }


                foreach (var entry in archive.Entries)
                {
                    if (!entry.IsDirectory)
                    {
                        Stream data = new MemoryStream();
                        entry.WriteTo(data);
                        data.Position = 0;
                        String name = entry.FilePath;

                        SkyDriveItemType type = SkyDriveItemType.File;
                        int dotIndex          = -1;
                        if ((dotIndex = name.LastIndexOf('.')) != -1)
                        {
                            String substrName = name.Substring(dotIndex).ToLower();
                            if (substrName.Equals(".gb") || substrName.Equals(".gbc") || substrName.Equals(".gba"))
                            {
                                type = SkyDriveItemType.ROM;
                            }
                            else if (substrName.Equals(".sgm"))
                            {
                                type = SkyDriveItemType.Savestate;
                            }
                            else if (substrName.Equals(".sav"))
                            {
                                type = SkyDriveItemType.SRAM;
                            }
                        }

                        if (type == SkyDriveItemType.File)
                        {
                            data.Close();
                            continue;
                        }

                        SDCardListItem listItem = new SDCardListItem()
                        {
                            Name       = name,
                            Type       = type,
                            isFolder   = false,
                            ParentPath = item.ThisFile.Path,
                            Stream     = data
                        };

                        listItems.Add(listItem);
                    }
                }

                //close the zip stream since we have the stream of each item inside it already
                s.Close();
            }

            return(listItems);
        }
Exemplo n.º 21
0
 public static IEnumerable <IArchiveEntry> RetreiveFilesFromArchiveStartingWith(IArchive archive, string fileNameStart)
 {
     return(archive.Entries
            .Where(e =>
                   e.Key.StartsWith(fileNameStart, StringComparison.InvariantCultureIgnoreCase) &&
                   !e.IsDirectory));
 }
 /// <summary>
 /// Create file provider that reads <paramref name="archive"/>.
 /// </summary>
 /// <param name="archive"></param>
 /// <param name="hintPath">(optional) clue to path of the package file</param>
 /// <param name="dateTime">(optional) Date time for folder entries</param>
 /// <param name="convertBackslashesToSlashes">if true converts '\' to '/'</param>
 public ArchiveFileProvider(IArchive archive, string hintPath = null, DateTimeOffset?dateTime = null, bool convertBackslashesToSlashes = false) : base(hintPath, dateTime)
 {
     this.streamProvider = new ArchiveStreamProvider(archive ?? throw new ArgumentNullException(nameof(archive)), belatedDisposeList);
     AddArchiveEntries(this.root, archive.Entries, streamProvider, convertBackslashesToSlashes);
 }
Exemplo n.º 23
0
 public static BigInteger GetBlockCount(this IArchive archive)
 {
     return(archive.Size / DomainSettings.ArchiveBlockSize);
 }
 public ArchiveStreamProvider(IArchive archive, IBelatedDisposeList belateSource)
 {
     this.archive      = archive;
     this.belateSource = belateSource;
 }
Exemplo n.º 25
0
 public IEnumerable <IExtractEntry> GetEntries(IArchive archive)
 {
     return(archive.Entries.Select(e => new ExtractEntry((T)e)));
 }
Exemplo n.º 26
0
 public void Apply(ComicBookFile comic, FileInfo file, IArchive archive, IEnumerable <IArchiveEntry> pages)
 {
     comic.Publisher = publisherMap.Where(n => comic.Path.Contains(n.Key))
                       .Select(n => n.Value)
                       .FirstOrDefault() ?? string.Empty;
 }
Exemplo n.º 27
0
 public ZipUpdater(FileInfo archive, int discoveryPriority, int downloadPriority = 101) : base(archive.Name, discoveryPriority, downloadPriority)
 {
     _archive = ArchiveFactory.Open(archive);
 }
Exemplo n.º 28
0
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
        public static string extraer(Activity contexto, ProgressDialog dialogoprogreso, string archivo, string console = "")
        {
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos

            string Innerarchivo = archivo;
            string directorio   = "";
            contexto.RunOnUiThread(() =>
            {
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                dialogoprogreso = new ProgressDialog(contexto);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos

                dialogoprogreso.SetCanceledOnTouchOutside(false);
                dialogoprogreso.SetCancelable(false);
                dialogoprogreso.SetTitle("Extrayendo rom...");
                dialogoprogreso.SetMessage("Esto solo pasara una vez con este rom");
                dialogoprogreso.Show();
            });
            if (!File.Exists(System.IO.Path.ChangeExtension(archivo, null)))
            {
                try
                {
                    IArchive entr     = null;
                    string   entrykey = "";
                    var      archive  = ArchiveFactory.Open(archivo);
                    directorio = System.IO.Path.GetDirectoryName(archivo);
                    if (console != "Dreamcast")
                    {
                        if (console == "PSX")
                        {
                            entr     = archive.Entries.Where(ax => ax.Key.EndsWith(".bin")).FirstOrDefault().Archive;
                            entrykey = archive.Entries.Where(ax => ax.Key.EndsWith(".bin")).FirstOrDefault().Key;
                        }
                        else
                        {
                            entr     = archive.Entries.ToList()[0].Archive;
                            entrykey = archive.Entries.ToList()[0].Key;
                        }


                        if (!File.Exists(directorio + "/" + entrykey))
                        {
                            entr.WriteToDirectory(directorio);
                        }
                    }
                    else
                    {
                        directorio = Directory.CreateDirectory(System.IO.Path.GetDirectoryName(archivo) + "/" + System.IO.Path.GetFileNameWithoutExtension(archivo)).FullName;

                        if (directorio.EndsWith("/"))
                        {
                            directorio = directorio.Remove(directorio.Length - 1);
                        }


                        foreach (var entry in archive.Entries)
                        {
                            if (entry.Key.ToLower().EndsWith(".gdi") || entry.Key.ToLower().EndsWith(".chd") || entry.Key.ToLower().EndsWith(".cdi"))
                            {
                                entrykey = entry.Key;
                            }


                            entry.WriteToDirectory(directorio);
                        }
                    }


                    // File.Delete(archivo);
                    var lector = JsonConvert.DeserializeObject <List <Models.registry> > (File.ReadAllText(cachepath + "/downloads.json"));
                    for (int i = 0; i < lector.Count; i++)
                    {
                        if (lector[i].path == archivo)
                        {
                            lector[i].path = directorio + "/" + entrykey;
                            break;
                        }
                    }



                    var arc = File.CreateText(cachepath + "/downloads.json");
                    arc.Write(JsonConvert.SerializeObject(lector));
                    arc.Close();


                    Innerarchivo = directorio + "/" + entrykey;
                    File.Delete(archivo);
                    MainActivity.gettearinstancia().cargardescargas();
                }
                catch (Exception)
                {
                    if (!Innerarchivo.EndsWith(".zip") && !Innerarchivo.EndsWith("7z") && !Innerarchivo.EndsWith("rar"))
                    {
                        contexto.RunOnUiThread(() => { Toast.MakeText(contexto, "Archivo ya extraido", ToastLength.Long).Show(); });
                    }
                    else
                    {
                        contexto.RunOnUiThread(() => { Toast.MakeText(contexto, "Error en la extraccion.Puede que no se pueda escribir en esa ruta", ToastLength.Long).Show(); });
                    }
                }
            }

            contexto.RunOnUiThread(() =>
            {
                dialogoprogreso.Dismiss();
            });



            return(Innerarchivo);
        }
Exemplo n.º 29
0
		private void ReSampleThumb(object sender, EventArgs e)
		{
			if (mItem != null)
			{
				try
				{
					string imageName = archiveViewer.SelectedItem.ToString();
					// Note: may throw exception when imageName has illegal characters
					string tempName = ThumbUtility.GetTempFolderPath(mItem.FilePath) + mItem.FileName + " - " + Path.GetFileName(imageName);
					if (!ThumbUtility.IsImageFile(imageName))
					{
						MessageBox.Show(imageName + " is not an image.");
						return;
					}
					if (mArchive == null)
					{
						mArchive = ArchiveFactory.Open(mItem.FilePath);
					}
					foreach (IArchiveEntry entry in mArchive.Entries)
					{
						if (entry.IsDirectory || entry.Key != imageName) continue;
						entry.WriteToFile(tempName, scOptions);
						break;
					}
					if (File.Exists(tempName))
					{
						using (Image img = Image.FromFile(tempName))
						{
							if (thumbViewer.Image != null && mThumbResampled)
								thumbViewer.Image.Dispose();
							// Note: may throw exception when img is not a valid image
							thumbViewer.Image = new Bitmap(img);
							mThumbResampled = true;
						}
						File.Delete(tempName);
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.ToString());
					CloseEditor();
				}
			}
			else
			{
				MessageBox.Show("Please select an archive first.");
				CloseEditor();
			}
		}
Exemplo n.º 30
0
        public ArchiveManagerViewModel(Window window, IArchive archive, string archiveFileName)
        {
            Window           = window;
            Archive          = archive;
            _archiveFileName = archiveFileName;
            Entries          = new GenericListModel <ArchiveEntryViewModel, ArchiveEntryViewModel>(
                archive.Entries.Select(x => new ArchiveEntryViewModel(x)),
                Getter, Setter);

            OpenCommand = new RelayCommand(o =>
            {
                Window.DialogResult = true;
                Window.Close();
            }, o => IsSelected);

            ImportCommand = new RelayCommand(o =>
            {
                var selectedEntry = SelectedValue;
                if (selectedEntry == null)
                {
                    return;
                }

                FileDialog.OnOpen(fileName =>
                {
                    using (var stream = File.OpenRead(fileName))
                    {
                        var data = new byte[stream.Length];
                        stream.Read(data, 0, data.Length);
                        selectedEntry.ImportData(data);
                    }

                    using (var stream = File.Create(_archiveFileName))
                        archive.Write(stream);

                    ShowInfoMessageBox("Save imported with success!");
                }, Filters);
            }, o => IsSelected);

            ExportCommand = new RelayCommand(o =>
            {
                var selectedEntry = SelectedEntry;
                if (selectedEntry == null)
                {
                    return;
                }

                FileDialog.OnSave(fileName =>
                {
                    using (var stream = File.Create(fileName))
                    {
                        stream.Write(selectedEntry.Data, 0, selectedEntry.Data.Length);
                    }
                }, Filters, $"{SelectedEntry?.Name ?? "empty save"}.bin", Window);
            }, o => !IsSelectedEmpty);

            CopyCommand = new RelayCommand(o =>
            {
            }, o => IsSelected);

            PasteCommand = new RelayCommand(o =>
            {
            }, o => IsSelected);

            DeleteCommand = new RelayCommand(o =>
            {
                Entries.SelectedValue?.Erase();
            }, o => !IsSelectedEmpty);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Writes the contents of a submission to an archive.
        /// </summary>
        private async Task WriteSubmissionToArchiveAsync(
            ZipArchive archive,
            Project project,
            ClassroomMembership student,
            IArchive templateContents,
            IArchive submissionContents,
            ProjectSubmissionDownloadFormat format)
        {
            bool includeEclipseProjects =
                (
                    format == ProjectSubmissionDownloadFormat.Eclipse ||
                    format == ProjectSubmissionDownloadFormat.All
                );
            bool includeFlatFiles =
                (
                    format == ProjectSubmissionDownloadFormat.Flat ||
                    format == ProjectSubmissionDownloadFormat.All
                );

            // Submissions are grouped by section.  If a student is in multiple
            // sections, just grab the first one
            string sectionName = student.SectionMemberships.First().Section.Name;

            var studentFolder = $"EclipseProjects\\{sectionName}\\{student.GitHubTeam}";

            // The project will contain all non-immutable submission files,
            // plus all immutable and private files from the template project.

            var projectContents = submissionContents.Files
                                  .Where
                                  (
                entry => project.GetFileType(entry) == FileType.Public
                                  )
                                  .Concat
                                  (
                templateContents.Files.Where
                (
                    entry => project.GetFileType(entry) != FileType.Public
                )
                                  )
                                  .ToList();

            foreach (var entry in projectContents)
            {
                if (ExcludeEntry(project, entry))
                {
                    continue;
                }

                var contents        = _transformer.GetFileContents(project, student, entry);
                var archiveFilePath = entry.FullPath;
                var fileName        = archiveFilePath.Substring(archiveFilePath.LastIndexOf("/") + 1);

                if (includeEclipseProjects)
                {
                    var archiveFileFolder = archiveFilePath.Contains("/")
                                                ? archiveFilePath.Substring(0, archiveFilePath.LastIndexOf("/"))
                                                : archiveFilePath;

                    var localFileFolder = $"{studentFolder}\\{archiveFileFolder}";
                    var localFilePath   = $"{localFileFolder}\\{fileName}";

                    // Add the file to the student project folder.
                    var projectFolderEntry = archive.CreateEntry(localFilePath);
                    using (Stream stream = projectFolderEntry.Open())
                    {
                        await stream.WriteAsync(contents, offset : 0, count : contents.Length);
                    }
                }

                // Add the file to the folder containing all files, if applicable.
                if (includeFlatFiles && fileName.EndsWith(".java") && project.GetFileType(entry) == FileType.Public)
                {
                    // Files are grouped by base name, and then by section
                    var baseFileName  = fileName.Substring(0, fileName.LastIndexOf("."));
                    var allFilesEntry = archive.CreateEntry($"AllFiles\\{baseFileName}\\{sectionName}\\{student.GitHubTeam}-{fileName}");
                    using (Stream stream = allFilesEntry.Open())
                    {
                        await stream.WriteAsync(contents, offset : 0, count : contents.Length);
                    }
                }
            }
        }
        /// <summary>
        /// Extracts the file from the archive with the passed key.
        /// </summary>
        /// <param name="node">The node to install the file from.</param>
        /// <param name="path">The path to install the file to.</param>
        /// <param name="silent">Determines if info messages should be added displayed.</param>
        private static void ExtractFile(ModNode node, string path, bool silent = false, bool overrideOn = false)
        {
            if (node == null)
            {
                return;
            }

            string destination = path;

            if (!string.IsNullOrEmpty(destination))
            {
                destination = KSPPathHelper.GetAbsolutePath(destination);
            }

            using (IArchive archive = ArchiveFactory.Open(node.ZipRoot.Key))
            {
                IArchiveEntry entry = archive.Entries.FirstOrDefault(e => e.FilePath.Equals(node.Key, StringComparison.CurrentCultureIgnoreCase));
                if (entry == null)
                {
                    return;
                }

                node.IsInstalled = false;
                if (!File.Exists(destination))
                {
                    try
                    {
                        // create new file.
                        entry.WriteToFile(destination);
                        node.IsInstalled = true;

                        if (!silent)
                        {
                            Messenger.AddInfo(string.Format(Messages.MSG_FILE_EXTRACTED_0, destination));
                        }
                    }
                    catch (Exception ex)
                    {
                        Messenger.AddError(string.Format(Messages.MSG_FILE_EXTRACTED_ERROR_0, destination), ex);
                    }
                }
                else if (overrideOn)
                {
                    try
                    {
                        // delete old file
                        File.Delete(destination);

                        // create new file.
                        entry.WriteToFile(destination);

                        if (!silent)
                        {
                            Messenger.AddInfo(string.Format(Messages.MSG_FILE_EXTRACTED_0, destination));
                        }
                    }
                    catch (Exception ex)
                    {
                        Messenger.AddError(string.Format(Messages.MSG_FILE_EXTRACTED_ERROR_0, destination), ex);
                    }
                }

                node.IsInstalled = File.Exists(destination);
                node.NodeType    = (node.IsInstalled) ? NodeType.UnknownFileInstalled : NodeType.UnknownFile;
            }
        }
 public static bool TryOpen(FileInfo fileInfo, ReaderOptions options, ArchiveTypeMask archiveTypes, out IArchive archive)
 {
     fileInfo.CheckNotNull("fileInfo");
     options = options ?? new ReaderOptions {
         LeaveStreamOpen = false
     };
     using (var stream = fileInfo.OpenRead())
     {
         if (archiveTypes.HasFlag(ArchiveTypeMask.Zip) && ZipArchive.IsZipFile(stream, null))
         {
             archive = ZipArchive.Open(fileInfo, options);
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (archiveTypes.HasFlag(ArchiveTypeMask.SevenZip) && SevenZipArchive.IsSevenZipFile(stream))
         {
             archive = SevenZipArchive.Open(fileInfo, options);
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (archiveTypes.HasFlag(ArchiveTypeMask.GZip) && GZipArchive.IsGZipFile(stream))
         {
             archive = GZipArchive.Open(fileInfo, options);
             return(true);
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (archiveTypes.HasFlag(ArchiveTypeMask.Rar) && RarArchive.IsRarFile(stream, options))
         {
             archive = RarArchive.Open(fileInfo, options);
             return(true);
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (archiveTypes.HasFlag(ArchiveTypeMask.Tar) && TarArchive.IsTarFile(stream))
         {
             archive = TarArchive.Open(fileInfo, options);
             return(true);
         }
     }
     archive = null;
     return(false);
 }
Exemplo n.º 34
0
 public ArchiveWriteToStream(IWriteToStream realWriteToStream, IArchive archive, IArchiveEntry entry)
 {
     this.realWriteToStream = realWriteToStream;
     Archive = archive;
     Entry   = entry;
 }
Exemplo n.º 35
0
 private void Close(string[] args)
 {
     _currentArchive?.Dispose();
     _currentArchive = null;
     Console.WriteLine();
 }
Exemplo n.º 36
0
        public static bool TryParse(WikiPage page,
                                    string directory,
                                    bool allowSource,
                                    L10i l10i,
                                    out IArchive archive)
        {
            archive = null;
            Dictionary<string, string> values;
            if (!TryParseTemplate(page.Text, out values))
            {
                return false;
            }

            int days = 14;
            if (values.ContainsKey("срок"))
            {
                int.TryParse(values["срок"], out days);
            }

            int forcedArchivationDelay = 0;
            if (values.ContainsKey("задержка принудительной архивации"))
            {
                int.TryParse(values["задержка принудительной архивации"], out forcedArchivationDelay);
            }

            int minimalSize = 3 * 1024;
            if (values.ContainsKey("размер правки"))
            {
                int.TryParse(values["размер правки"], out minimalSize);
            }

            int archiveSize = 70 * 1024;
            if (values.ContainsKey("размер архива"))
            {
                int.TryParse(values["размер архива"], out archiveSize);
            }

            bool checkForResult = false;
            if (values.ContainsKey("итог"))
            {
                string value = values["итог"].ToLower();
                if (value == "да")
                {
                    checkForResult = true;
                }
            }

            string pageName = page.Title;
            if (allowSource && values.ContainsKey("обрабатывать"))
            {
                pageName = values["обрабатывать"];
            }

            string removeFromText = "";
            if (values.ContainsKey("убирать из архива"))
            {
                removeFromText = values["убирать из архива"];
            }

            string accepted = "";
            if (values.ContainsKey("решения"))
            {
                accepted = values["решения"];
            }

            string rejected = "";
            if (values.ContainsKey("отклонённые заявки"))
            {
                rejected = values["отклонённые заявки"];
            }

            string format = pageName + "/Архив/%(номер)";
            if (values.ContainsKey("формат"))
            {
                format = pageName + "/" + values["формат"];
            }

            string header = "{{closed}}\n";
            if (values.ContainsKey("заголовок"))
            {
                header = values["заголовок"];
            }

            if (values.ContainsKey("страница"))
            {
                format = pageName + "/" + values["страница"];
            }

            if (allowSource && values.ContainsKey("абсолютный путь"))
            {
                format = values["формат"];
            }

            int topics = 0;
            if (values.ContainsKey("тем в архиве"))
            {
                int.TryParse(values["тем в архиве"], out topics);
            }
            bool newSectionsDown = true;
            if (values.ContainsKey("новые"))
            {
                if (values["новые"].ToLower() == "сверху")
                {
                    newSectionsDown = false;
                }
            }

            var onHold = new List<string>();
            if (values.ContainsKey("пропускать с"))
            {
                string[] separators;
                if (values["пропускать с"].Contains("\""))
                {
                    separators = new string[] { "\"," };
                }
                else
                {
                    separators = new string[] { "," };
                }
                string[] cats = values["пропускать с"].Split(separators,
                    StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < cats.Length; ++i)
                {
                    string cat = cats[i].Replace("\"", "").Trim();
                    if (!string.IsNullOrEmpty(cat))
                    {
                        onHold.Add(cat);
                    }
                }
            }

            var lookForLine = new List<string>();
            if (values.ContainsKey("архивировать с"))
            {
                string[] separators;
                if (values["архивировать с"].Contains("\""))
                {
                    separators = new string[] { "\"," };
                }
                else
                {
                    separators = new string[] { "," };
                }
                string[] cats = values["архивировать с"].Split(separators,
                    StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < cats.Length; ++i)
                {
                    string cat = cats[i].Replace("\"", "").Trim();
                    if (!string.IsNullOrEmpty(cat))
                    {
                        lookForLine.Add(cat);
                    }
                }
            }

            if (values.ContainsKey("тип"))
            {
                string t = values["тип"].ToLower();
                if (t == "страница")
                {
                    archive = new Archive(l10i,
                        pageName,
                        directory,
                        days,
                        format,
                        header,
                        lookForLine,
                        onHold,
                        removeFromText,
                        checkForResult,
                        newSectionsDown,
                        minimalSize,
                        forcedArchivationDelay);
                }
                else if (t == "месяц")
                {
                    archive = new ArchiveByMonth(l10i,
                        pageName,
                        directory,
                        days,
                        format,
                        header,
                        lookForLine,
                        onHold,
                        removeFromText,
                        checkForResult,
                        newSectionsDown,
                        minimalSize,
                        forcedArchivationDelay);
                }
                else if (t == "год")
                {
                    archive = new ArchiveByYear(l10i,
                        pageName,
                        directory,
                        days,
                        format,
                        header,
                        lookForLine,
                        onHold,
                        removeFromText,
                        checkForResult,
                        newSectionsDown,
                        minimalSize,
                        forcedArchivationDelay);
                }
                else if (t == "полгода")
                {
                    archive = new ArchiveByHalfYear(l10i,
                        pageName,
                        directory,
                        days,
                        format,
                        header,
                        lookForLine,
                        onHold,
                        removeFromText,
                        checkForResult,
                        newSectionsDown,
                        minimalSize,
                        forcedArchivationDelay);
                }
                else if (t == "квартал")
                {
                    archive = new ArchiveByQuarter(l10i,
                        pageName,
                        directory,
                        days,
                        format,
                        header,
                        lookForLine,
                        onHold,
                        removeFromText,
                        checkForResult,
                        newSectionsDown,
                        minimalSize,
                        forcedArchivationDelay);
                }
                else if (t == "нумерация" && topics > 0)
                {
                    archive = new ArchiveByTopicNumber(l10i,
                        pageName,
                        directory,
                        days,
                        format,
                        header,
                        lookForLine,
                        onHold,
                        removeFromText,
                        checkForResult,
                        newSectionsDown,
                        topics,
                        minimalSize,
                        forcedArchivationDelay);
                }
                else if (allowSource && t == "заявки на арбитраж")
                {
                    archive = new RequestsForArbitrationArchive(pageName,
                        accepted,
                        rejected,
                        days,
                        directory);
                }
            }
            if (archive != null)
            {
                Archive a = archive as Archive;
                if (a != null &&
                    values.ContainsKey("убирать ссылки") &&
                    values["убирать ссылки"].ToLower() == "да")
                {
                    a.Processor = RemoveHttp;
                }
                return true;
            }
            return false;
        }
        /// <summary>
        /// Creates a tree of TreeNodeMod nodes that represent the content of a mod archive.
        /// </summary>
        /// <param name="modInfo">The ModInfo of the mod the create a tree for.</param>
        /// <param name="silent">Determines if info messages should be added.</param>
        /// <returns>A tree of TreeNodeMod nodes that represent the content of a mod archive.</returns>
        public static ModNode CreateModNode(ModInfo modInfo, bool silent = false)
        {
            if (File.Exists(modInfo.LocalPath))
            {
                // Get AVC version file informations.
                if (OptionsController.AVCSupportOnOff)
                {
                    AVCInfo avcInfo = TryReadAVCVersionFile(modInfo.LocalPath);
                    if (avcInfo != null)
                    {
                        ImportAvcInfo(avcInfo, ref modInfo);
                    }
                }

                // Still no name? Use filename then
                if (string.IsNullOrEmpty(modInfo.Name))
                {
                    modInfo.Name = Path.GetFileNameWithoutExtension(modInfo.LocalPath);
                }

                ModNode node = new ModNode(modInfo);
                using (IArchive archive = ArchiveFactory.Open(modInfo.LocalPath))
                {
                    char   seperator = '/';
                    string extension = Path.GetExtension(modInfo.LocalPath);
                    if (extension != null && extension.Equals(Constants.EXT_RAR, StringComparison.CurrentCultureIgnoreCase))
                    {
                        seperator = '\\';
                    }

                    // create a TreeNode for every archive entry
                    foreach (IArchiveEntry entry in archive.Entries)
                    {
                        CreateModNode(entry.FilePath, node, seperator, entry.IsDirectory, silent);
                    }
                }

                // Destination detection
                switch (OptionsController.DestinationDetectionType)
                {
                case DestinationDetectionType.SmartDetection:
                    // Find installation root node (first folder that contains (Parts or Plugins or ...)
                    if (!FindAndSetDestinationPaths(node) && !silent)
                    {
                        Messenger.AddInfo(string.Format(Messages.MSG_ROOT_NOT_FOUND_0, node.Text));
                    }

                    if (OptionsController.CopyToGameData)
                    {
                        if (!silent)
                        {
                            Messenger.AddInfo(string.Format(Messages.MSG_DESTINATION_0_SET_TO_GAMEDATA, node.Text));
                        }
                        SetDestinationPaths(node, KSPPathHelper.GetPath(KSPPaths.GameData));
                    }
                    break;

                case DestinationDetectionType.SimpleDump:
                    if (!silent)
                    {
                        Messenger.AddInfo(string.Format(Messages.MSG_DESTINATION_0_SET_TO_GAMEDATA, node.Text));
                    }
                    SetDestinationPaths(node, KSPPathHelper.GetPath(KSPPaths.GameData));
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                SetToolTips(node);
                CheckNodesWithDestination(node);

                return(node);
            }
            else
            {
                if (!silent)
                {
                    Messenger.AddInfo(string.Format(Messages.MSG_MOD_ZIP_NOT_FOUND_0, modInfo.LocalPath));
                }
            }

            return(null);
        }
Exemplo n.º 38
0
 public ArchiveStrategy(string FileOutName, string BaseDir, string FileInName, IArchive iarchive)
 {
     this._FileOutName = FileOutName; this._BaseDir = BaseDir; this._FileInName = FileInName; this._iarchive = iarchive;
 }
Exemplo n.º 39
0
        /// <summary>
        /// Convert a Microsoft Office installer from Retail to Volume, or vice-versa
        /// </summary>
        /// <param name="licenseChannel">Current License Channel</param>
        /// <param name="productName">Microsoft Office Product to Convert</param>
        public static void ChangeChannel(string licenseChannel, string productName)
        {
            string architecture = InstallerInformation.InstallerArchitecture;
            string retailFolder = new ProductListRetail().GetProductFolder(productName);
            string volumeFolder = new ProductListVolume().GetProductFolder(productName);

            string fullInstallerPath = string.Empty;

            if (licenseChannel == "Retail")
            {
                fullInstallerPath = InstallerInformation.InstallerPath + retailFolder + Path.DirectorySeparatorChar;
            }
            else if (licenseChannel == "Volume")
            {
                fullInstallerPath = InstallerInformation.InstallerPath + volumeFolder + Path.DirectorySeparatorChar;
            }

            XmlDocument doc = new XmlDocument();

            byte[] patchXml;
            switch (InstallerInformation.SetupVersionFull)
            {
            case "14.0.4755.1000":
                patchXml = Resources.Office14_XML;
                break;

            case "15.0.4420.1017":
            case "15.0.4433.1506":
            case "15.0.4454.1000":
                patchXml = Resources.Office15_XML;
                break;

            case "15.0.4569.1503":
                patchXml = Resources.Office15SP1_XML;
                break;

            // TODO: Office 2016 Channel Changer
            default:
                throw new Exception("Unsupported Microsoft Office Edition!");
            }

            doc.Load(new MemoryStream(CommonUtilities.DecompressResource(patchXml)));

            // Root
            XmlElement root = doc.DocumentElement;

            if (root != null)
            {
                // Products Node
                XmlNodeList productList = root.ChildNodes;

                // Find Desired Product Node in Products Node
                XmlNode product = null;
                foreach (XmlNode productInstance in productList)
                {
                    XmlAttributeCollection productAttributes = productInstance.Attributes;
                    if (productAttributes != null && productAttributes["name"].Value == productName)
                    {
                        product = productInstance;
                        break;
                    }
                }

                // Product Unsupported
                if (product == null)
                {
                    throw new ApplicationException("This product is not supported due to lack of patches.");
                }

                // Patch Product
                PatchProcessor(product, fullInstallerPath, licenseChannel, architecture);
            }

            #region File Renaming, Zip Files, and Cleanup
            // Rename Folders
            if (licenseChannel == "Retail")
            {
                Directory.Move(fullInstallerPath, InstallerInformation.InstallerPath + Path.DirectorySeparatorChar + volumeFolder);
            }
            else if (licenseChannel == "Volume")
            {
                Directory.Move(fullInstallerPath, InstallerInformation.InstallerPath + Path.DirectorySeparatorChar + retailFolder);
            }

            // Get Extraction Folder
            string unpackDirectoryAdmin   = InstallerInformation.InstallerPath + Path.DirectorySeparatorChar + "Admin";
            string unpackDirectoryProduct = InstallerInformation.InstallerPath + Path.DirectorySeparatorChar;
            string unpackDirectorySetup   = InstallerInformation.InstallerPath + Path.DirectorySeparatorChar;
            if (licenseChannel == "Retail")
            {
                unpackDirectoryProduct += volumeFolder;
            }
            else if (licenseChannel == "Volume")
            {
                unpackDirectoryProduct += retailFolder;
            }

            // Create Admin Folder if it doesn't exist
            if (Directory.Exists(InstallerInformation.InstallerPath + Path.DirectorySeparatorChar + "Admin"))
            {
                return;
            }

            // Extract Archives
            byte[] x86, x64, shared, productZip32, setupZip32, productZip64, setupZip64;
            switch (InstallerInformation.SetupVersionFull)
            {
            case "14.0.4755.1000":
                x86          = Resources.Office14_Admin32;
                x64          = Resources.Office14_Admin64;
                shared       = Resources.Office14_AdminShared;
                productZip32 = null;
                productZip64 = null;
                setupZip32   = null;
                setupZip64   = null;
                break;

            case "15.0.4420.1017":
            case "15.0.4433.1506":
            case "15.0.4454.1000":
                x86          = Resources.Office15_Admin32;
                x64          = Resources.Office15_Admin64;
                shared       = Resources.Office15_AdminShared;
                productZip32 = Resources.Office15_ProductRoot32;
                productZip64 = Resources.Office15_ProductRoot64;
                setupZip32   = Resources.Office15_SetupRoot32;
                setupZip64   = Resources.Office15_SetupRoot64;
                break;

            case "15.0.4569.1503":
                x86          = Resources.Office15SP1_Admin32;
                x64          = Resources.Office15SP1_Admin64;
                shared       = Resources.Office15SP1_AdminShared;
                productZip32 = Resources.Office15SP1_ProductRoot32;
                productZip64 = Resources.Office15SP1_ProductRoot64;
                setupZip32   = Resources.Office15SP1_SetupRoot32;
                setupZip64   = Resources.Office15SP1_SetupRoot64;
                break;

            default:
                throw new Exception("Unsupported Microsoft Office Edition!");
            }

            if (InstallerInformation.InstallerArchitecture == Architecture.X86)
            {
                // Extract Admin Folder
                using (IArchive archive32 = ArchiveFactory.Open(new MemoryStream(x86)))
                {
                    foreach (IArchiveEntry entry in archive32.Entries)
                    {
                        if (!entry.IsDirectory)
                        {
                            entry.WriteToDirectory(unpackDirectoryAdmin, new ExtractionOptions()
                            {
                                ExtractFullPath = true, Overwrite = true
                            });
                        }
                    }
                }

                // Extract Product Folder
                if (productZip32 != null)
                {
                    using (IArchive archiveProduct = ArchiveFactory.Open(new MemoryStream(productZip32)))
                    {
                        foreach (IArchiveEntry entry in archiveProduct.Entries)
                        {
                            if (!entry.IsDirectory)
                            {
                                entry.WriteToDirectory(unpackDirectoryProduct, new ExtractionOptions()
                                {
                                    ExtractFullPath = true, Overwrite = true
                                });
                            }
                        }
                    }
                }

                // Extract Setup Folder
                if (setupZip32 != null)
                {
                    using (IArchive archiveSetup = ArchiveFactory.Open(new MemoryStream(setupZip32)))
                    {
                        foreach (IArchiveEntry entry in archiveSetup.Entries)
                        {
                            if (!entry.IsDirectory)
                            {
                                entry.WriteToDirectory(unpackDirectorySetup, new ExtractionOptions()
                                {
                                    ExtractFullPath = true, Overwrite = true
                                });
                            }
                        }
                    }
                }
            }
            else if (InstallerInformation.InstallerArchitecture == Architecture.X64)
            {
                // Extract Admin Folder
                using (IArchive archive64 = ArchiveFactory.Open(new MemoryStream(x64)))
                {
                    foreach (IArchiveEntry entry in archive64.Entries)
                    {
                        if (!entry.IsDirectory)
                        {
                            entry.WriteToDirectory(unpackDirectoryAdmin, new ExtractionOptions()
                            {
                                ExtractFullPath = true, Overwrite = true
                            });
                        }
                    }
                }

                // Extract Product Folder
                if (productZip64 != null)
                {
                    using (IArchive archiveProduct = ArchiveFactory.Open(new MemoryStream(productZip64)))
                    {
                        foreach (IArchiveEntry entry in archiveProduct.Entries)
                        {
                            if (!entry.IsDirectory)
                            {
                                entry.WriteToDirectory(unpackDirectoryProduct, new ExtractionOptions()
                                {
                                    ExtractFullPath = true, Overwrite = true
                                });
                            }
                        }
                    }
                }

                // Extract Setup Folder
                if (setupZip64 != null)
                {
                    using (IArchive archiveSetup = ArchiveFactory.Open(new MemoryStream(setupZip64)))
                    {
                        foreach (IArchiveEntry entry in archiveSetup.Entries)
                        {
                            if (!entry.IsDirectory)
                            {
                                entry.WriteToDirectory(unpackDirectorySetup, new ExtractionOptions()
                                {
                                    ExtractFullPath = true, Overwrite = true
                                });
                            }
                        }
                    }
                }
            }

            // Extract Admin Folder Components Shared Between x86 and x64
            using (IArchive archiveShared = ArchiveFactory.Open(new MemoryStream(shared)))
            {
                foreach (IArchiveEntry entry in archiveShared.Entries)
                {
                    if (!entry.IsDirectory)
                    {
                        entry.WriteToDirectory(unpackDirectoryAdmin, new ExtractionOptions()
                        {
                            ExtractFullPath = true, Overwrite = true
                        });
                    }
                }
            }
            #endregion
        }
Exemplo n.º 40
0
        private void convertToZip(string filename)
        {
            if (string.IsNullOrEmpty(SelectedFilePath))
            {
                return;
            }

            if (File.Exists(filename))
            {
                if (MessageBox.Show("Overwrite?", "Save", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    File.Delete(filename);
                }
                else
                {
                    return;
                }
            }

            Task <int> task1 = Task.Run(() => {
                IsVisibleProgress     = Visibility.Visible;
                IsEnableProgressClose = false;

                var opts             = new SharpCompress.Writers.WriterOptions(CompressionType.Deflate);
                opts.ArchiveEncoding = new SharpCompress.Common.ArchiveEncoding();
                //opts.ArchiveEncoding.Default = System.Text.Encoding.GetEncoding("shift_jis");
                opts.ArchiveEncoding.Default = System.Text.Encoding.UTF8;

                using (var zip = File.OpenWrite(filename))
                    using (var zipWriter = WriterFactory.Open(zip, ArchiveType.Zip, opts))
                    {
                        ProgressOutFileName = SelectedFilePath;

                        IArchive archive = ArchiveFactory.Open(SelectedFilePath);
                        var entries      = archive.Entries.Where(e =>
                                                                 e.IsDirectory == false && (
                                                                     Path.GetExtension(e.Key).Equals(".jpg") ||
                                                                     Path.GetExtension(e.Key).Equals(".jpeg") ||
                                                                     Path.GetExtension(e.Key).Equals(".png") ||
                                                                     Path.GetExtension(e.Key).Equals(".bmp")));

                        var list      = entries.ToList();
                        ProgressMax   = list.Count;
                        ProgressValue = 0;
                        foreach (var item in entries.ToList())
                        {
                            ProgressFileName = item.Key;
                            var outStream    = new MemoryStream();

#if IMAGE_RESIZER
                            var instructions    = new Instructions();
                            instructions.Format = "jpg";

                            if (IsResize)
                            {
                                instructions.Width  = ImageWidth;
                                instructions.Height = ImageHeight;
                                instructions.Mode   = FitMode.Max;
                            }

                            if (IsCompress)
                            {
                                if (IsGrayscale)
                                {
                                    instructions.Grayscale = GrayscaleMode.Flat; // TODO: check mode
                                }

                                instructions.JpegSubsampling = JpegSubsamplingMode.Y4Cb2Cr0;
                                instructions.JpegQuality     = JpegQuality;
                            }

                            ImageBuilder.Current.Build(new ImageJob(item.OpenEntryStream(), outStream, instructions, false, true));
#endif
#if IMAGE_SHARP
                            using (Image image = Image.Load(item.OpenEntryStream()))
                            {
                                if (IsResize)
                                {
                                    image.Mutate(x => x
                                                 .Resize(new ResizeOptions
                                    {
                                        Mode = ResizeMode.Min,
                                        Size = new Size(ImageWidth, ImageHeight),
                                    })
                                                 );
                                }

                                if (IsCompress)
                                {
                                    if (IsGrayscale)
                                    {
                                        image.Mutate(x => x
                                                     .Grayscale()
                                                     );
                                    }

                                    // Use ImageSharp
                                    if (false)
                                    {
                                        var enc       = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();
                                        enc.Quality   = JpegQuality;
                                        enc.Subsample = SixLabors.ImageSharp.Formats.Jpeg.JpegSubsample.Ratio444;
                                        if (ImageFormat == ImgFmt.IMG_444)
                                        {
                                            enc.Subsample = SixLabors.ImageSharp.Formats.Jpeg.JpegSubsample.Ratio444;
                                        }
                                        else if (ImageFormat == ImgFmt.IMG_420)
                                        {
                                            enc.Subsample = SixLabors.ImageSharp.Formats.Jpeg.JpegSubsample.Ratio420;
                                        }
                                        image.SaveAsJpeg(outStream, enc);
                                    }

                                    // Use MozJpeg
                                    if (true)
                                    {
                                        var bmpenc = new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder();
                                        image.Save(outStream, bmpenc);
                                        outStream.Seek(0, SeekOrigin.Begin);

                                        var tjc = new MozJpegSharp.TJCompressor();
                                        var b   = new System.Drawing.Bitmap(outStream);
                                        //var compressed = tjc.Compress(b, MozJpegSharp.TJSubsamplingOption.Chrominance420, 75, MozJpegSharp.TJFlags.None);
                                        var compressed = tjc.Compress(b, MozJpegSharp.TJSubsamplingOption.Chrominance420, 30, MozJpegSharp.TJFlags.None);
                                        outStream      = new MemoryStream(compressed);
                                    }
                                }
                                else
                                {
                                    image.SaveAsJpeg(outStream);
                                }
                            }
#endif

                            outStream.Seek(0, SeekOrigin.Begin);
                            zipWriter.Write(item.Key, outStream);

                            ProgressValue++;
                        }
                    }

                IsEnableProgressClose = true;
                return(1);
            });
        }
Exemplo n.º 41
0
 private void ProcessModdedRpfFile(RpfListBuilder.IDirectory rpf, IArchive rageArchiveWrapper7)
 {
     foreach (var c in rpf.Contents)
         ProcessContent(c, rageArchiveWrapper7.Root);
 }
Exemplo n.º 42
0
		private void CloseEditor()
		{
			mParent.Enabled = true;
			mParent.Activate();
			Hide();
			archiveViewer.Items.Clear();
			if (thumbViewer.Image != null && mThumbResampled)
			{
				Image img = thumbViewer.Image;
				thumbViewer.Image = null;
				img.Dispose();
			}
			if (mArchive != null)
			{
				mArchive.Dispose();
				mArchive = null;
			}
			if (mArchiveReader != null)
			{
				mArchiveReader.Cancel();
				mArchiveReader.Dispose();
			}
		}
Exemplo n.º 43
0
		/// <summary>
		/// Creates a repository for the given student, and pushes the non-test files
		/// from the source project to the new repository.
		/// </summary>
		private async Task<CreateAndPushResult> CreateAndPushAsync(
			Project project,
			ClassroomMembership student,
			string webhookUrl,
			bool overwriteIfSafe,
			ICollection<GitHubTeam> teams,
			ICollection<GitHubRepository> repositories,
			IArchive templateContents)
		{
			string orgName = project.Classroom.GitHubOrganization;
			string repoName = $"{project.Name}_{student.GitHubTeam}";

			try
			{
				var repository = repositories.SingleOrDefault(repo => repo.Name == repoName);
				var team = teams.First(teamCandidate => teamCandidate.Name == student.GitHubTeam);
				bool repositoryAlreadyExisted = (repository != null);

				if (repositoryAlreadyExisted)
				{
					if (!overwriteIfSafe)
						return CreateAndPushResult.Exists;

					var commits = await _repoClient.GetAllCommitsAsync(orgName, repoName);
					if (commits.Count > c_numInitialCommits)
						return CreateAndPushResult.Exists;
				}
				else
				{
					repository = await _repoClient.CreateRepositoryAsync
					(
						orgName,
						repoName,
						team,
						overwrite: false
					);

					var staffTeam = GetStaffTeam(project.Classroom, teams);
					if (staffTeam != null)
					{
						await _teamClient.AddRepositoryAsync(orgName, repoName, staffTeam);
					}
				}

				await _repoClient.OverwriteRepositoryAsync
				(
					repository,
					c_starterCommitMessage,
					templateContents,
					entry => project.GetFileType(entry) != FileType.Private,
					entry => project.GetFileType(entry) == FileType.Immutable
				);

				await _repoClient.EnsurePushWebhookAsync(repository, webhookUrl);

				return repositoryAlreadyExisted
					? CreateAndPushResult.Overwritten
					: CreateAndPushResult.Created;
			}
			catch (Exception ex)
			{
				_logger.LogError
				(
					(EventId)0,
					ex,
					"Failed to create repository {RepoName} in organization {Org}.", repoName, orgName
				);

				return CreateAndPushResult.Failed;
			}
		}
Exemplo n.º 44
0
 /// <summary>
 /// Create an instance of solution monitor.
 /// </summary>
 /// <param name="SrcMLServiceDirectory"></param>
 /// <param name="lastModifiedArchive"></param>
 /// <param name="CurrentSrcMLArchive"></param>
 /// <returns></returns>
 public static SolutionMonitor CreateMonitor(string SrcMLServiceDirectory, IArchive lastModifiedArchive, params IArchive[] CurrentSrcMLArchive) {
     var openSolution = GetOpenSolution();
     return CreateMonitor(openSolution, SrcMLServiceDirectory, lastModifiedArchive, CurrentSrcMLArchive);
 }
Exemplo n.º 45
0
        public IList<IExtendValue> GetExtendFieldValues(IArchive archive)
        {
            int extendId;
            int siteId = archive.Category.Site.Id;
            IDictionary<int, IExtendValue> extendValues =
                new Dictionary<int, IExtendValue>();
            foreach (IExtendField field in archive.Category.ExtendFields)
            {
                extendValues.Add(field.Id, this.CreateExtendValue(field, -1, null));
            }

            this.extendDAL.GetExtendValues(siteId,(int)ExtendRelationType.Archive, archive.Id, rd =>
            {
                while (rd.Read())
                {
                    extendId = int.Parse(rd["fieldId"].ToString());

                    if (extendValues.ContainsKey(extendId))
                    {
                        extendValues[extendId].Id = int.Parse(rd["id"].ToString());
                        extendValues[extendId].Value = rd["fieldValue"].ToString().Replace("\n", "<br />");
                    }

                }
            });

            return new List<IExtendValue>(extendValues.Values);
        }
Exemplo n.º 46
0
        /// <summary>
        /// Opens an archive.
        /// </summary>
        public void Load(string fileName)
        {
            // close first...
            Close();

            this.archive = RageArchiveWrapper7.Open(fileName);
            this.fileName = fileName;
        }
Exemplo n.º 47
0
        internal async Task Initialise()
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(this._path);
            if (file == null)
            {
                throw new FileNotFoundException("the file could not be found in the isolated storage");
            }

            this.FullPath = file.Path;
            this._bundle = ZipArchive.Open(await file.OpenStreamForReadAsync());
           
            var manifestEntry = this._bundle.Entries.Where(e => string.Compare(e.Key, "manifest.json", StringComparison.OrdinalIgnoreCase) == 0).FirstOrDefault();
            if (manifestEntry == null)
            {
                throw new ArgumentException("manifest.json not found in archive - not a Pebble this.Bundle.");
            }

            using (Stream jsonstream = manifestEntry.OpenEntryStream())
            {
                var serializer = new DataContractJsonSerializer(typeof(BundleManifest));
                this.Manifest = serializer.ReadObject(jsonstream) as BundleManifest;
            }

            if (this.Manifest.Type == "firmware")
            {
                this.BundleType = BundleType.Firmware;
                this.BinaryContent = await this.ReadFileToArray(this.Manifest.Firmware.Filename, this.Manifest.Firmware.Size);
            }
            else
            {
                this.BundleType = BundleType.Application;
                this.BinaryContent = await this.ReadFileToArray(this.Manifest.ApplicationManifest.Filename, this.Manifest.ApplicationManifest.Size);

                // Convert first part to app manifest
#if NETFX_CORE  && !WINDOWS_PHONE_APP
                byte[] buffer = new byte[Marshal.SizeOf<ApplicationMetadata>()];
#else
                byte[] buffer = new byte[Marshal.SizeOf(typeof(ApplicationMetadata))];
#endif
                Array.Copy(this.BinaryContent, 0, buffer, 0, buffer.Length);
                this.Application = buffer.AsStruct<ApplicationMetadata>();
            }

            this.HasResources = this.Manifest.Resources.Size != 0;
            if (this.HasResources)
            {
                this.Resources = await this.ReadFileToArray(this.Manifest.Resources.Filename, this.Manifest.Resources.Size);
            }
        }
Exemplo n.º 48
0
 /// <summary>
 /// Closes an archive.
 /// </summary>
 public void Close()
 {
     if (archive != null)
         archive.Dispose();
     archive = null;
     fileName = null;
 }
Exemplo n.º 49
0
        // Replacement for individual raf reading and individual filetype searching
        // Provide the directory of RADS\projects\lol_game_client\filearchives or the equivalent
        private bool ReadFiles(DirectoryInfo dir, Logger logger, FileType filetype)
        {
            try
            {
                IArchive archive = null;

                logger.Event("Opening the 'filearchives' directory: " + dir.FullName);

                switch (filetype)
                {
                case FileType.RAF:
                    archive = new RAFArchiveWrapper(new RAFMasterFileList(dir.FullName));
                    break;

                case FileType.ZIP:
                    archive = new ZIPArchiveWrapper(new ZipFile(dir.FullName + "/HeroPak_client.zip"));
                    break;

                default:
                    //TODO log error
                    return(false);
                }

                foreach (IFileEntry e in archive.SearchFileEntries(new string[] { ".dds", ".skn", ".skl", ".inibin", "animations.list", ".anm" }))
                {
                    // Split off the actual file name from the full path
                    String name = e.FileName.Substring(e.FileName.LastIndexOf('/') + 1).ToLower();

                    switch (e.SearchPhrase)
                    {
                    case ".dds":
                        // Try to parse out unwanted textures.
                        if (!e.FileName.ToLower().Contains("loadscreen") &&
                            !e.FileName.ToLower().Contains("circle") &&
                            !e.FileName.ToLower().Contains("square") &&
                            e.FileName.ToLower().Contains("data") &&
                            e.FileName.ToLower().Contains("characters"))
                        {
                            // Check that the file isn't already in the dictionary
                            if (!textures.ContainsKey(name))
                            {
                                textures.Add(name, e);
                            }
                            else
                            {
                                logger.Warning("Duplicate texture " + name + ": " + e.FileName);
                            }
                        }
                        break;

                    case ".skn":
                        if (!skns.ContainsKey(name))
                        {
                            skns.Add(name, e);
                        }
                        else
                        {
                            logger.Warning("Duplicate skn " + name + ": " + e.FileName);
                        }
                        break;

                    case ".skl":
                        if (!skls.ContainsKey(name))
                        {
                            skls.Add(name, e);
                        }
                        else
                        {
                            logger.Warning("Duplicate skn " + name + ": " + e.FileName);
                        }
                        break;

                    case ".inibin":
                        // Try to only read champion inibins
                        if (e.FileName.ToLower().Contains("data") &&
                            e.FileName.ToLower().Contains("characters"))
                        {
                            inibins.Add(e);
                        }
                        else
                        {
                            logger.Warning("Excluding inibin " + name + ": " + e.FileName);
                        }
                        break;

                    case "animations.list":
                        // Riot changed their directory structure for some skins.
                        // Originally, champion Animation.list files were stored in a directory structure like
                        // "*/ChampionName/Animation.list".  Now, some are stored like
                        // "*/ChampionName/Skins/Skin01/Animation.list".

                        //logger.Event("animationLists << " + e.FileName);

                        if (e.FileName.ToLower().Contains("skin") == false &&
                            e.FileName.ToLower().Contains("base") == false)
                        {
                            // Original Case.

                            // Remove the file name.
                            name = e.FileName.Remove(e.FileName.LastIndexOf('/'));

                            // Remove proceeding directories to get the parent directory
                            name = name.Substring(name.LastIndexOf('/') + 1).ToLower();
                        }
                        else
                        {
                            // Newer Case.
                            string   path      = e.FileName.ToString();
                            string[] splitPath = path.Split('/');

                            // Sanity
                            if (splitPath.Length > 3)
                            {
                                name = splitPath[splitPath.Length - 4].ToLower();
                            }
                        }

                        // Store.
                        if (!animationLists.ContainsKey(name))
                        {
                            //logger.Event("animationLists.Add(" + name + ", " + e.FileName + ");");
                            animationLists.Add(name, e);
                        }
                        else
                        {
                            logger.Warning("Duplicate animation list " + name + ": " + e.FileName);
                        }
                        break;

                    case ".anm":
                        // Remove the .anm extension.
                        name = name.Remove(name.Length - 4);

                        if (!animations.ContainsKey(name))
                        {
                            animations.Add(name, e);
                        }
                        else
                        {
                            logger.Warning("Duplicate anm " + name + ": " + e.FileName);
                        }
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                // Something went wrong. Most likely the RAF read failed due to a bad directory.
                logger.Error("Failed to open RAFs");
                logger.Error(e.Message);
                return(false);
            }

            return(true);
        }
Exemplo n.º 50
0
        /// <summary>
        /// 更新文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="type"></param>
        /// <param name="upgradePath"></param>
        /// <param name="resume">是否断点续传</param>
        /// <returns></returns>
        public static int UpgradeFile(string fileName, UpgradeFileType type, string upgradePath, bool resume)
        {
            //检查目录是否存在及权限
            DirectoryInfo dir = new DirectoryInfo(String.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, upgradePath));

            if (!dir.Exists)
            {
                Directory.CreateDirectory(dir.FullName).Create();
            }
            else
            {
                //设置权限
                if ((dir.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                {
                    dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
                }
            }

            //断点续传
            byte[] bytes = DownloadFile(fileName, null);
            if (bytes == null)
            {
                return(-1);
            }

            //压缩文件
            if (type == UpgradeFileType.Zip)
            {
                //IArchive archive = ArchiveFactory.Open(file.FullName);
                MemoryStream ms      = new MemoryStream(bytes);
                IArchive     archive = ArchiveFactory.Open(ms);

                foreach (IArchiveEntry entry in archive.Entries)
                {
                    if (!entry.IsDirectory)
                    {
                        entry.WriteToDirectory(dir.FullName, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                    }
                }
                archive.Dispose();
                ms.Dispose();
            }
            else
            {
                string dirName = dir.FullName;
                if (type == UpgradeFileType.Lib)
                {
                    // fileName = fileName + ".lib";
                    dirName = Cms.PyhicPath;
                }

                //检查文件是否存在和权限
                FileInfo file = new FileInfo(String.Format("{0}{1}", dirName, fileName));

                if (file.Exists)
                {
                    if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    {
                        file.Attributes = file.Attributes & ~FileAttributes.ReadOnly;
                    }
                }
                else
                {
                    file.Create().Dispose();
                }

                //输出到文件
                FileStream fs = file.OpenWrite();
                //  fs.Write(ms.GetBuffer(), 0, (int)ms.Length);
                fs.Write(bytes, 0, bytes.Length);
                fs.Flush();
                fs.Dispose();
            }

            return(1);
        }
Exemplo n.º 51
0
		private void ListArchiveContent(object sender, DoWorkEventArgs e)
		{
			//mFileNameList
			BackgroundWorker worker = sender as BackgroundWorker;
			try
			{
				//using (Stream stream = File.OpenRead(mItem.FilePath))
				//{
				//    mArchiveReader = ReaderFactory.Open(stream);
				//    ArchiveEncoding.Default = Encoding.GetEncoding("Shift-JIS");
				//    while (mArchiveReader.MoveToNextEntry())
				//    {
				//        if (mArchiveReader.Entry.IsDirectory) continue;
				//        archiveViewer.Items.Add(mArchiveReader.Entry.Key);
				//    }
				//    mArchiveReader.Dispose();
				//}
				mArchive = ArchiveFactory.Open(mItem.FilePath);
				if (mArchive.IsSolid)
				{
					throw new Exception("Error: Cannot create thumbnail for a SOLID archive.");
				}
				int numEntries = System.Linq.Enumerable.Count(mArchive.Entries);
				Queue<string> queue = new Queue<string>(numEntries);
				int counter = 0;
				foreach (IArchiveEntry entry in mArchive.Entries)
				{
					if (entry.IsDirectory) continue;
					queue.Enqueue(entry.Key);
					string msg = "Extracting " + counter + " of " + numEntries + " files...";
					worker.ReportProgress(++counter * 100 / numEntries, msg);
				}
				e.Result = queue.ToArray();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
				e.Result = null;
			}
		}
Exemplo n.º 52
0
        public GenericTAHStream(GenericTahInfo info, ArcsTahFilesEntry tsoInfo)
        {
            // zipファイルの中か?
            if (info.zipid != -1)
            {
                ArcsZipArcEntry zip     = TDCGExplorer.ArcsDB.GetZip(info.zipid);
                string          zippath = Path.Combine(TDCGExplorer.SystemDB.zips_path, zip.path);
                switch (Path.GetExtension(zip.path).ToLower())
                {
                case ".zip":
                    archive = new ZipArchive();
                    break;

                case ".lzh":
                    archive = new LzhArchive();
                    break;

                case ".rar":
                    archive = new RarArchive();
                    break;

                default:
                    archive = new DirectAccessArchive();
                    break;
                }
                TDCGExplorer.LastAccessFile = zippath;
                archive.Open(zippath);
                if (archive == null)
                {
                    throw new Exception(TextResource.ArchiveIsNull);
                }

                //
                foreach (IArchiveEntry entry in archive)
                {
                    // ディレクトリのみの場合はスキップする.
                    if (entry.IsDirectory == true)
                    {
                        continue;
                    }
                    // マッチするファイルを見つけた.
                    if (entry.FileName == info.path)
                    {
                        ms = new MemoryStream((int)entry.Size);

                        archive.Extract(entry, ms);
                        ms.Seek(0, SeekOrigin.Begin);
                        tah = new TAHFile(ms);
                        tah.LoadEntries();
                        if (tsoInfo == null)
                        {
                            return;
                        }
                        int tahentry = 0;
                        foreach (TAHEntry ent in tah.EntrySet.Entries)
                        {
                            // 該当ファイルを見つけた.
                            if (tahentry == tsoInfo.tahentry)
                            {
                                byte[] data = TAHUtil.ReadEntryData(tah.Reader, ent);
                                //
                                Cursor.Current = Cursors.WaitCursor;
                                ims            = new MemoryStream(data);
                                return;
                            }
                            tahentry++;
                        }
                    }
                }
            }
            else
            {
                string source = Path.Combine(TDCGExplorer.SystemDB.arcs_path, info.path);
                tah = new TAHFile(source);
                tah.LoadEntries();
                if (tsoInfo == null)
                {
                    return;
                }
                int tahentry = 0;
                foreach (TAHEntry ent in tah.EntrySet.Entries)
                {
                    // 該当ファイルを見つけた.
                    if (tahentry == tsoInfo.tahentry)
                    {
                        byte[] data = TAHUtil.ReadEntryData(tah.Reader, ent);
                        //
                        ims = new MemoryStream(data);
                        return;
                    }
                    tahentry++;
                }
            }
            throw new Exception("TAH内のファイルが見つかりません");
        }
Exemplo n.º 53
0
        /// <summary>
        /// Create an instance of solution monitor.
        /// </summary>
        /// <param name="openSolution"></param>
        /// <param name="SrcMLServiceDirectory"></param>
        /// <param name="lastModifiedArchive"></param>
        /// <param name="CurrentSrcMLArchive"></param>
        /// <returns></returns>
        private static SolutionMonitor CreateMonitor(Solution openSolution, string SrcMLServiceDirectory, IArchive lastModifiedArchive, params IArchive[] CurrentSrcMLArchive) {
            Contract.Requires(openSolution != null, "A solution must be open");

            var currentMonitor = new SolutionMonitor(SolutionWrapper.Create(openSolution), SrcMLServiceDirectory, lastModifiedArchive, CurrentSrcMLArchive);
            return currentMonitor;
        }
Exemplo n.º 54
0
 public ArchivedFile SelectFileFromArchive(IArchive archive)
 {
     return(UserSelectFileFromArchive(archive.RootEntries));
 }
Exemplo n.º 55
0
        /// <summary>
        /// Creates an archive.
        /// </summary>
        public void New(string fileName)
        {
            // close first...
            Close();

            this.archive = RageArchiveWrapper7.Create(fileName);
            this.fileName = fileName;
        }
Exemplo n.º 56
0
        private void SwapSortNumber(IArchive archive)
        {
            if (archive == null) return;
            int sortN = archive.SortNumber;
            archive.SortNumber = this.SortNumber;
            this.SortNumber = sortN;

            archive.SaveSortNumber();
            this.Save();
        }
Exemplo n.º 57
0
 public TexFile(IArchive fileContainer) : base(fileContainer)
 {
 }
Exemplo n.º 58
0
        /// <summary>
        /// Writes the contents of a submission to an archive.
        /// </summary>
        private async Task WriteSubmissionToArchiveAsync(
            ZipArchive archive,
            Project project,
            ClassroomMembership student,
            IArchive templateContents,
            IArchive submissionContents)
        {
            var studentFolder = $"EclipseProjects\\{student.GitHubTeam}";

            // The project will contain all non-immutable submission files,
            // plus all immutable and private files from the template project.

            var projectContents = submissionContents.Files
                                  .Where
                                  (
                entry => project.GetFileType(entry) == FileType.Public
                                  )
                                  .Concat
                                  (
                templateContents.Files.Where
                (
                    entry => project.GetFileType(entry) != FileType.Public
                )
                                  )
                                  .ToList();

            foreach (var entry in projectContents)
            {
                if (ExcludeEntry(project, entry))
                {
                    continue;
                }

                var contents = _transformer.GetFileContents(project, student, entry);

                var archiveFilePath   = entry.FullPath;
                var archiveFileFolder = archiveFilePath.Contains("/")
                                        ? archiveFilePath.Substring(0, archiveFilePath.LastIndexOf("/"))
                                        : archiveFilePath;

                var localFileFolder = $"{studentFolder}\\{archiveFileFolder}";
                var fileName        = archiveFilePath.Substring(archiveFilePath.LastIndexOf("/") + 1);
                var localFilePath   = $"{localFileFolder}\\{fileName}";

                // Add the file to the student project folder.
                var projectFolderEntry = archive.CreateEntry(localFilePath);
                using (Stream stream = projectFolderEntry.Open())
                {
                    await stream.WriteAsync(contents, offset : 0, count : contents.Length);
                }

                // Add the file to the folder containing all files, if applicable.
                if (fileName.EndsWith(".java") && project.GetFileType(entry) == FileType.Public)
                {
                    var allFilesEntry = archive.CreateEntry($"AllFiles\\{student.GitHubTeam}-{fileName}");
                    using (Stream stream = allFilesEntry.Open())
                    {
                        await stream.WriteAsync(contents, offset : 0, count : contents.Length);
                    }
                }
            }
        }
		/// <summary>
		/// Returns a new student submission.
		/// </summary>
		private StudentSubmission GetSubmission(
			ClassroomMembership student,
			IArchive contents)
		{
			return new StudentSubmission(student, contents);
		}
Exemplo n.º 60
0
 public static void Extract(string filePath, string directoryPath)
 {
     using (IArchive archive = Open(filePath, FileAccess.Read))
         archive.ExtractAllEntries(directoryPath);
 }