/// <summary>Initializes a new instance of the <see cref="JackrabbitLibrary" /> class.</summary>
 /// <param name="fileType">The type of file</param>
 /// <param name="libraryName">The name of the library.</param>
 /// <param name="version">The version.</param>
 /// <param name="specificity">The version specificity.</param>
 public JackrabbitLibrary(FileType fileType, string libraryName, Version version, SpecificVersion specificity)
 {
     this.FileType = fileType;
     this.LibraryName = libraryName;
     this.Version = version;
     this.Specificity = specificity;
 }
        private void FsCtl_Get_Compression_IsCompressionSupported(FileType fileType)
        {
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Test case steps:");
            MessageStatus status;

            //Step 1: Create file
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "1. Create " + fileType.ToString());
            status = this.fsaAdapter.CreateFile(fileType);

            //Step 2: FSCTL request with FSCTL_GET_COMPRESSION
            FSCTL_GET_COMPRESSION_Reply compressionReply = new FSCTL_GET_COMPRESSION_Reply();
            uint outputBufferSize = (uint)TypeMarshal.ToBytes<FSCTL_GET_COMPRESSION_Reply>(compressionReply).Length;

            long bytesReturned;
            byte[] outputBuffer = new byte[0];

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "2. FSCTL request with FSCTL_GET_COMPRESSION");
            status = this.fsaAdapter.FsCtlGetCompression(outputBufferSize, out bytesReturned, out outputBuffer);

            //Step 3: Verify test result
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "3. Verify returned NTSTATUS code.");
            // 2.1.5.9.7   FSCTL_GET_COMPRESSION
            // <64> Section 2.1.5.9.7: This is only implemented by the NTFS and ReFS file systems.
            if (this.fsaAdapter.FileSystem == FileSystem.NTFS || this.fsaAdapter.FileSystem == FileSystem.REFS)
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.SUCCESS, status, "FSCTL_GET_COMPRESSION is supported, status set to STATUS_SUCCESS.");
            }
            else
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.INVALID_DEVICE_REQUEST, status,
                        "If the object store does not implement this functionality, the operation MUST be failed with STATUS_INVALID_DEVICE_REQUEST.");
            }
        }
 public bool IsFileType(FileType type, [NotNull] string extensionName)
 {
     if (extensionName == null) throw new ArgumentNullException(nameof(extensionName));
     Dictionary<string, ExtensionName> map;
     if (!this.mapedType.TryGetValue((int)type, out map)) return false;
     return map.ContainsKey(extensionName.TrimStart('.').ToLower());
 }
        private void AlternateDataStream_FsCtl_Set_ZeroData(FileType fileType)
        {
            //Prerequisites: Create streams on a newly created file

            //Step 1: FSCTL request with FSCTL_SET_ZERO_DATA
            FSCTL_SET_ZERO_DATA_Request setZeroDataRequest = new FSCTL_SET_ZERO_DATA_Request();
            setZeroDataRequest.FileOffset = 0;
            setZeroDataRequest.BeyondFinalZero = 0;

            uint inputBufferSize = (uint)TypeMarshal.ToBytes<FSCTL_SET_ZERO_DATA_Request>(setZeroDataRequest).Length;

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. FSCTL request with FSCTL_SET_ZERO_DATA", ++testStep);
            status = this.fsaAdapter.FsCtlSetZeroData(setZeroDataRequest, inputBufferSize);

            //Step 2: Verify test result
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. Verify returned NTSTATUS code.", ++testStep);
            if (this.fsaAdapter.IsSetZeroDataSupported == false)
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.INVALID_DEVICE_REQUEST, status,
                    "If the object store does not implement this functionality, the operation MUST be failed with STATUS_INVALID_DEVICE_REQUEST.");
            }
            else
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.SUCCESS, status,
                        "FSCTL_SET_ZERO_DATA is supported, status set to STATUS_SUCCESS.");
            }
        }
Esempio n. 5
0
 static private FileType MakeFile(JadeData.Project.File file)
 {
     FileType result = new FileType();
     result.Name = file.Name;
     result.Path = file.Path;
     return result;
 }
Esempio n. 6
0
        public string UserComment; // xml format

        #endregion Fields

        #region Constructors

        public G2File(String name, String hash, byte[] hashByte, TypeHash typeHash
            , long size, FileType fileType, String codecInfo
            , FileLocationFound filelocation, int lenghtMedia
            , String protocolName, String linkFile)
            : base(name,hash,hashByte,typeHash,size,fileType,codecInfo,filelocation,lenghtMedia,protocolName,linkFile)
        {
        }
        private void AlternateDataStream_FsCtl_Get_IntegrityInformation(FileType fileType)
        {
            //Prerequisites: Create streams on a newly created file

            //Step 1: FSCTL Request with FSCTL_GET_INTEGRITY_INFORMATION
            FSCTL_GET_INTEGRITY_INFORMATION_BUFFER integrityInfo = new FSCTL_GET_INTEGRITY_INFORMATION_BUFFER();
            uint outputBufferSize = (uint)TypeMarshal.ToBytes<FSCTL_GET_INTEGRITY_INFORMATION_BUFFER>(integrityInfo).Length;

            long bytesReturned;
            byte[] outputBuffer = new byte[0];
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. FSCTL Request with FSCTL_GET_INTEGRITY_INFORMATION.", ++testStep);
            status = this.fsaAdapter.FsCtlGetIntegrityInfo(outputBufferSize, out bytesReturned, out outputBuffer);

            //Step 2: Verify test result
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. Verify returned NTStatus code.", ++testStep);
            if (this.fsaAdapter.Transport == Transport.SMB)
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.NOT_SUPPORTED, status,
                    "This operation is not supported for SMB transport.");
            }
            else
            {
                if (this.fsaAdapter.IsIntegritySupported == false)
                {
                    this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.INVALID_DEVICE_REQUEST, status, "If the object store does not implement this functionality, the operation MUST be failed with STATUS_INVALID_DEVICE_REQUEST.");
                }
                else
                {
                    this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.SUCCESS, status, "Integrity is supported, status set to STATUS_SUCCESS.");
                }
            }
        }
Esempio n. 8
0
        public static string ContainingFolder(int sym, FileType type)
        {
            if (sym < 0)
                throw new ArgumentOutOfRangeException("sym");

            return ContainingFolder(sym.ToString(), type);
        }
    /// <summary>
    /// Gets search results for full text map search
    /// </summary>
    /// <param name="name">Name to search for</param>
    /// <returns>Search results</returns>
    public string GetResults(string name, FileType type)
    {
      return "Use CaDownloader to get maps and mods automatically: http://caspring.org/wiki/CaUpdater";
      if (cachedResults.ContainsKey(name)) return cachedResults[name];

      WebClient wc = new WebClient();
      string result = "";

      if (String.IsNullOrEmpty(name)) return "you must type name of map, e.g. !maplink altored";

      try {
        result = wc.DownloadString("http://spring.unknown-files.net/page/search/1/" + (int)type + "/" + name);
      } catch {
        return "link search failed, unknown files down :(";
      }
      if (result == "" || !result.Contains("http://spring.unknown-files.net/file/")) return "link search failed, contact Licho";

      int start = result.IndexOf("<b>Search Results</b>");
      int end = result.IndexOf("<b>Quick Search</b>");
      if (start == -1 || end == -1) return "no link found";
      result = result.Substring(start, end - start); // pickup just result lines + something

      MatchCollection c = Regex.Matches(result, "<a href='(http://spring.unknown-files.net/file/[0-9]*)[^>]*>([^<]+)");
      string response = "";
      foreach (Match m in c) response += m.Groups[2].Value + " ---> " + m.Groups[1].Value + "\n";
      if (response == "") response = "no such map found";
      cachedResults[name] = response;
      return response;
    }
Esempio n. 10
0
        public IEnumerable<IMediaFile> GetMediaForProjectByType(int projectId, FileType type)
        {
            var wikiFiles = WikiFile.CurrentFiles(projectId);

            var mediaFiles = new List<MediaFile>();

            foreach (var wikiFile in wikiFiles)
            {
                var mediaFile = new MediaFile
                {
                    Current = wikiFile.Current,
                    Archived = wikiFile.Archived,
                    CreateDate = wikiFile.CreateDate,
                    Name = wikiFile.Name,
                    Id = wikiFile.Id,
                    CreatedBy = wikiFile.CreatedBy,
                    DotNetVersion = wikiFile.DotNetVersion,
                    Downloads = wikiFile.Downloads,
                    FileType = (FileType)Enum.Parse(typeof(FileType), wikiFile.FileType),
                    FileVersion = wikiFile.NodeVersion,
                    Path = wikiFile.Path,
                    RemovedBy = wikiFile.RemovedBy,
                    SupportsMediumTrust = false,
                    UmbVersion = wikiFile.Versions,
                    Verified = wikiFile.Verified
                };

                if (mediaFiles.Contains(mediaFile) == false)
                    mediaFiles.Add(mediaFile);
            }

            return mediaFiles;
        }
