Example #1
0
        private void CheckArchiveName(long highestLogVersion, long byteOffset, File corruptedLogsArchive)
        {
            string name = corruptedLogsArchive.Name;

            assertTrue(name.StartsWith("corrupted-neostore.transaction.db-" + highestLogVersion + "-" + byteOffset, StringComparison.Ordinal));
            assertTrue(FilenameUtils.isExtension(name, "zip"));
        }
Example #2
0
 public void Read(EndianReader reader)
 {
     Offset     = reader.ReadInt32();
     Size       = reader.ReadInt32();
     NameOrigin = reader.ReadString();
     Name       = FilenameUtils.FixFileIdentifier(NameOrigin);
 }
Example #3
0
 public ArchiveFileEntry(long offset, long size, string name)
 {
     Offset     = offset;
     Size       = size;
     NameOrigin = name;
     Name       = FilenameUtils.FixFileIdentifier(name);
 }
        private static async Task <UploadResult> UploadAttachmentAsync(Attachment attachment, string attachmentFilePath, bool overwriteExisting)
        {
            // Create the directory, if it does not exist.
            Directory.CreateDirectory(Path.GetDirectoryName(attachmentFilePath));

            (FileMode fileMode, string filePath) =
                overwriteExisting
                    ? (FileMode.Create, attachmentFilePath)
                    : (FileMode.CreateNew, FilenameUtils.EnsureFilenameIsUnique(attachmentFilePath));

            Logger.Trace($"Trying to upload attachment {attachment.Id} to {attachmentFilePath}");

            using (var fileStream = new FileStream(
                       filePath,
                       fileMode,
                       FileAccess.Write,
                       FileShare.None,
                       bufferSize: 4096,
                       options: FileOptions.Asynchronous | FileOptions.SequentialScan))
            {
                await attachment.Content.CopyToFastAsync(fileStream).ConfigureAwait(false);
            }

            Logger.Info($"(Deliver) Attachment {attachment.Id} is uploaded successfully to \"{attachmentFilePath}\"");
            return(UploadResult.SuccessWithUrl(attachmentFilePath));
        }
Example #5
0
        string Create(string[] parts, string fileExt)
        {
            fileExt = FilenameUtils.CleanName(fileExt);
            string tempName = string.Empty;

            foreach (var part in parts)
            {
                tempName = Path.Combine(tempName, FilenameUtils.CleanName(part));
            }
            tempName = Path.Combine(baseDir, tempName);
            var newName = tempName + fileExt;

            if (usedNames.Contains(newName))
            {
                for (int i = 2; ; i++)
                {
                    newName = tempName + "." + i.ToString() + fileExt;
                    if (!usedNames.Contains(newName))
                    {
                        break;
                    }
                }
            }
            usedNames.Add(newName);
            return(newName);
        }
Example #6
0
        string Create(string[] parts, string fileExt)
        {
            fileExt = FilenameUtils.CleanName(fileExt);
            string tempName = string.Empty;

            for (int i = 0; i < parts.Length; i++)
            {
                var part   = parts[i];
                int maxLen = i == parts.Length - 1 ? MaxNameLength : MaxDirNameLength;
                tempName = Path.Combine(tempName, FixLongName(FilenameUtils.CleanName(part), maxLen));
            }
            tempName = Path.Combine(baseDir, tempName);
            var newName = tempName + fileExt;

            if (usedNames.Contains(newName))
            {
                for (int i = 2; ; i++)
                {
                    newName = tempName + "." + i.ToString() + fileExt;
                    if (!usedNames.Contains(newName))
                    {
                        break;
                    }
                }
            }
            usedNames.Add(newName);
            return(newName);
        }
 //vormals GetApplicationNameForExe
 public Application getDescription(string application)
 {
     if (Utils.IsBlank(application))
     {
         return(Application.notfound);
     }
     if (!applicationNameCache.contains(application))
     {
         string path = WindowsApplicationLauncher.GetExecutableCommand(application);
         if (File.Exists(path))
         {
             FileVersionInfo info = FileVersionInfo.GetVersionInfo(path);
             if (Utils.IsBlank(info.FileDescription))
             {
                 // Does not contain version information
                 applicationNameCache.put(application, new Application(
                                              application.ToLower(),
                                              FilenameUtils.getName(application)));
             }
             else
             {
                 applicationNameCache.put(application, new Application(
                                              application.ToLower(),
                                              info.FileDescription));
             }
         }
         else
         {
             applicationNameCache.put(application, new Application(
                                          application.ToLower(),
                                          FilenameUtils.getName(application)));
         }
     }
     return(applicationNameCache.get(application) as Application);
 }
Example #8
0
        internal SerializedFile(IFileCollection collection, IAssemblyManager manager, SerializedFileScheme scheme)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }
            if (scheme == null)
            {
                throw new ArgumentNullException(nameof(scheme));
            }

            Collection      = collection;
            AssemblyManager = manager;
            FilePath        = scheme.FilePath;
            NameOrigin      = scheme.Name;
            Name            = FilenameUtils.FixFileIdentifier(scheme.Name);
            Flags           = scheme.Flags;

            Header   = scheme.Header;
            Metadata = scheme.Metadata;
        }
Example #9
0
        private void ReadScheme()
        {
            using (PartialStream stream = new PartialStream(m_stream, m_offset, m_size))
            {
                using (EndianReader reader = new EndianReader(stream, EndianType.BigEndian))
                {
                    Header.Read(reader);
                }

                EndianType endianess = Header.SwapEndianess ? EndianType.BigEndian : EndianType.LittleEndian;
                using (SerializedFileReader reader = new SerializedFileReader(stream, endianess, Header.Generation))
                {
                    if (IsMetadataAtTheEnd(reader.Generation))
                    {
                        reader.BaseStream.Position = Header.FileSize - Header.MetadataSize;
                        reader.BaseStream.Position++;
                    }

                    Metadata.Read(reader);
                }
            }

#warning TEMP HACK
            Flags = Metadata.Hierarchy.Platform == Platform.NoTarget ? TransferInstructionFlags.NoTransferInstructionFlags : Flags;
            if (FilenameUtils.IsEngineResource(Name) || Header.Generation < FileGeneration.FG_500a1 && FilenameUtils.IsBuiltinExtra(Name))
            {
                Flags |= TransferInstructionFlags.IsBuiltinResourcesFile;
            }
            Flags |= Header.SwapEndianess ? TransferInstructionFlags.SwapEndianess : TransferInstructionFlags.NoTransferInstructionFlags;
        }
Example #10
0
        DecompileContext CreateDecompileContext()
        {
            string ext, name;

            if (bamlNode.DisassembleBaml)
            {
                ext  = ".baml";
                name = dnSpy_BamlDecompiler_Resources.BAMLFile;
            }
            else
            {
                ext  = ".xaml";
                name = dnSpy_BamlDecompiler_Resources.XAMLFile;
            }
            var saveDlg = new SaveFileDialog {
                FileName   = FilenameUtils.CleanName(RemovePath(bamlNode.GetFilename())),
                DefaultExt = ext,
                Filter     = $"{name}|*{ext}|{dnSpy_BamlDecompiler_Resources.AllFiles}|*.*",
            };

            if (saveDlg.ShowDialog() != DialogResult.OK)
            {
                return(null);
            }
            return(CreateDecompileContext(saveDlg.FileName));
        }
Example #11
0
        protected override void setPath(string filename)
        {
            string parent = Path.Combine(FilenameUtils.getPrefix(filename),
                                         MakeValidPath(FilenameUtils.getPath(filename)));
            string name = MakeValidFilename(FilenameUtils.getName(filename));

            base.setPath(parent + name);
        }
Example #12
0
 public static void FixResourceVersion(string name, ref RTTIClassHierarchyDescriptor origin)
 {
     if (origin.Version == new Version(5, 6, 4, VersionType.Patch, 1))
     {
         if (FilenameUtils.IsDefaultResource(name))
         {
             origin.Version = new Version(5, 6, 5, VersionType.Final);
         }
     }
 }