Esempio n. 11
0
        internal static char GetDelimiter(FileType fileType)
        {
            char delimiter;
            switch (fileType)
            {
                case FileType.CSV:
                {
                        delimiter = ',';
                        break;
                }

                case FileType.TXT:
                {
                        delimiter = '\t';
                        break;
                }
                default:
                {
                    Debug.Assert(false, "Un supported FileType");
                    delimiter = ',';
                    break;
                }
            }

            return delimiter;
        }
Esempio n. 12
0
        private void configure(FileType type, P3DOperation operation, String addonPath)
        {
            // Prepare the process to run
            ProcessStartInfo start = new ProcessStartInfo();

            // Enter in the command line arguments, everything you would enter after the executable name itself
            start.Arguments = "-Configure: File=" + type + ", Operation=" + operation + ", Path=" + addonPath;

            // Enter the executable to run, including the complete path
            start.FileName = @"C:\Prepar3D v3\Prepar3D.exe";

            // Do you want to show a console window?
            start.WindowStyle = ProcessWindowStyle.Hidden;
            start.CreateNoWindow = true;
            int exitCode;

            logger.Info("Calling Prepar3D.exe with arguments {0}", start.Arguments);

            // Run the external process & wait for it to finish
            using (Process proc = Process.Start(start))
            {
                proc.WaitForExit();

                // Retrieve the app's exit code
                exitCode = proc.ExitCode;
            }
        }
        private void FsCtl_Set_Sparse_IsSparseFileSupported(FileType fileType)
        {
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Test case steps:");
            MessageStatus status;

            //Step 1: Create file
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "1. Create " + fileType.ToString());
            status = this.fsaAdapter.CreateFile(fileType);

            //Step 2: Write data to file
            if (fileType == FileType.DataFile)
            {
                long bytesToWrite = 1024;
                long bytesWritten = 0;
                BaseTestSite.Log.Add(LogEntryKind.TestStep, "2. Write the file with " + bytesToWrite + " bytes.");
                status = this.fsaAdapter.WriteFile(0, bytesToWrite, out bytesWritten);
            }
            else
            {
                BaseTestSite.Log.Add(LogEntryKind.TestStep, "2. Do not write data to directory file.");
            }

            //Step 3: FSCTL request with FSCTL_SET_SPARSE
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "3. FSCTL request with FSCTL_SET_SPARSE");
            status = this.fsaAdapter.FsCtlSetSparse(true);

            //Step 4: Verify test result
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "4. Verify returned NTSTATUS code.");
            if (this.fsaAdapter.FileSystem == FileSystem.FAT32)
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.INVALID_DEVICE_REQUEST, status,
                "If the object store does not implement this functionality, the operation MUST be failed with STATUS_INVALID_DEVIeCE_REQUEST.");
                return;
            }

            if (fileType == FileType.DirectoryFile)
            {
                if (this.fsaAdapter.FileSystem == FileSystem.CSVFS)
                {
                    this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.STATUS_NOT_IMPLEMENTED, status,
                        "If the Open is a directory on a Cluster Shared Volume File System (CSVFS), the operation MUST be failed with STATUS_NOT_IMPLEMENTED.");
                }
                else
                {
                    this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.INVALID_PARAMETER, status,
                        "If the file is not a Data file, the operation MUST be failed with STATUS_INVALID_PARAMETER.");
                }
                return;
            }

            if (this.fsaAdapter.IsSparseFileSupported == false)
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.INVALID_DEVICE_REQUEST, status,
                    "If the object store does not implement this functionality, the operation MUST be failed with STATUS_INVALID_DEVICE_REQUEST.");
            }
            else
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.SUCCESS, status, "FSCTL_SET_SPARSE is supported, status set to STATUS_SUCCESS.");
            }
        }
Esempio n. 14
0
        private static FileDialogResult ShowFileDialog(object owner, FileDialog dialog, IEnumerable<FileType> fileTypes, 
            FileType defaultFileType, string defaultFileName)
        {
            int filterIndex = fileTypes.ToList().IndexOf(defaultFileType);
            if (filterIndex >= 0) { dialog.FilterIndex = filterIndex + 1; }
            if (!string.IsNullOrEmpty(defaultFileName))
            {
                dialog.FileName = Path.GetFileName(defaultFileName);
                string directory = Path.GetDirectoryName(defaultFileName);
                if (!string.IsNullOrEmpty(directory))
                {
                    dialog.InitialDirectory = directory;
                }
            }

            dialog.Filter = CreateFilter(fileTypes);
            if (dialog.ShowDialog(owner as Window) == true)
            {
                filterIndex = dialog.FilterIndex - 1;
                if (filterIndex >= 0 && filterIndex < fileTypes.Count())
                {
                    defaultFileType = fileTypes.ElementAt(filterIndex);
                }
                else
                {
                    defaultFileType = null;
                }
                return new FileDialogResult(dialog.FileName, defaultFileType);
            }
            else
            {
                return new FileDialogResult();
            }
        }
Esempio n. 15
0
		public Document(string filePath, bool needSaveAs)
		{
			this.needSaveAs = needSaveAs;
		
			if (!File.Exists(filePath))
				throw new FileNotFoundException("\"{0}\" does not exist.".F(filePath), filePath);

			try
			{
				foreach (string line in GetFileContent(filePath))
					lines.Add(new Line(line, LineModification.Clean, this));
			}
			catch
			{
				throw new FileNotFoundException("\"{0}\" could not be opened.".F(filePath), filePath);
			}

			point = new Caret(this);
			mark = new Caret(this);

			this.filePath = filePath;
			this.fileType = Config.ChooseFileType(filePath);

			if (lines.Count == 0)
				lines.Add(new Line("", LineModification.Clean, this));

			lastModified = File.GetLastWriteTime(filePath);
		}
Esempio n. 16
0
 private bool BothHaveTextAndData(FileType addedTypes)
 {
     return
         (FileType.HasFlag(FileType.Data) && addedTypes.HasFlag(FileType.Text))
             ||
             (FileType.HasFlag(FileType.Text) && addedTypes.HasFlag(FileType.Data));
 }
Esempio n. 17
0
 private bool BothHaveRarAndGZip(FileType addedTypes)
 {
     return
         (FileType.HasFlag(FileType.Rar) && addedTypes.HasFlag(FileType.GZip))
             ||
             (FileType.HasFlag(FileType.GZip) && addedTypes.HasFlag(FileType.Rar));
 }
Esempio n. 18
0
 public void Remove(FileType fileTypes)
 {
     if (FileType.HasFlag(fileTypes))
     {
         FileType &= ~fileTypes;
     }
 }
        private void AlternateDataStream_Query_FileNetworkOpenInformation(FileType fileType)
        {
            //Prerequisites: Create streams on a newly created file

            //Step 1: Query FILE_NETWORKOPEN_INFORMATION
            long byteCount;
            byte[] outputBuffer;
            FileNetworkOpenInformation fileNetworkOpenInfo = new FileNetworkOpenInformation();
            uint outputBufferSize = (uint)TypeMarshal.ToBytes<FileNetworkOpenInformation>(fileNetworkOpenInfo).Length;

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. QueryFileInformation with FileInfoClass.FILE_NETWORKOPEN_INFORMATION", ++testStep);
            status = this.fsaAdapter.QueryFileInformation(FileInfoClass.FILE_NETWORKOPEN_INFORMATION, outputBufferSize, out byteCount, out outputBuffer);

            // Step 2: Verify FILE_NETWORKOPEN_INFORMATION
            fileNetworkOpenInfo = TypeMarshal.ToStruct<FileNetworkOpenInformation>(outputBuffer);
            bool isIntegrityStreamSet = (fileNetworkOpenInfo.FileAttributes & (uint)FileAttribute.INTEGRITY_STREAM) == (uint)FileAttribute.INTEGRITY_STREAM;

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. Verify outputBuffer.FileAttributes.FILE_ATTRIBUTE_INTEGRITY_STREAM", ++testStep);
            if (this.fsaAdapter.IsIntegritySupported == true)
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, true, isIntegrityStreamSet,
                    "If integrity is supported, the object store MUST set FILE_ATTRIBUTE_INTEGRITY_STREAM in OutputBuffer.FileAttributes.");
            }
            else
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, false, isIntegrityStreamSet, "Integrity is not supported, FILE_ATTRIBUTE_INTEGRITY_STREAM MUST NOT set.");
            }
        }