Example #13
0
 private void CompareSnapshotFiles(ISet <string> firstSnapshotFileNames, ISet <string> secondSnapshotFileNames, FileSystemAbstraction fileSystem)
 {
     assertThat(format("Should have %d modified index segment files. Snapshot segment files are: %s", NUMBER_OF_INDEXES, firstSnapshotFileNames), firstSnapshotFileNames, hasSize(NUMBER_OF_INDEXES));
     foreach (string fileName in firstSnapshotFileNames)
     {
         assertFalse("Snapshot segments fileset should not have files from another snapshot set." + DescribeFileSets(firstSnapshotFileNames, secondSnapshotFileNames), secondSnapshotFileNames.Contains(fileName));
         string path = FilenameUtils.getFullPath(fileName);
         assertTrue("Snapshot should contain files for index in path: " + path + "." + DescribeFileSets(firstSnapshotFileNames, secondSnapshotFileNames), secondSnapshotFileNames.Any(name => name.StartsWith(path)));
         assertTrue(format("Snapshot segment file '%s' should exist.", fileName), fileSystem.FileExists(new File(fileName)));
     }
 }
        private async Task Generate()
        {
            ProcessFailed        = false;
            generatingInProgress = true;
            CmdOutputString      = String.Empty;
            string path = FilenameUtils.GetTempFilePathWithExtension(".txt");

            File.WriteAllText(path, GpgBatchGenerator.GetScript(ToGpgKeygenParams()));
            Wrapper cmdWrapper = new Wrapper();

            cmdWrapper.Exited          += CmdWrapper_Exited;
            cmdWrapper.Failed          += CmdWrapper_Failed;
            cmdWrapper.OnIncommingText += CmdWrapper_OnIncommingText;
            CmdOutputString            += "Tworzenie klucza: " + System.Environment.NewLine;
            await RunGpgCommand(cmdWrapper, " --batch --gen-key -v " + path);

            if (ProcessFailed)
            {
                CmdOutputString =
                    "Wygenerowanie niemożliwe. Proszę zainstalować pakieg GPG";
                return;
            }

            string keyId =
                CmdOutputString.Split(Environment.NewLine.ToCharArray()).Last(w => String.IsNullOrEmpty(w) == false)
                .Split(' ')[5].Remove(0, 2).Trim();

            File.Delete(path);
            CmdOutputString += "Import klucza do bazy lokalnej: " + System.Environment.NewLine;
            await RunGpgCommand(cmdWrapper,
                                $"--import {GpgKeygenParams.DefaultPublicKeyFilename} {GpgKeygenParams.DefaultPrivateKeyFilename}");


            if (MessageBox.Show("Czy wysłać nowo wygenerowany klucz publiczny na serwer?", "Pytanie", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                await RunGpgCommand(cmdWrapper,
                                    $" --keyserver {Properties.Settings.Default.KeyServer}  --send-key {keyId}");

                CmdOutputString += "Zakończono wysyłanie" + System.Environment.NewLine;
            }

            if (!Limited)
            {
                if (MessageBox.Show("Czy przygotować dokument dla nowo wygenerowanego klucza?", "Pytanie",
                                    MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                {
                    KeyIntroduceGenerator generator = new KeyIntroduceGenerator();
                    generator.GenerateDocument(Properties.Settings.Default.DocumentOutputPath, keyId, Username);
                    CmdOutputString += "Zakończono tworzenie dokumentów" + System.Environment.NewLine;
                }
            }

            ClearFields();
        }
Example #15
0
 private static bool IsEngineFile(string fileName)
 {
     if (FilenameUtils.IsDefaultResource(fileName))
     {
         return(true);
     }
     if (FilenameUtils.IsBuiltinExtra(fileName))
     {
         return(true);
     }
     return(false);
 }
Example #16
0
        /// <summary>
        /// Find a bitmap in the ResourcesBundle for a given name
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Bitmap IconForName(string name, int size)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                name = "notfound.tiff";
            }

            Bitmap image = _bitmapCache.Get(name, size);

            if (null == image)
            {
                if (FilenameUtils.getPrefix(name) != string.Empty)
                {
                    try
                    {
                        image = new Icon(name, size, size).ToBitmap();
                    }
                    catch (ArgumentException)
                    {
                        //was not an icon, try as plain bitmap
                        image = (Bitmap)Image.FromFile(name);
                        if (size > 0)
                        {
                            image = ResizeImage(image, new Size(size, size));
                        }
                    }
                }
                else
                {
                    object obj = ResourcesBundle.ResourceManager.GetObject(FilenameUtils.getBaseName(name),
                                                                           ResourcesBundle.Culture);
                    if (obj is Icon)
                    {
                        image = (new Icon(obj as Icon, size, size)).ToBitmap();
                    }
                    else if (obj is Bitmap)
                    {
                        image = (Bitmap)obj;
                    }
                }
                if (image != null && image.RawFormat == ImageFormat.Tiff)
                {
                    // handle multi-page tiffs
                    image = GetTiffImage(image, size);
                }
                else if (size > 0)
                {
                    image = ResizeImage(image, new Size(size, size));
                }
                _bitmapCache.Put(name, image, size);
            }
            return(image);
        }
Example #17
0
 public void Read(SerializedFileReader reader)
 {
     if (IsReadAssetName(reader.Generation))
     {
         AssetPath = reader.ReadStringZeroTerm();
     }
     if (IsReadHash(reader.Generation))
     {
         Hash.Read(reader);
         Type = (AssetType)reader.ReadInt32();
     }
     FilePathOrigin = reader.ReadStringZeroTerm();
     FilePath       = FilenameUtils.FixFileIdentifier(FilePathOrigin);
 }
Example #18
0
        static string GetRelativePath(string sourceDir, string destFile)
        {
            var s = FilenameUtils.GetRelativePath(sourceDir, destFile);

            if (Path.DirectorySeparatorChar != '\\')
            {
                s = s.Replace(Path.DirectorySeparatorChar, '\\');
            }
            if (Path.AltDirectorySeparatorChar != '\\')
            {
                s = s.Replace(Path.AltDirectorySeparatorChar, '\\');
            }
            return(s);
        }
Example #19
0
 /// <summary>
 /// Get file extension. Ignores OS specific special characters. Includes the dot if available.
 /// </summary>
 /// <param name="filename"></param>
 /// <returns></returns>
 public static string GetSafeExtension(string filename)
 {
     if (IsNotBlank(filename))
     {
         //see http://windevblog.blogspot.com/2008/09/get-default-application-in-windows-xp.html
         string extension = FilenameUtils.getExtension(filename);
         if (IsBlank(extension))
         {
             return(String.Empty);
         }
         return("." + extension);
     }
     return(String.Empty);
 }
 public void Read(SerializedReader reader)
 {
     if (HasAssetPath(reader.Generation))
     {
         AssetPath = reader.ReadStringZeroTerm();
     }
     if (HasHash(reader.Generation))
     {
         Guid.Read(reader);
         Type = (AssetType)reader.ReadInt32();
     }
     PathNameOrigin = reader.ReadStringZeroTerm();
     PathName       = FilenameUtils.FixFileIdentifier(PathNameOrigin);
 }
Example #21
0
        DecompileContext CreateDecompileContext()
        {
            var saveDlg = new SaveFileDialog {
                FileName   = FilenameUtils.CleanName(nodes[0].ToString(decompiler, DocumentNodeWriteOptions.Title)) + decompiler.FileExtension,
                DefaultExt = decompiler.FileExtension,
                Filter     = $"{decompiler.GenericNameUI}|*{decompiler.FileExtension}|{dnSpy_Resources.AllFiles}|*.*",
            };

            if (saveDlg.ShowDialog() != true)
            {
                return(null);
            }
            return(CreateDecompileContext(saveDlg.FileName));
        }
Example #22
0
        DecompileContext CreateDecompileContext()
        {
            var saveDlg = new SaveFileDialog {
                FileName   = FilenameUtils.CleanName(nodes[0].ToString(decompiler)) + decompiler.FileExtension,
                DefaultExt = decompiler.FileExtension,
                Filter     = string.Format("{0}|*{1}|{2}|*.*", decompiler.GenericNameUI, decompiler.FileExtension, dnSpy_Resources.AllFiles),
            };

            if (saveDlg.ShowDialog() != true)
            {
                return(null);
            }
            return(CreateDecompileContext(saveDlg.FileName));
        }
 public void Read(SerializedFileStream stream)
 {
     if (IsReadAssetName(stream.Generation))
     {
         AssetPath = stream.ReadStringZeroTerm();
     }
     if (IsReadHash(stream.Generation))
     {
         Hash.Read(stream);
         Type = (AssetType)stream.ReadInt32();
     }
     FilePathOrigin = stream.ReadStringZeroTerm();
     FilePath       = FilenameUtils.FixFileIdentifier(FilePathOrigin);
 }
Example #24
0
        void Write(XmlWriter writer, BuildAction buildAction)
        {
            var files = project.Files.Where(a => a.BuildAction == buildAction).OrderBy(a => a.Filename, StringComparer.OrdinalIgnoreCase).ToArray();

            if (files.Length == 0)
            {
                return;
            }
            writer.WriteStartElement("ItemGroup");
            foreach (var file in files)
            {
                if (file.BuildAction == BuildAction.DontIncludeInProjectFile)
                {
                    continue;
                }
                writer.WriteStartElement(ToString(buildAction));
                writer.WriteAttributeString("Include", GetRelativePath(file.Filename));
                if (file.DependentUpon != null)
                {
                    writer.WriteElementString("DependentUpon", FilenameUtils.GetRelativePath(Path.GetDirectoryName(file.Filename), file.DependentUpon.Filename));
                }
                if (file.SubType != null)
                {
                    writer.WriteElementString("SubType", file.SubType);
                }
                if (file.Generator != null)
                {
                    writer.WriteElementString("Generator", file.Generator);
                }
                if (file.LastGenOutput != null)
                {
                    writer.WriteElementString("LastGenOutput", FilenameUtils.GetRelativePath(Path.GetDirectoryName(file.Filename), file.LastGenOutput.Filename));
                }
                if (file.AutoGen)
                {
                    writer.WriteElementString("AutoGen", "True");
                }
                if (file.DesignTime)
                {
                    writer.WriteElementString("DesignTime", "True");
                }
                if (file.DesignTimeSharedInput)
                {
                    writer.WriteElementString("DesignTimeSharedInput", "True");
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }
        private string AssembleFileDownloadUrlFor(Attachment attachment, MessageInfo referringUserMessage)
        {
            try
            {
                string extension     = MimeTypeRepository.Instance.GetExtensionFromMimeType(attachment.ContentType);
                string fileName      = PayloadFileNameFactory.CreateFileName(NamePattern, attachment, referringUserMessage);
                string validFileName = FilenameUtils.EnsureValidFilename($"{fileName}{extension}");

                return(Path.Combine(Location, validFileName));
            }
            catch (Exception ex)
            {
                Logger.Error($"An fatal error occured while determining the file path: {ex}");
                return(null);
            }
        }
Example #26
0
 protected override void OnCellEditStarting(CellEditEventArgs e)
 {
     e.Control.AutoSize = false;
     e.Control.Bounds   = new Rectangle(e.Control.Bounds.X + IconSize, e.Control.Bounds.Y,
                                        e.Control.Bounds.Width - IconSize, e.Control.Bounds.Height);
     if (e.Control is TextBox)
     {
         //Only select filename part w/o extension (Explorer like behavior)
         TextBox tb             = e.Control as TextBox;
         int     extensionIndex = FilenameUtils.indexOfExtension((string)e.Value);
         if (extensionIndex > -1)
         {
             tb.Select(0, extensionIndex);
         }
     }
     base.OnCellEditStarting(e);
 }
Example #27
0
 public void Read(BundleReader reader)
 {
     if (HasBlobIndex(reader.Generation))
     {
         Offset     = reader.ReadInt64();
         Size       = reader.ReadInt64();
         BlobIndex  = reader.ReadInt32();
         NameOrigin = reader.ReadStringZeroTerm();
     }
     else
     {
         NameOrigin = reader.ReadStringZeroTerm();
         Offset     = reader.ReadInt32();
         Size       = reader.ReadInt32();
     }
     Name = FilenameUtils.FixFileIdentifier(NameOrigin);
 }
Example #28
0
        public static String ConvertFileNameToClassName(string root, FileInfo file)
        {
            String rootName = root + System.IO.Path.DirectorySeparatorChar;

            if (file.FullName.StartsWith(rootName))
            {
                String fileName = StringUtils.Replace(file.FullName, rootName, "");
                return(FilenameUtils.RemoveExtension(fileName).Replace(
                           System.IO.Path.DirectorySeparatorChar, '.'));
            }
            else
            {
                throw new ArgumentException(rootName
                                            + " doesn't look like the root of "
                                            + file.FullName);
            }
        }
Example #29
0
 public void Read(BundleReader reader)
 {
     if (HasBlobIndex(reader.Signature))
     {
         Offset     = reader.ReadInt64();
         Size       = reader.ReadInt64();
         BlobIndex  = reader.ReadInt32();
         PathOrigin = reader.ReadStringZeroTerm();
     }
     else
     {
         PathOrigin = reader.ReadStringZeroTerm();
         Offset     = reader.ReadInt32();
         Size       = reader.ReadInt32();
     }
     Path = FilenameUtils.FixFileIdentifier(PathOrigin);
 }
Example #30
0
        private static async Task LogReceivedMessageMessageAsync(ReceivedMessage message, Uri url)
        {
            const string logDir = @".\logs\receivedmessages\";

            if (Directory.Exists(logDir) == false)
            {
                Directory.CreateDirectory(logDir);
            }

            string hostInformation;

            try
            {
                hostInformation = $"{url.Host}_{url.Port}";
            }
            catch
            {
                hostInformation = "localhost";
            }

            try
            {
                string newReceivedMessageFile =
                    FilenameUtils.EnsureValidFilename($"{hostInformation}.{Guid.NewGuid()}.{DateTime.Now:yyyyMMdd}");

                Logger.Info($"Logging to \"{newReceivedMessageFile}\"");

                using (FileStream destinationStream =
                           FileUtils.CreateAsync(
                               Path.Combine(logDir, newReceivedMessageFile),
                               FileOptions.SequentialScan))
                {
                    await message.UnderlyingStream
                    .CopyToFastAsync(destinationStream)
                    .ConfigureAwait(false);
                }

                message.UnderlyingStream.Position = 0;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                throw;
            }
        }