Esempio n. 20
0
 static private FileType MakeFile(JadeCore.Project.FileItem file, string projectDir)
 {
     FileType result = new FileType();
     //Convert to relative path for storage in workspace
     result.Path = JadeUtils.IO.PathUtils.CalculateRelativePath(projectDir + @"\", file.Path.Str);
     return result;
 }
        private void FsInfo_Query_FileFsSizeInformation_SectorsPerAllocationUnit(FileType fileType)
        {
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Test case steps:");
            MessageStatus status;

            //Step 1: Create file
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "1. Create " + fileType.ToString());
            status = this.fsaAdapter.CreateFile(fileType);

            //Step 2: Query FileFsSizeInformation
            long byteCount;
            byte[] outputBuffer = new byte[0];
            FileFsSizeInformation fsSizeInfo = new FileFsSizeInformation();

            uint outputBufferSize = (uint)TypeMarshal.ToBytes<FileFsSizeInformation>(fsSizeInfo).Length;

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "2. Query FileFsSizeInformation");
            status = this.fsaAdapter.QueryFileSystemInformation(FileSystemInfoClass.File_FsSizeInformation, outputBufferSize, out byteCount, out outputBuffer);

            //Step 3: Verify test result
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "3. Verify OutputBuffer.SectorsPerAllocationUnit");
            fsSizeInfo = TypeMarshal.ToStruct<FileFsSizeInformation>(outputBuffer);
            uint expectedSectorsPerAllocationUnit = this.fsaAdapter.ClusterSizeInKB * 1024 / fsSizeInfo.BytesPerSector;
            uint actualSectorsPerAllocationUnit = fsSizeInfo.SectorsPerAllocationUnit;
            BaseTestSite.Log.Add(LogEntryKind.Debug, "ClusterSize is " + this.fsaAdapter.ClusterSizeInKB + " KB.");
            BaseTestSite.Log.Add(LogEntryKind.Debug, "BytesPerSector is " + fsSizeInfo.BytesPerSector + " bytes.");
            this.fsaAdapter.AssertAreEqual(this.Manager, expectedSectorsPerAllocationUnit, actualSectorsPerAllocationUnit, "OutputBuffer.SectorsPerAllocationUnit set to Open.File.Volume.ClusterSize / Open.File.Volume.LogicalBytesPerSector.");
        }
 public MessageEventArgs_402(int messageId, string messageName, string path,
                             FileType fileType, int size, DateTime created, DateTime modified, string checksum, string comment)
     : base(messageId, messageName, path, fileType, size, created, modified)
 {
     this.checksum = checksum;
     this.comment = comment;
 }
Esempio n. 23
0
        /// <summary>
        /// Returns an extension based on the given file type.
        /// </summary>
        /// <param name="fileType"></param>
        /// <returns></returns>
        public static string FileTypeToExtension(FileType fileType)
        {
            string extension = null;

            switch (fileType)
            {
                case FileType.CSS:
                    extension = ".css";
                    break;

                case FileType.JavaScript:
                    extension = ".js";
                    break;

                case FileType.Gif:
                    extension = ".gif";
                    break;

                case FileType.Jpeg:
                    extension = ".jpg";
                    break;

                case FileType.Png:
                    extension = ".png";
                    break;

                default:
                    throw new Exception("FileTypeToExtension - unknown file type: " + fileType.ToString());
            }

            return extension;
        }
        private void AlternateDataStream_FsCtl_Query_AllocatedRanges(FileType fileType)
        {
            //Prerequisites: Create streams on a newly created file

            //Step 1: FSCTL request with FSCTL_QUERY_ALLOCATED_RANGES
            long byteCount;
            byte[] outputBuffer;
            FSCTL_QUERY_ALLOCATED_RANGES_Request queryAllocatedRangesRequest = new FSCTL_QUERY_ALLOCATED_RANGES_Request();
            queryAllocatedRangesRequest.FileOffset = 0;
            queryAllocatedRangesRequest.Length = dataStreamList[":" + dataStreamName1 + ":$DATA"];
            uint outputBufferSize = (uint)TypeMarshal.ToBytes<FSCTL_QUERY_ALLOCATED_RANGES_Request>(queryAllocatedRangesRequest).Length;

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. FSCTL request with FSCTL_QUERY_ALLOCATED_RANGES", ++testStep);
            status = this.fsaAdapter.FsCtlQueryAllocatedRanges(queryAllocatedRangesRequest, outputBufferSize, out byteCount, out outputBuffer);

            //Step 2: Verify test result
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. Verify returned NTStatus code.", ++testStep);
            if (this.fsaAdapter.IsQueryAllocatedRangesSupported == false)
            {
                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.INVALID_DEVICE_REQUEST, status,
                    "If the object store does not implement this functionality, the operation MUST be failed with STATUS_INVALID_DEVICE_REQUEST.");
            }
            else
            {
                FSCTL_QUERY_ALLOCATED_RANGES_Reply queryAllocatedRangesReply = TypeMarshal.ToStruct<FSCTL_QUERY_ALLOCATED_RANGES_Reply>(outputBuffer);

                this.fsaAdapter.AssertAreEqual(this.Manager, dataStreamList[":" + dataStreamName1 + ":$DATA"], queryAllocatedRangesReply.Length,
                    "AllocatedRanges.Length is expected to same as the length of written data.");

                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.SUCCESS, status,
                    "FSCTL_QUERY_ALLOCATED_RANGES is supported, status set to STATUS_SUCCESS.");
            }
        }
        private void AlternateDataStream_Set_FileShortNameInformation(FileType fileType)
        {
            //Prerequisites: Create streams on a newly created file

            //Step 1: Set FILE_SHORTNAME_INFORMATION
            FileShortNameInformation shortNameInfo = new FileShortNameInformation();

            string shortName = this.fsaAdapter.ComposeRandomFileName(8);
            shortNameInfo.FileName = Encoding.Unicode.GetBytes(shortName);
            shortNameInfo.FileNameLength = (uint)shortNameInfo.FileName.Length;

            byte[] inputBuffer = TypeMarshal.ToBytes<FileShortNameInformation>(shortNameInfo);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. SetFileInformation with FileInfoClass.FILE_SHORTNAME_INFORMATION.", ++testStep);
            status = this.fsaAdapter.SetFileInformation(FileInfoClass.FILE_SHORTNAME_INFORMATION, inputBuffer);
            if (this.fsaAdapter.IsShortNameSupported == false)
            {
                BaseTestSite.Log.Add(LogEntryKind.Debug, "FileShortNameInformation is not supported.");
                this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.INVALID_PARAMETER, status,
                    "If a file system does not support a specific File Information Class, STATUS_INVALID_PARAMETER MUST be returned.");
            }
            else
            {
                if (status == MessageStatus.SHORT_NAMES_NOT_ENABLED_ON_VOLUME)
                {
                    BaseTestSite.Log.Add(LogEntryKind.Debug, "If Open.File.Volume.GenerateShortNames is FALSE, the operation MUST be failed with STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME.");
                    BaseTestSite.Log.Add(LogEntryKind.Debug, "To enable short name in specific volume, such as volume with driver letter N:, use command: fsutil 8dot3name set N: 0.");
                }
                else
                {
                    this.fsaAdapter.AssertAreEqual(this.Manager, MessageStatus.INVALID_PARAMETER, status,
                        "If Open.Stream.StreamType is DataStream and Open.Stream.Name is not empty. The operation MUST be failed with STATUS_INVALID_PARAMETER.");
                }
            }
        }
Esempio n. 26
0
 private static bool IsHeaderLinkOrScriptControlAdded(Page page, string ResolvedUrl, FileType fType)
 {
     switch (fType)
     {
         case FileType.Css:
             foreach (Control c in page.Header.Controls)
             {
                 var linkControl = c as HtmlLink;
                 if (linkControl == null) continue;
                 if (linkControl.Attributes["href"] == ResolvedUrl)
                     return true;
             }
             break;
         case FileType.Javascript:
             foreach (Control c in page.Header.Controls)
             {
                 var genericControl = c as HtmlGenericControl;
                 if (genericControl == null) continue;
                 if (genericControl.Attributes["src"] == ResolvedUrl)
                     return true;
             }
             break;
     }
     return false;
 }
        /// <summary>
        /// Create one alternate data stream on the newly created file
        /// </summary>
        /// <param name="fileType">The newly created file type: DataFile, DirectoryFile</param>
        private void AlternateDataStream_CreateStream(FileType fileType)
        {
            dataStreamList = new Dictionary<string, long>();
            long bytesToWrite = 0;
            long bytesWritten = 0;

            //Step 1: Create a new File, it could be a DataFile or a DirectoryFile
            fileName = this.fsaAdapter.ComposeRandomFileName(8);
            createFileType = (fileType == FileType.DataFile ? CreateOptions.NON_DIRECTORY_FILE : CreateOptions.DIRECTORY_FILE);
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. Create a file with type: " + fileType.ToString() + " and name: " + fileName, ++testStep);
            status = this.fsaAdapter.CreateFile(
                        fileName,
                        FileAttribute.NORMAL,
                        createFileType,
                        FileAccess.GENERIC_ALL,
                        ShareAccess.FILE_SHARE_READ | ShareAccess.FILE_SHARE_WRITE | ShareAccess.FILE_SHARE_DELETE,
                        CreateDisposition.OPEN_IF);
            this.fsaAdapter.AssertIfNotSuccess(status, "Create file operation failed");

            //Step 2: Write some bytes into the Unnamed Data Stream in the newly created file
            if (fileType == FileType.DataFile)
            {
                //Write some bytes into the DataFile.
                bytesToWrite = 1024;
                bytesWritten = 0;
                dataStreamList.Add("::$DATA", bytesToWrite);

                BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. Write the file with " + bytesToWrite + " bytes data.", ++testStep);
                status = this.fsaAdapter.WriteFile(0, bytesToWrite, out bytesWritten);
                this.fsaAdapter.AssertIfNotSuccess(status, "Write data to file operation failed.");
            }
            else
            {
                //Do not write data into DirectoryFile.
                bytesToWrite = 0;
                BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. Do not write data into DirectoryFile.", ++testStep);
            }

            //Step 3: Create an Alternate Data Stream <Stream1> in the newly created file
            dataStreamName1 = this.fsaAdapter.ComposeRandomFileName(8);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. Create an Alternate Data Stream with name: " + dataStreamName1 + " on this file.", ++testStep);
            status = this.fsaAdapter.CreateFile(
                        fileName + ":" + dataStreamName1 + ":$DATA",
                        FileAttribute.NORMAL | FileAttribute.INTEGRITY_STREAM, // Set Integrity field
                        CreateOptions.NON_DIRECTORY_FILE,
                        FileAccess.GENERIC_ALL,
                        ShareAccess.FILE_SHARE_READ | ShareAccess.FILE_SHARE_WRITE | ShareAccess.FILE_SHARE_DELETE,
                        CreateDisposition.OPEN_IF);
            this.fsaAdapter.AssertIfNotSuccess(status, "Create Alternate Data Stream operation failed");

            //Step 4: Write some bytes into the Alternate Data Stream <Stream1> in the file
            bytesToWrite = 2048;
            bytesWritten = 0;
            dataStreamList.Add(":" + dataStreamName1 + ":$DATA", bytesToWrite);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "{0}. Write the stream with " + bytesToWrite + " bytes data.", ++testStep);
            status = this.fsaAdapter.WriteFile(0, bytesToWrite, out bytesWritten);
            this.fsaAdapter.AssertIfNotSuccess(status, "Write data to stream operation failed.");
        }
Esempio n. 28
0
        /// <summary>
        /// Determines whether [is valid file type] [the specified file type].
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="fileType">Type of the file.</param>
        /// <returns></returns>
        /// <createdOn>1/26/2016 12:27 PM</createdOn>
        public static bool IsValidFileType(this FileUpload control, FileType fileType = FileType.Image)
        {
            if (!control.HasFile || !control.HasFiles)
                throw new Exception("No file exsit in the file upload");

            var isAllowedExtension = false;

            if (control.AllowMultiple)
            {
                foreach (var file in control.PostedFiles)
                {
                    isAllowedExtension = FileTypeSetting.IsAllowedExtension(file.FileName.GetSimpleFileExtension(), fileType);

                    if (!isAllowedExtension)
                        return false;
                }
            }
            else
            {
                isAllowedExtension =
                    FileTypeSetting.IsAllowedExtension(control.PostedFile.FileName.GetSimpleFileExtension(), fileType);
            }

            return isAllowedExtension;
        }
        public void FindLinks(string[] words, FileType type, TasClient tas, TasSayEventArgs e)
        {
            if (words.Length == 0)
            {
                Battle b = tas.MyBattle;
                if (b == null) return;
                ah.Respond(e, string.Format("Getting Zero-K mirrors for currently hosted {0}", type));
                if (type == FileType.Map) GetLinksAsync(b.MapName, e);
                else GetLinksAsync(b.ModName, e);
            }
            else
            {
                int[] resultIndexes;
                string[] resultVals;
                int cnt;
                if (type == FileType.Map) cnt = ah.FilterMaps(words, out resultVals, out resultIndexes);
                else cnt = ah.FilterMods(words, out resultVals, out resultIndexes);

                if (cnt == 0) ah.Respond(e, string.Format("No such {0} found", type));
                else
                {
                    ah.Respond(e, string.Format("Getting Zero-K mirrors for {0}, please wait", resultVals[0]));
                    GetLinksAsync(resultVals[0], e);
                }
            }
        }
		internal static FileType GetInternalFileType(FileType fileType)
		{
			switch (fileType)
			{
			case FileType.WordDocument:
			case FileType.WordDocumentX:
			case FileType.WordDocumentMacroX:
			case FileType.WordDocumentTemplateX:
			case FileType.WordDocumentMacroTemplateX:
			case FileType.RTFDocument:
				return FileType.WordDocument;

			case FileType.ExcelSheet:
			case FileType.ExcelSheetX:
			case FileType.ExcelSheetMacroX:
			case FileType.ExcelSheetTemplateX:
			case FileType.ExcelSheetMacroTemplateX:
				return FileType.ExcelSheet;

			case FileType.PowerPoint:
			case FileType.PowerPointX:
			case FileType.PowerPointMacroX:
			case FileType.PowerPointTemplateX:
			case FileType.PowerPointMacroTemplateX:
			case FileType.PowerPointShowX:
			case FileType.PowerPointMacroShowX:
				return FileType.PowerPoint;

			default:
				return fileType;
			}
		}
Esempio n. 31
0
        public static void HandleContainer(Container container)
        {
            // Get the FileType
            FileType fileType = FileTypeExtensions.GetTypeFromContainer(container);

            // Format the destination S3 path
            string s3Path = $"/smash/{FileTypeExtensions.GetNamePrefixFromType(fileType)}/{container.Id}";

            // Convert the Container into a JSON string
            byte[] json = Encoding.UTF8.GetBytes(WebFileHandler.ToJson(container));

            // Write the data to S3
            S3Api.TransferFile(json, s3Path, "data.json", "application/json");

            // Check if this has an image
            if (fileType == FileType.Event || fileType == FileType.PopUpNews || fileType == FileType.Present)
            {
                // Get the image
                byte[] image = (byte[])container.GetType().GetProperty("Image").GetValue(container);

                // Write the image to S3
                S3Api.TransferFile(image, s3Path, "image.jpg", "image/jpeg");

                // Create a new MagickImage
                using (MagickImage magickImage = new MagickImage(image))
                {
                    // Set the output format to WebP
                    magickImage.Format = MagickFormat.WebP;

                    // Create the raw WebP
                    byte[] webpImage = magickImage.ToByteArray();

                    // Upload to S3
                    S3Api.TransferFile(webpImage, s3Path, "image.webp", "image/webp");
                }
            }

            lock (WebFileHandler.Lock)
            {
                // Connect to the remote server if needed
                WebFileHandler.Connect(((SsbuBotConfiguration)Configuration.LoadedConfiguration).WebConfig);

                // Convert the Container to a StrippedContainer
                StrippedContainer strippedContainer = StrippedContainer.ConvertToStrippedContainer(container);

                // Declare a variable to hold the container list
                List <StrippedContainer> containerList;

                // Format the container list path
                string indexPath = string.Format(((SsbuBotConfiguration)Configuration.LoadedConfiguration).WebConfig.ContainerListPath, FileTypeExtensions.GetNamePrefixFromType(fileType));

                // Check if the file exists
                if (WebFileHandler.Exists(indexPath))
                {
                    // Deserialize the List
                    containerList = WebFileHandler.ReadAllText <List <StrippedContainer> >(indexPath);
                }
                else
                {
                    // Create a new List
                    containerList = new List <StrippedContainer>();
                }

                // Check if the Container already exists in the list
                int index = containerList.FindIndex(x => x.Id == container.Id);

                // Check the index
                if (index == -1)
                {
                    // Add the StrippedContainer to the List
                    containerList.Insert(0, strippedContainer);
                }
                else
                {
                    // Replace the item at the index
                    containerList[index] = strippedContainer;
                }

                // Serialize and write the container list
                WebFileHandler.WriteAllText(indexPath, WebFileHandler.ToJson(containerList));

                // Declare a variable to hold the ContainerIndex
                ContainerIndex containerIndex;

                // Check if the ContainerIndex exists
                if (!WebFileHandler.Exists(((SsbuBotConfiguration)Configuration.LoadedConfiguration).WebConfig.ContainerIndexPath))
                {
                    // Create a dummy StrippedContainer
                    StrippedContainer dummyStrippedContainer = new StrippedContainer();
                    dummyStrippedContainer.Id   = "-1";
                    dummyStrippedContainer.Text = new Dictionary <Nintendo.Bcat.Language, string>();

                    // Create a dummy ContainerIndex
                    containerIndex           = new ContainerIndex();
                    containerIndex.Event     = dummyStrippedContainer;
                    containerIndex.LineNews  = dummyStrippedContainer;
                    containerIndex.PopUpNews = dummyStrippedContainer;
                    containerIndex.Present   = dummyStrippedContainer;
                }
                else
                {
                    // Read the file
                    containerIndex = WebFileHandler.ReadAllText <ContainerIndex>(((SsbuBotConfiguration)Configuration.LoadedConfiguration).WebConfig.ContainerIndexPath);
                }

                // Get the correct property
                PropertyInfo propertyInfo = containerIndex.GetType().GetProperty(container.GetType().Name);

                // Set the value
                propertyInfo.SetValue(containerIndex, strippedContainer);

                // Write out the ContainerIndex
                WebFileHandler.WriteAllText(((SsbuBotConfiguration)Configuration.LoadedConfiguration).WebConfig.ContainerIndexPath, WebFileHandler.ToJson(containerIndex));

                // Disconnect from the remote server
                WebFileHandler.Disconnect();
            }
        }
Esempio n. 32
0
 //nothing to do here, just pass data to generic constructor
 public ItemTRSData(string _path, FileType _type) :
     base(_path, _type)
 {
 }
Esempio n. 33
0
 public FileHeader(FileType type, string extension, string header)
 {
     this.Type      = type;
     this.Extension = extension;
     this.Header    = parsePattern(header);
 }
Esempio n. 34
0
 private static extern bool RENDERDOC_GetThumbnail(IntPtr filename, FileType type, UInt32 maxsize, IntPtr outmem);
Esempio n. 35
0
 public AudioFile(string filename, FileType filetype)
 {
     m_Filename = filename;
     m_Filetype = filetype;
 }
Esempio n. 36
0
 public FileHandle getFileHandle(string path, FileType type)
 {
     return(new GLFWFileHandle(path, type));
 }
Esempio n. 37
0
        public void SendKno2Message(MessageDTO message)
        {
            try
            {
                //config DTO
                Kno2ConfigurationDTO configDTO = this.GetKno2Configuration();


                //Get the httpClient that will be used for the transmissions
                HttpClient httpClient = this.GetHttpClient(configDTO);


                //Validate the addresses (probably optional)
                Dictionary <string, bool> addressValidationResults =
                    ApiHelper.ValidateAddresses(httpClient: httpClient,
                                                directoryValidateUri: this.DirectoryValidate(),
                                                addresses: new[] { message.ToAddress, configDTO.FromAddress });

                // Request the available document types (cacheable)
                IEnumerable <string> documentTypes = ApiHelper.RequestDocumentTypes(httpClient: httpClient,
                                                                                    documentTypesUri: this.DocumentTypesUri());


                // Request a message draft id
                var outboundMessage = ApiHelper.RequestMessageDraft(httpClient: httpClient,
                                                                    messageUri: this.MessagesUri()
                                                                    );


                var      attachmentIds = new List <string>();
                FileType fileType      = message.FileType;

                //get a new file name
                string fileName = FileHelpers.GenerateAttachmentName(fileType);

                //upload the attachment
                var attachment = ApiHelper.UploadAttachment(httpClient: httpClient,
                                                            attachmentsUri: this.AttachmentsUri(outboundMessage.Id),
                                                            fileName: fileName,
                                                            attachment: new AttachmentResource
                {
                    NativeFileName  = fileName,
                    NativeFileBytes = message.FileBytes,
                    DocumentType    = documentTypes.First(),
                    AttachmentMeta  = new AttachmentMetaResource
                    {
                        DocumentTitle       = message.DocumentTitle,
                        DocumentType        = documentTypes.First(),
                        DocumentDate        = DateTime.UtcNow,
                        DocumentDescription = message.DocumentDescription,
                        Confidentiality     = Confidentiality.Normal
                    }
                }
                                                            );

                // Request the attachment meta data
                var    attachments = new List <AttachmentResource>();
                string id          = attachment.Id;

                var metadata = ApiHelper.RequestAttachmentMetadata(httpClient: httpClient,
                                                                   attachmentsUri: this.AttachmentsUri(messageId: outboundMessage.Id, attachmentId: id)
                                                                   );
                attachments.Add(metadata);


                // Send the message (draft)
                outboundMessage.Attachments = attachments;
                outboundMessage.Subject     = configDTO.Subject;
                outboundMessage.ToAddress   = message.ToAddress;
                outboundMessage.FromAddress = configDTO.FromAddress;
                outboundMessage.Comments    = message.Comments;
                outboundMessage.Body        = message.Body;

                outboundMessage.Patient = new Patient
                {
                    BirthDate  = message.BirthDate,
                    FirstName  = message.FirstName,
                    Gender     = message.Gender,
                    LastName   = message.LastName,
                    MiddleName = message.MiddleName,
                    PatientId  = message.PatientId,
                };

                ApiHelper.SendDraft(httpClient: httpClient,
                                    messageUri: this.MessagesUri(outboundMessage.Id),
                                    messageResource: outboundMessage);


                ApiHelper.SendRelease(httpClient: httpClient,
                                      messageSendUri: this.MessageSendUri(outboundMessage.Id),
                                      messageResource: outboundMessage
                                      );
            }
            catch (AggregateException ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var innerException in ex.InnerExceptions)
                {
                    sb.AppendLine(innerException.Message);
                    sb.AppendLine(innerException.StackTrace);
                    innerException.Message.ToConsole();
                    if (innerException.InnerException != null)
                    {
                        sb.AppendLine(innerException.InnerException.Message);
                        sb.AppendLine(innerException.InnerException.StackTrace);
                    }
                }
                throw new Exception(sb.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 public Document(string title, string message, FileType fileType, byte[] documentBytes)
     : base(title, message, fileType, documentBytes)
 {
 }
 public Document(string title, string message, FileType fileType, string documentPath)
     : base(title, message, fileType, documentPath)
 {
 }
Esempio n. 40
0
        private static FileInfo GetFileInfo(Context context, XmlNode node)
        {
            string   displayName = node.SelectSingleNode("DisplayName").InnerText;
            Guid     guid        = new Guid(node.SelectSingleNode("Guid").InnerText);
            int      size        = Int32.Parse(node.SelectSingleNode("Size").InnerText);
            FileType filetype    = (FileType)Enum.Parse(typeof(FileType), node.Name);

            int sectionCount = Int32.Parse(node.SelectSingleNode("Sections/@count").InnerText);

            int[]  sectionLengths     = new int[sectionCount];
            bool[] dteAllowed         = new bool[sectionCount];
            bool[] compressionAllowed = new bool[sectionCount];
            bool[] hidden             = new bool[sectionCount];

            for (int i = 0; i < sectionCount; i++)
            {
                XmlNode sectionNode = node.SelectSingleNode(string.Format("Sections/Section[@value='{0}']", i));

                XmlAttribute hideAttribute = sectionNode.Attributes["hide"];
                if (hideAttribute != null)
                {
                    hidden[i] = Boolean.Parse(hideAttribute.InnerText);
                }

                sectionLengths[i] = Int32.Parse(sectionNode.Attributes["entries"].InnerText);
                dteAllowed[i]     = Boolean.Parse(sectionNode.Attributes["dte"].InnerText);
                if (filetype == FileType.CompressedFile)
                {
                    compressionAllowed[i] = Boolean.Parse(sectionNode.Attributes["compressible"].InnerText);
                }
            }

            XmlNodeList sectors = node.SelectNodes("Sectors/*");
            Dictionary <SectorType, IList <KeyValuePair <Enum, int> > > dict = new Dictionary <SectorType, IList <KeyValuePair <Enum, int> > >(3);
            bool first = true;
            KeyValuePair <Enum, int> primaryFile = new KeyValuePair <Enum, int>();

            foreach (XmlNode sectorNode in sectors)
            {
                SectorType sectorType = (SectorType)Enum.Parse(typeof(SectorType), sectorNode.Name);
                if (!dict.ContainsKey(sectorType))
                {
                    dict.Add(sectorType, new List <KeyValuePair <Enum, int> >());
                }
                int  offset   = Int32.Parse(sectorNode.Attributes["offset"].InnerText);
                Enum fileEnum = null;
                switch (sectorType)
                {
                case SectorType.BootBin:
                    dict[sectorType].Add(new KeyValuePair <Enum, int>(PatcherLib.Iso.PspIso.Sectors.PSP_GAME_SYSDIR_BOOT_BIN, offset));
                    dict[sectorType].Add(new KeyValuePair <Enum, int>(PatcherLib.Iso.PspIso.Sectors.PSP_GAME_SYSDIR_EBOOT_BIN, offset));
                    fileEnum = PatcherLib.Iso.PspIso.Sectors.PSP_GAME_SYSDIR_BOOT_BIN;
                    break;

                case SectorType.FFTPack:
                    FFTPack.Files fftPackFile = (FFTPack.Files)Enum.Parse(typeof(FFTPack.Files), sectorNode.SelectSingleNode("@index").InnerText);
                    dict[sectorType].Add(new KeyValuePair <Enum, int>(fftPackFile, offset));
                    fileEnum = fftPackFile;
                    break;

                case SectorType.Sector:
                    PatcherLib.Iso.PsxIso.Sectors file = (PatcherLib.Iso.PsxIso.Sectors)Enum.Parse(typeof(PatcherLib.Iso.PsxIso.Sectors), sectorNode.SelectSingleNode("@filename").InnerText);
                    dict[sectorType].Add(new KeyValuePair <Enum, int>(file, offset));
                    fileEnum = file;
                    break;
                }


                if (first)
                {
                    //bytes = reader( iso, fileEnum, offset, size );
                    primaryFile = new KeyValuePair <Enum, int>(fileEnum, offset);
                    first       = false;
                }
            }

            IList <IList <string> >            entryNames   = GetEntryNames(node.SelectSingleNode("Sections"), node.SelectSingleNode("//Templates"));
            IList <string>                     sectionNames = GetSectionNames(node.SelectSingleNode("Sections"));
            IList <IList <int> >               disallowedEntries;
            IList <IDictionary <int, string> > staticEntries;

            GetDisallowedEntries(node, sectionLengths.Length, out disallowedEntries, out staticEntries);
            Set <byte> terminators    = new Set <byte>(new byte[] { 0xFE });
            XmlNode    terminatorNode = node.SelectSingleNode("Terminators");

            if (terminatorNode != null)
            {
                foreach (XmlNode nnn in terminatorNode.SelectNodes("Terminator"))
                {
                    terminators.Add(
                        byte.Parse(nnn.InnerText, System.Globalization.NumberStyles.HexNumber));
                }
            }

            FileInfo fi = new FileInfo
            {
                Context           = context,
                DisplayName       = displayName,
                DisallowedEntries = disallowedEntries.AsReadOnly(),
                StaticEntries     = staticEntries.AsReadOnly(),
                EntryNames        = entryNames.AsReadOnly(),
                FileType          = filetype,
                Guid               = guid,
                Hidden             = hidden.AsReadOnly(),
                SectionLengths     = sectionLengths.AsReadOnly(),
                Sectors            = new ReadOnlyDictionary <SectorType, IList <KeyValuePair <Enum, int> > >(dict),
                SectionNames       = sectionNames,
                AllowedTerminators = terminators.AsReadOnly(),
                Size               = size,
                PrimaryFile        = primaryFile,
                CompressionAllowed = compressionAllowed,
                DteAllowed         = dteAllowed
            };

            return(fi);
        }
Esempio n. 41
0
 public DatasourceDetail(FileType fileType, FileNameList filesName)
 {
     FileType  = fileType;
     FilesName = filesName;
 }
Esempio n. 42
0
 /// <summary>
 /// Calls on the private Add method to add an element to the Tree!
 /// </summary>
 /// <param name="filepath"> Location of the node we are removing </param>
 /// <param name="data"> Data of node we are adding </param>
 /// <param name="type"> Type of file we are adding </param>
 public void Add(Queue <string> filepath, string data, FileType type)
 {
     _elements = Add(filepath, _elements, type, data);
 }
Esempio n. 43
0
 public OpenCommand(IconFitterVM viewModel, FileType fileType) : base(viewModel)
 {
     FileType = fileType;
 }
Esempio n. 44
0
 public static string GetTemplate(this FileType ftype)
 {
     //ToDo: make templates customizable
     return(ftype.FileTemplate);
 }
Esempio n. 45
0
        public static RvFile FromADir(RvFile dbDir, EScanLevel eScanLevel, ThreadWorker bgw, ref bool fileErrorAbort)
        {
            string    fullDir   = dbDir.FullName;
            DatStatus datStatus = dbDir.IsInToSort ? DatStatus.InToSort : DatStatus.NotInDat;

            RvFile fileDir = new RvFile(FileType.Dir);


            DirectoryInfo oDir = new DirectoryInfo(fullDir);

            DirectoryInfo[] oDirs  = oDir.GetDirectories();
            FileInfo[]      oFiles = oDir.GetFiles();

            // add all the subdirectories into scanDir
            foreach (DirectoryInfo dir in oDirs)
            {
                RvFile tDir = new RvFile(FileType.Dir)
                {
                    Name             = dir.Name,
                    FileModTimeStamp = dir.LastWriteTime
                };
                tDir.SetStatus(datStatus, GotStatus.Got);
                fileDir.ChildAdd(tDir);
            }

            // add all the files into scanDir
            foreach (FileInfo oFile in oFiles)
            {
                string fName = oFile.Name;
                if (fName == "__RomVault.tmp")
                {
                    File.Delete(oFile.FullName);
                    continue;
                }
                string fExt = Path.GetExtension(oFile.Name);

                FileType ft = DBTypeGet.fromExtention(fExt);

                if (Settings.rvSettings.FilesOnly)
                {
                    ft = FileType.File;
                }

                RvFile tFile = new RvFile(ft)
                {
                    Name             = oFile.Name,
                    Size             = (ulong)oFile.Length,
                    FileModTimeStamp = oFile.LastWriteTime
                };
                tFile.FileStatusSet(FileStatus.SizeVerified);
                tFile.SetStatus(datStatus, GotStatus.Got);

                if (eScanLevel == EScanLevel.Level3 && tFile.FileType == FileType.File)
                {
                    FromAFile(tFile, fullDir, eScanLevel, bgw, ref fileErrorAbort);
                }

                fileDir.ChildAdd(tFile);
            }
            return(fileDir);
        }
Esempio n. 46
0
 public string?GetFileUrl(string name, FileType fileType)
 => fileType switch
 {
Esempio n. 47
0
        private void TextureSaveDialog_Shown(object sender, EventArgs e)
        {
            jpegCompression.Value = saveData.jpegQuality;

            blackPoint.Text = Formatter.Format(saveData.comp.blackPoint);
            whitePoint.Text = Formatter.Format(saveData.comp.whitePoint);

            mipSelect.Items.Clear();
            for (int i = 0; i < tex.mips; i++)
            {
                mipSelect.Items.Add(i + " - " + Math.Max(1, tex.width >> i) + "x" + Math.Max(1, tex.height >> i));
            }

            mipSelect.SelectedIndex = (saveData.mip >= 0 ? saveData.mip : 0);

            sampleSelect.Items.Clear();
            for (int i = 0; i < tex.msSamp; i++)
            {
                sampleSelect.Items.Add(String.Format("Sample {0}", i));
            }

            sampleSelect.SelectedIndex = Math.Min((int)tex.msSamp, (saveData.sample.sampleIndex == ~0U ? 0 : (int)saveData.sample.sampleIndex));

            resolveSamples.Enabled = true;

            if (tex.format.compType == FormatComponentType.UInt ||
                tex.format.compType == FormatComponentType.SInt ||
                tex.format.compType == FormatComponentType.Depth ||
                (tex.creationFlags & TextureCreationFlags.DSV) != 0)
            {
                resolveSamples.Enabled = false;
            }

            if (saveData.sample.sampleIndex == ~0U && resolveSamples.Enabled)
            {
                resolveSamples.Checked = true;
            }
            else
            {
                oneSample.Checked = true;
            }

            String[] cubeFaces = { "X+", "X-", "Y+", "Y-", "Z+", "Z-" };

            UInt32 numSlices = Math.Max(tex.arraysize, tex.depth);

            sliceSelect.Items.Clear();

            for (UInt32 i = 0; i < numSlices; i++)
            {
                if (tex.cubemap)
                {
                    String name = cubeFaces[i % 6];
                    if (numSlices > 6)
                    {
                        name = string.Format("[{0}] {1}", (i / 6), cubeFaces[i % 6]); // Front 1, Back 2, 3, 4 etc for cube arrays
                    }
                    sliceSelect.Items.Add(name);
                }
                else
                {
                    sliceSelect.Items.Add("Slice " + i);
                }
            }

            sliceSelect.SelectedIndex = (saveData.slice.sliceIndex >= 0 ? saveData.slice.sliceIndex : 0);

            gridWidth.Maximum = tex.depth * tex.arraysize * tex.msSamp;

            mipGroup.Visible = (tex.mips > 1);

            sampleGroup.Visible = (tex.msSamp > 1);

            sliceGroup.Visible = (tex.depth > 1 || tex.arraysize > 1 || tex.msSamp > 1);

            if (saveData.destType != FileType.DDS)
            {
                cubeCruciform.Enabled = (tex.cubemap && tex.arraysize == 6);

                if (!oneSlice.Checked && !cubeCruciform.Enabled)
                {
                    mapSlicesToGrid.Checked = true;
                }
            }

            FileType selectedType = saveData.destType;

            fileFormat.SelectedIndex = 0;
            fileFormat.SelectedIndex = 1;
            fileFormat.SelectedIndex = (int)selectedType;

            if (saveData.alpha == AlphaMapping.Discard)
            {
                alphaMap.SelectedIndex = 0;
            }
            else
            {
                alphaMap.SelectedIndex = alphaMap.Items.Count - 1;
            }
        }
Esempio n. 48
0
 /// <summary>
 /// Creates a new file object with a provided UUID
 /// </summary>
 /// <param name="uuid">The UUID of the file object</param>
 /// <param name="videoUrl">The url of the video</param>
 /// <param name="audioUrl">The url of the audio</param>
 /// <param name="title">The the title of the file</param>
 /// <param name="sha1">The sha1 hash of the file</param>
 /// <param name="subtitles">The subtitles of this file</param>
 /// <param name="duration">The duration of the file</param>
 /// <param name="isFileAvailable">Whether the file is available</param>
 /// <param name="type">Whether it's stored offline or it's downloaded</param>
 public ServerFile(int uuid, string videoUrl, string audioUrl, string title, string sha1, SubtitleInfo[] subtitles, double duration, bool isFileAvailable, FileType type) : base(videoUrl, audioUrl, title, sha1, subtitles, duration, isFileAvailable, type)
 {
     UUID = uuid;
 }
Esempio n. 49
0
        private void HandleFile(string file)
        {
            // TODO: Add support for dropping folders

            // Analyze file and find out what type it is
            FileType type = AnalyzeFile(file);

            if (type == FileType.Uknown)
            {
                lblResult.Text = "I don't know what type this file is :(";
                return;
            }

            lblResult.Text = "The file is a " + type.ToString() + " file!" + "\r\n";

            // Add the extension if it is missing
            string ext = GetExtension(type);

            FileInfo info = new FileInfo(file);

            if (info.Extension != ext)
            {
                string newFile = file + ext;
                File.Move(file, newFile);
                file = newFile;

                lblResult.Text += "Added proper extension to the file";
            }

            // If raw Steam Workshop file (7z), extract GMA file
            switch (type)
            {
            case FileType.LZMA:
                // Extract the GMA file
                lblResult.Text = "Please extract this file with 7-zip and drop the extracted file here";
                break;

            case FileType.GMAD:
                // Extract the addon folder
                lblResult.Text = "Extracting GMAD file...";

                try
                {
                    GMADTool.Extract(file, Path.GetDirectoryName(file));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "Error!");
                    lblResult.Text = "Failed to extract addon folder!";
                    break;
                }

                lblResult.Text = "Successfully extracted addon folder!";
                break;

            default:
                // Nothing more to do with the rest of the types
                lblResult.Text += "Now just put this file in the correct directory in GMOD!";
                break;
            }
        }
Esempio n. 50
0
 public SearchFile(string path, string fileName, FileType type) :
     this(new List <string>(), new FileInfo(FileUtil.JoinPath(path, fileName)), type)
 {
 }
Esempio n. 51
0
 public SearchFile(IList <string> containers, FileInfo file, FileType type)
 {
     Containers = containers;
     File       = file;
     Type       = type;
 }
Esempio n. 52
0
 public AffectedFile(string path, FileType fileType, string project)
 {
     Path     = path;
     FileType = fileType;
     Project  = project;
 }
Esempio n. 53
0
        unsafe void convert_filename(byte *srcname, byte *destname, ref FileAccessMode filemode, ref FileType filetype, ref bool wildflag)
        {
            byte *p, q;

            // Search for ':', p points to first character after ':'
            if ((p = CharFunctions.strchr(srcname, ':')) != null)
            {
                p++;
            }
            else
            {
                p = srcname;
            }

            // Convert char set of the remaining string -> destname
            q = destname;
            for (int i = 0; i < IEC.NAMEBUF_LENGTH && (*q++ = conv_from_64(*p++, true)) != 0; i++)
            {
                ;
            }

            // Look for mode parameters seperated by ','
            p = destname;
            while ((p = CharFunctions.strchr(p, ',')) != null)
            {
                // Cut string after the first ','
                *p++ = 0;
                switch ((Char)(*p))
                {
                case 'p':
                    filetype = FileType.FTYPE_PRG;
                    break;

                case 's':
                    filetype = FileType.FTYPE_SEQ;
                    break;

                case 'r':
                    filemode = FileAccessMode.FMODE_READ;
                    break;

                case 'w':
                    filemode = FileAccessMode.FMODE_WRITE;
                    break;

                case 'a':
                    filemode = FileAccessMode.FMODE_APPEND;
                    break;
                }
            }

            // Search for wildcards
            wildflag = CharFunctions.strchr(destname, '?') != null || CharFunctions.strchr(destname, '*') != null;
        }
Esempio n. 54
0
        byte open_file(int channel, BytePtr filename)
        {
            using (BytePtr plainname = new BytePtr(256))
            {
                FileAccessMode filemode = FileAccessMode.FMODE_READ;
                FileType       filetype = FileType.FTYPE_PRG;
                bool           wildflag = false;
                FileMode       fmode    = FileMode.Open;
                FileAccess     faccess  = FileAccess.Read;

                unsafe
                {
                    convert_filename(filename, plainname, ref filemode, ref filetype, ref wildflag);
                }

                // Channel 0 is READ PRG, channel 1 is WRITE PRG
                if (channel == 0)
                {
                    filemode = FileAccessMode.FMODE_READ;
                    filetype = FileType.FTYPE_PRG;
                }
                else if (channel == 1)
                {
                    filemode = FileAccessMode.FMODE_WRITE;
                    filetype = FileType.FTYPE_PRG;
                }

                // Wildcards are only allowed on reading
                if (wildflag)
                {
                    if (filemode != FileAccessMode.FMODE_READ)
                    {
                        set_error(ErrorCode1541.ERR_SYNTAX33);
                        return((byte)C64StatusCode.ST_OK);
                    }

                    find_first_file(plainname);
                }

                // Select fopen() mode according to file mode
                switch (filemode)
                {
                case FileAccessMode.FMODE_READ:
                    fmode   = FileMode.Open;
                    faccess = FileAccess.Read;
                    break;

                case FileAccessMode.FMODE_WRITE:
                    fmode   = FileMode.OpenOrCreate;
                    faccess = FileAccess.ReadWrite;
                    break;

                case FileAccessMode.FMODE_APPEND:
                    fmode   = FileMode.Append;
                    faccess = FileAccess.ReadWrite;
                    break;
                }

                try
                {
                    string fullpath = Path.Combine(dir_path, plainname.ToString());

                    file[channel] = new FileStream(fullpath, fmode, faccess);

                    if (filemode == FileAccessMode.FMODE_READ)  // Read and buffer first byte
                    {
                        read_char[channel] = (byte)file[channel].ReadByte();
                    }
                    else
                    {
                        Environment.CurrentDirectory = Assembly.GetExecutingAssembly().Location;
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    set_error(ErrorCode1541.ERR_NOTREADY);
                }
                catch (FileNotFoundException)
                {
                    set_error(ErrorCode1541.ERR_FILENOTFOUND);
                }
            }

            return((byte)C64StatusCode.ST_OK);
        }
Esempio n. 55
0
        unsafe byte open_directory(int channel, byte *filename)
        {
            using (BytePtr buf = new BytePtr(Encoding.ASCII.GetBytes("\u0001\u0004\u0001\u0001\u0000\u0000\u0012\u0022                \u0022 00 2A\0")),
                   pattern = new BytePtr(IEC.NAMEBUF_LENGTH))
            {
                //char str[NAMEBUF_LENGTH];
                byte *         p, q;
                int            i;
                FileAccessMode filemode = FileAccessMode.FMODE_READ;
                FileType       filetype = FileType.FTYPE_PRG;
                bool           wildflag = false;
                string         str;

                // Special treatment for "$0"
                if (filename[0] == '0' && filename[1] == 0)
                {
                    filename += 1;
                }

                // Convert filename ('$' already stripped), filemode/type are ignored
                convert_filename(filename, pattern, ref filemode, ref filetype, ref wildflag);

                DirectoryInfo dir = new DirectoryInfo(dir_path);
                if (!dir.Exists)
                {
                    set_error(ErrorCode1541.ERR_NOTREADY);
                    return((byte)C64StatusCode.ST_OK);
                }

                FileSystemInfo[] files = dir.GetFileSystemInfos();

                file[channel] = new FileStream(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite);

                p = (byte *)buf.Pointer + 8;

                for (i = 0; i < 16 & i < dir_title.Length; i++)
                {
                    *p++ = conv_to_64((byte)dir_title[i], false);
                }

                file[channel].Write(buf, 0, 32);

                IEnumerator fenum = files.GetEnumerator();
                while (fenum.MoveNext() && (((FileSystemInfo)fenum.Current).Name == "." || ((FileSystemInfo)fenum.Current).Name == ".."))
                {
                    ;
                }

                do
                {
                    FileSystemInfo fsi = (FileSystemInfo)fenum.Current;

                    if (match(pattern.ToString(), fsi.Name))
                    {
                        // Clear line with spaces and terminate with null byte
                        for (i = 0; i < buf.Length; i++)
                        {
                            buf[i] = (byte)' ';
                        }

                        buf[31] = 0;

                        p = buf;
                        *p++ = 0x01;    // Dummy line link
                        *p++ = 0x01;

                        if (fsi is FileInfo)
                        {
                            FileInfo fi = (FileInfo)fsi;

                            // Calculate size in blocks (254 bytes each)
                            i = (int)((fi.Length + 254) / 254);
                            *p++ = (byte)(i & 0xff);
                            *p++ = (byte)((i >> 8) & 0xff);

                            p++;
                            if (i < 10)
                            {
                                p++;            // Less than 10: add one space
                            }
                            if (i < 100)
                            {
                                p++;            // Less than 100: add another space
                            }
                            str = fi.Name;
                            // Convert and insert file name
                            *p++ = (byte)'\"';
                            q = p;
                            for (i = 0; i < 16 && i < str.Length; i++)
                            {
                                *q++ = conv_to_64((byte)str[i], true);
                            }
                            *q++ = (byte)'\"';
                            p   += 18;
                        }
                        // File type
                        if (fsi is DirectoryInfo)
                        {
                            *p++ = (byte)'D';
                            *p++ = (byte)'I';
                            *p++ = (byte)'R';
                        }
                        else
                        {
                            *p++ = (byte)'P';
                            *p++ = (byte)'R';
                            *p++ = (byte)'G';
                        }

                        // Write line
                        file[channel].Write(buf, 0, 32);
                    }
                } while (fenum.MoveNext());
            }

            // Final line

            file[channel].Write(Encoding.ASCII.GetBytes("\u0001\u0001\0\0BLOCKS FREE.             \0\0\0"), 0, 32);

            file[channel].Position = 0;
            read_char[channel]     = (byte)file[channel].ReadByte();

            return((byte)C64StatusCode.ST_OK);
        }
Esempio n. 56
0
 public SearchFile(FileInfo fileInfo, FileType type) :
     this(new List <string>(), fileInfo, type)
 {
 }
 public GetFilteredDataQuery(string username, FileType fileType, DateTime startingFrom)
 {
     Username     = username;
     FileType     = fileType;
     StartingFrom = startingFrom;
 }
Esempio n. 58
0
        public static RvFile FromADir(RvFile dbDir, EScanLevel eScanLevel, ThreadWorker bgw, ref bool fileErrorAbort)
        {
            string    fullDir   = dbDir.FullName;
            DatStatus datStatus = dbDir.IsInToSort ? DatStatus.InToSort : DatStatus.NotInDat;

            RvFile fileDir = new RvFile(FileType.Dir);


            DirectoryInfo oDir = new DirectoryInfo(fullDir);

            DirectoryInfo[] oDirs  = oDir.GetDirectories();
            FileInfo[]      oFiles = oDir.GetFiles();

            // add all the subdirectories into scanDir
            foreach (DirectoryInfo dir in oDirs)
            {
                RvFile tDir = new RvFile(FileType.Dir)
                {
                    Name      = dir.Name,
                    TimeStamp = dir.LastWriteTime
                };
                tDir.SetStatus(datStatus, GotStatus.Got);
                fileDir.ChildAdd(tDir);
            }

            // add all the files into scanDir
            foreach (FileInfo oFile in oFiles)
            {
                string fName = oFile.Name;
                if (fName == "__RomVault.tmp")
                {
                    File.Delete(oFile.FullName);
                    continue;
                }
                string fExt = Path.GetExtension(oFile.Name);

                FileType ft = DBTypeGet.fromExtention(fExt);

                if (Settings.rvSettings.FilesOnly)
                {
                    ft = FileType.File;
                }

                RvFile tFile = new RvFile(ft)
                {
                    Name      = oFile.Name,
                    Size      = (ulong)oFile.Length,
                    TimeStamp = oFile.LastWriteTime
                };
                tFile.FileStatusSet(FileStatus.SizeVerified);
                tFile.SetStatus(datStatus, GotStatus.Got);

                if (eScanLevel == EScanLevel.Level3)
                {
                    FromAFile(tFile, fullDir, eScanLevel, bgw, ref fileErrorAbort);
                }

                fileDir.ChildAdd(tFile);

                /*
                 * // if we find a zip file add it as zip files.
                 * // else
                 * if (ft == FileType.File)
                 * {
                 * // Scanning a file
                 * //
                 * // Level1 & 2 : (are the same for files) Fully checksum changed only files
                 * // Here we are just getting the TimeStamp of the File, and later
                 * // if the TimeStamp was not matched we will have to read the files CRC, MD5 & SHA1
                 * //
                 * // Level3: Fully checksum everything
                 * // Get everything about the file right here so
                 * // read CRC, MD5 & SHA1
                 *
                 * errorCode = CHD.CheckFile(oFile, out tFile.AltSHA1, out tFile.AltMD5, out tFile.CHDVersion);
                 *
                 * if (errorCode == 0)
                 * {
                 *  if (tFile.AltSHA1 != null)
                 *  {
                 *      tFile.FileStatusSet(FileStatus.AltSHA1FromHeader);
                 *  }
                 *  if (tFile.AltMD5 != null)
                 *  {
                 *      tFile.FileStatusSet(FileStatus.AltMD5FromHeader);
                 *  }
                 *
                 *  // if we are scanning at Level3 then we get all the info here
                 *  if (EScanLevel == EScanLevel.Level3)
                 *  {
                 *      FileResults(fullDir, tFile);
                 *      ChdManCheck(fullDir, tFile);
                 *  }
                 * }
                 * else if (errorCode == 32)
                 * {
                 *  tFile.GotStatus = GotStatus.FileLocked;
                 *  _bgw.Report(new bgwShowError(fullDir, "File Locked"));
                 * }
                 * else
                 * {
                 *  string filename = Path.Combine(fullDir, tFile.Name);
                 *  ReportError.Show("File: " + filename + " Error: " + new Win32Exception(errorCode).Message + ". Scan Aborted.");
                 *  _fileErrorAbort = true;
                 *  return fileDir;
                 * }
                 * }
                 */
            }
            return(fileDir);
        }
Esempio n. 59
0
 public GLFWFileHandle(string fileName, FileType type) : base(fileName, type)
 {
 }
Esempio n. 60
0
 public AllFileSelector(FileType filterType)
 {
     FilterType = filterType;
 }