Example #1
1
        public override void Import(IFile fileSystem, string rootPath)
        {
            string folderPath = GetFolder(rootPath);

            string fileFullPath = System.IO.Path.Combine(folderPath, GetExportedFilename());
            content = fileSystem.ReadBinary(fileFullPath);
        }
		public ISourceSymbol[] SourceSymbolsFor(IFile file)
		{
			var provider = ProviderFor(file);
			return provider != null
				? provider.SourceSymbolsFor(file)
				: EmptyArray.Of<ISourceSymbol>();
		}
Example #3
0
 public static async Task<KcpKeyFile> Create(IFile storageFile, ICanSHA256Hash hasher)
 {
     var kcpKeyFile = new KcpKeyFile();
     _hasher = hasher;
     await kcpKeyFile.Init(storageFile);
     return kcpKeyFile;
 }
 public void ExploreFile(IFile psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
 {
   if ((psiFile.Language.Name == "CSHARP") || (psiFile.Language.Name == "VBASIC"))
   {
     psiFile.ProcessDescendants(new FileExplorer(_provider, _factories, psiFile, consumer, interrupted));
   }
 }
 public void ExploreFile(IFile psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
 {
     if ((psiFile.Language.Is<JavaScriptLanguage>() && !psiFile.Language.Is<JavaScriptWinRTLanguage>()) && (psiFile.GetProject() != null))
     {
         psiFile.ProcessDescendants(new JasmineFileExplorer(myFactory, consumer, psiFile, interrupted, myJavaScriptDependencyManager.GetTransitiveDependencies(psiFile.GetSourceFile())));
     }
 }
Example #6
0
        public FileStream(IFile file)
        {
            if (file == null)
                throw new ArgumentNullException("file");

            File = file;
        }
Example #7
0
 static bool IsDescriptorFilename(IFile file)
 {
     return file.FullPath.EndsWith("/bundle.txt", StringComparison.OrdinalIgnoreCase) ||
            file.FullPath.EndsWith("/scriptbundle.txt", StringComparison.OrdinalIgnoreCase) ||
            file.FullPath.EndsWith("/stylesheetbundle.txt", StringComparison.OrdinalIgnoreCase) ||
            file.FullPath.EndsWith("/htmltemplatebundle.txt", StringComparison.OrdinalIgnoreCase);
 }
Example #8
0
 public static ModelReference CreateModelReference(IFile file)
 {
     var model = LoadModel(file);
     var reference = new ModelReference(file.FullPathName, model);
     References.Add(reference);
     return reference;
 }
 public ResharperProjectUpdater(IFile descriptor, resharper::JetBrains.ProjectModel.IProject project, Func<ExecutionEnvironment> env)
 {
     _project = project;
     _ignoredAssemblies = ReadIgnoredAssemblies();
     Descriptor = descriptor;
     _env = env;
 }
Example #10
0
        public Suite(IFile systemFile)
        {
            System = Path.GetFileNameWithoutExtension(systemFile.FullPath);
            SystemFile = systemFile;

            LastRun = DateTime.MinValue;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SelfMediaDatabase.Core.Operations.Prune.PruneOperation"/> class.
        /// </summary>
        /// <param name="directory">Injection wrapper of <see cref="System.IO.Directory"/>.</param>
        /// <param name="file">Injection wrapper of <see cref="System.IO.File"/>.</param>
        /// <param name="path">Injection wrapper of <see cref="System.IO.Path"/>.</param>
        /// <param name="imageComparer">Image comparer.</param>
        /// <param name="fileSystemHelper">Helper to access to files.</param>
        public PruneOperation(
            IDirectory directory, 
            IFile file, 
            IPath path, 
            IImageComparer imageComparer, 
            IFileSystemHelper fileSystemHelper,
            IDialog dialog,
            IRenameOperation renameOperation)
        {
            if (directory == null)
                throw new ArgumentNullException("directory");
            if (file == null)
                throw new ArgumentNullException("file");
            if (imageComparer == null)
                throw new ArgumentNullException("imageComparer");
            if (fileSystemHelper == null)
                throw new ArgumentNullException("fileSystemHelper");
            if (path == null)
                throw new ArgumentNullException("path");
            if (dialog == null)
                throw new ArgumentNullException("dialog");
            if (renameOperation == null)
                throw new ArgumentNullException("renameOperation");

            _directory = directory;
            _file = file;
            _path = path;
            _imageComparer = imageComparer;
            _fileSystemHelper = fileSystemHelper;
            _dialog = dialog;
            _renameOperation = renameOperation;
        }
Example #12
0
        public string Compile(string source, IFile sourceFile)
        {
            lock (_lock)
            {
                rootDirectory = sourceFile.Directory;
                Initialize();

                StartRecordingOpenedFiles();
                dependentFileList.Add(sourceFile.FullPath);

                try
                {
                    var compilerOptions = GetCompilerOptions(sourceFile);
                    return (string)sassCompiler.compile(source, compilerOptions);
                }
                catch (Exception e)
                {
                    // Provide more information for SassSyntaxErrors
                    if (e.Message == "Sass::SyntaxError")
                    {
                        throw CreateSassSyntaxError(sourceFile, e);
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    StopRecordingOpenedFiles();
                }
            }
        }
 // TODO: Read-retry should be part of an extension method that can be reused for reading the index in indexed folder repositories.
 public IPackageDescriptor Read(IFile filePath)
 {
     if (!filePath.Exists)
         return null;
     IOException ioException = null;
     int tries = 0;
     while (tries < FILE_READ_RETRIES)
     {
         try
         {
             using (var fileStream = filePath.OpenRead())
             {
                 var descriptor = new PackageDescriptorReader().Read(fileStream);
                 if (descriptor.Name == null)
                     descriptor.Name = PackageNameUtility.GetName(filePath.NameWithoutExtension);
                 return descriptor;
             }
         }
         catch (InvalidPackageException ex)
         {
             throw new InvalidPackageException(String.Format("Invalid package for file '{0}'.", filePath.Path), ex);
         }
         catch (IOException ex)
         {
             ioException = ex;
             tries++;
             Thread.Sleep(FILE_READ_RETRIES_WAIT);
             continue;
         }
     }
     throw ioException;
 }
Example #14
0
        /// <summary>
        /// Resolves the path to vsce..
        /// </summary>
        /// <returns>The path to vsce.</returns>
        public FilePath ResolvePath()
        {
            // Check if path allready resolved
            if (_cachedPath != null && _cachedPath.Exists)
            {
                return _cachedPath.Path;
            }

            // Last resort try path
            var envPath = _environment.GetEnvironmentVariable("path");
            if (!string.IsNullOrWhiteSpace(envPath))
            {
                var pathFile = envPath
                    .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(path => _fileSystem.GetDirectory(path))
                    .Where(path => path.Exists)
                    .Select(path => path.Path.CombineWithFilePath("vsce.cmd"))
                    .Select(_fileSystem.GetFile)
                    .FirstOrDefault(file => file.Exists);

                if (pathFile != null)
                {
                    _cachedPath = pathFile;
                    return _cachedPath.Path;
                }
            }

            throw new CakeException("Could not locate vsce.");
        }
Example #15
0
 public ConfigWriter(IFile file, string filePath)
 {
     mDoc = XDocument.Parse(file.ReadAllText(filePath));
       mDoc.Declaration = new XDeclaration("1.0", null, null);
       mFile = file;
       mPath = filePath;
 }
        public void SetUp()
        {
            _file = MockRepository.GenerateMock<IFile>();
            _recentActivities = new RecentActivities(_file);

            _recentActivities.Update(FIRST_ACTIVITY);
        }
 public override void Open(IFile file, int cacheSizeInBytes)
 {
     base.Open(asyncBufSize != 0
         ? (ReplicationMasterFile)new AsyncReplicationMasterFile(this, file, asyncBufSize)
         : new ReplicationMasterFile(this, file),
         cacheSizeInBytes);
 }
        /// <summary>
        /// Adds a <see cref="IFile"/> to the current <see cref="IDirectory"/>.
        /// </summary>
        public void AddFile(IFile file)
        {
            if (_files.Contains(file)) return;

            file.Directory = this;
            _files.Add(file);
        }
Example #19
0
        CompileResult CompileImpl(string lessSource, IFile file)
        {
            currentFiles.Push(file);

            var parser = (ObjectInstance)ScriptEngine.Evaluate("(new window.less.Parser)");
            var callback = new CompileResult(ScriptEngine);
            try
            {
                parser.CallMemberFunction("parse", lessSource, callback);
            }
            catch (JavaScriptException ex)
            {
                var message = ((ObjectInstance)ex.ErrorObject).GetPropertyValue("message").ToString();
                throw new LessCompileException(
                    string.Format(
                        "Less compile error in {0}:\r\n{1}",
                        file.FullPath,
                        message
                    )
                );
            }
            catch (InvalidOperationException ex)
            {
                throw new LessCompileException(
                    string.Format("Less compile error in {0}.", file.FullPath),
                    ex
                );
            }

            currentFiles.Pop();
            return callback;
        }
Example #20
0
        public override TexturePackage CreatePackage(IFile package)
        {
            var tp = new TexturePackage(package, this);
            if (LoadFromCache(tp)) return tp;

            var list = new List<TextureItem>();
            try
            {
                HLLib.Initialize();
                using (var pack = new HLLib.Package(package.FullPathName))
                {
                    var folder = pack.GetRootFolder();
                    var items = folder.GetItems();
                    list.AddRange(items
                        .Select(item => new HLLib.WADFile(item))
                        .Where(wad => IsValidLumpType(wad.GetLumpType()))
                        .Select(wad => new TextureItem(tp, StripExtension(wad.Name), wad.Width, wad.Height)));
                }
            }
            finally
            {
                HLLib.Shutdown();
            }
            foreach (var ti in list)
            {
                tp.AddTexture(ti);
            }
            SaveToCache(tp);
            return tp;
        }
Example #21
0
 public CachedZipPackage(IPackageRepository source, IFile packageFile, IDirectory cacheDirectoryPath, IEnumerable<IExportBuilder> builders)
     : base(packageFile)
 {
     Source = source;
     _cacheDirectoryPathPath = cacheDirectoryPath;
     _builders = builders;
 }
Example #22
0
        public string Compile(string lessSource, IFile sourceFile)
        {
            Trace.Source.TraceInformation("Compiling {0}", sourceFile.FullPath);
            lock (ScriptEngine)
            {
                currentFiles.Clear();
                ScriptEngine.SetGlobalFunction("xhr", new Action<ObjectInstance, ObjectInstance, FunctionInstance, FunctionInstance>(Xhr));

                var result = CompileImpl(lessSource, sourceFile);
                if (result.Css != null)
                {
                    Trace.Source.TraceInformation("Compiled {0}", sourceFile.FullPath);
                    return result.Css;
                }
                else
                {
                    var message = string.Format(
                        "Less compile error in {0}:\r\n{1}",
                        sourceFile.FullPath,
                        result.ErrorMessage
                    );
                    Trace.Source.TraceEvent(TraceEventType.Critical, 0, message);
                    throw new LessCompileException(message);
                }
            }
        }
 public PackageDescriptor Read(IFile filePath)
 {
     if (!filePath.Exists)
         return null;
     IOException ioException = null;
     int tries = 0;
     while (tries < FILE_READ_RETRIES)
     {
         try
         {
             using (var fileStream = filePath.OpenRead())
             {
                 var descriptor = Read(fileStream);
                 if (descriptor.Name == null)
                     descriptor.Name = PackageNameUtility.GetName(filePath.NameWithoutExtension);
                 return descriptor;
             }
         }
         catch (IOException ex)
         {
             ioException = ex;
             tries++;
             Thread.Sleep(FILE_READ_RETRIES_WAIT);
             continue;
         }
     }
     throw ioException;
 }
        public void ExploreFile(IFile psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
        {
            if (psiFile.Language.Name != "CSHARP" && psiFile.Language.Name != "VBASIC")
                return;

            psiFile.ProcessDescendants(new XunitFileExplorer(provider, psiFile.GetSourceFile().ToProjectFile(), consumer, interrupted));
        }
Example #25
0
        public string Compile(string lessSource, IFile sourceFile)
        {
            Trace.Source.TraceInformation("Compiling {0}", sourceFile.FullPath);
            lock (engine)
            {
                currentFiles.Clear();

                var result = CompileImpl(lessSource, sourceFile);
                if (result.Css != null)
                {
                    Trace.Source.TraceInformation("Compiled {0}", sourceFile.FullPath);
                    return result.Css;
                }
                else
                {
                    var message = string.Format(
                        "Less compile error in {0}:\r\n{1}",
                        sourceFile.FullPath,
                        result.ErrorMessage
                    );
                    Trace.Source.TraceEvent(TraceEventType.Critical, 0, message);
                    throw new LessCompileException(message);
                }
            }
        }
Example #26
0
        private static void ReplaceLegacyControlTags(IFile file)
        {
            var contents = file.Contents;

            var regex = new Regex
                (@"(<%@\s*?Register\s+?TagPrefix="")(.+?)(""\s+?Namespace="".+?""\s+?Assembly="")(Subtext.Web.Controls)(""\s*?%>)"
                , RegexOptions.IgnoreCase | RegexOptions.Multiline
                );

            var newContent = regex.Replace(contents, delegate(Match m)
            {
                if (m.Groups[2].Value.Equals("st", StringComparison.CurrentCultureIgnoreCase))
                {
                    return string.Empty;
                }
                var sb = new StringBuilder();

                sb.Append(m.Groups[1].Value);
                sb.Append(m.Groups[2].Value);
                sb.Append(m.Groups[3].Value);
                sb.Append("Subtext.Web");
                sb.Append(m.Groups[5].Value);

                return sb.ToString();
            });

            if (contents != newContent)
            {
                var stream = new StreamWriter(file.OpenWrite());
                stream.Write(newContent);
                stream.Close();
            }
        }
 public OperationResult Post(IFile file)
 {
     return new OperationResult.SeeOther
         {
             RedirectLocation = typeof(UploadedFile).CreateUri(new { id = this.ReceiveStream(file.ContentType, file.OpenStream()) })
         };
 }
    public IEnumerable<UnitTestElementDisposition> AcceptElement(IElement element, IFile file)
#endif
    {
      IDeclaration declaration = (IDeclaration)element;
      var behaviorElement = _behaviorFactory.CreateBehavior(declaration.DeclaredElement);
      
      if (behaviorElement == null)
      {
        yield break;
      }

      yield return new UnitTestElementDisposition(behaviorElement,
#if RESHARPER_6
                                                  file.GetSourceFile().ToProjectFile(),
#else
                                                  file.ProjectFile,
#endif
                                                  declaration.GetNavigationRange().TextRange,
                                                  declaration.GetDocumentRange().TextRange);

      var behaviorSpecifications =
        _behaviorSpecificationFactory.CreateBehaviorSpecificationsFromBehavior(behaviorElement,
                                                                               declaration.DeclaredElement);

      foreach (var behaviorSpecificationElement in behaviorSpecifications)
      {
        yield return new UnitTestElementDisposition(new UnitTestElementLocation[0],
                                                    behaviorSpecificationElement);
      }
    }
Example #29
0
        public void DecryptToStream(IFile file, Stream outputStream)
        {
            if (file == null)
                throw new ArgumentNullException(nameof(file));
            if (outputStream == null)
                throw new ArgumentNullException(nameof(outputStream));

            //Read IV
            int ivSize = _encryptionProvider.BlockSize / 8;
            byte[] iv = new byte[ivSize];
            using (Stream fileData = file.Read())
            {
                fileData.Seek(0, SeekOrigin.Begin);
                fileData.Read(iv, 0, iv.Length);

                //Write decrypted data
                byte[] key = _key.GenerateBlock(_encryptionProvider.BlockSize);
                ICryptoTransform decryptor = _encryptionProvider.CreateDecryptor(key, iv);

                using (var cryptoStream = new CryptoStream(fileData, decryptor, CryptoStreamMode.Read))
                {
                    cryptoStream.CopyTo(outputStream);
                }
            }
        }
        public UncompressedPackage(IPackageRepository source,
                                   IFile originalPackageFile,
                                   IDirectory wrapCacheDirectory)
        {
            Check.NotNull(source, "source");
            if (originalPackageFile == null || originalPackageFile.Exists == false)
            {
                IsValid = false;
                return;
            }
            _originalPackageFile = originalPackageFile;
            BaseDirectory = wrapCacheDirectory;
            // get the descriptor file inside the package

            Source = source;
            var wrapDescriptor = wrapCacheDirectory.Files("*.wrapdesc").SingleOrDefault();

            if (wrapDescriptor == null)
            {
                IsValid = false;
                return;
            }

            var versionFile = wrapCacheDirectory.GetFile("version");
            _descriptor = new PackageDescriptorReader().Read(wrapDescriptor);
            _semver = _descriptor.SemanticVersion ?? _descriptor.Version.ToSemVer();
            if (_semver == null)
                _semver = versionFile.Exists ? versionFile.ReadString().ToSemVer() : null;

            IsValid = string.IsNullOrEmpty(Name) == false && _semver != null;
            if (IsValid)
                Identifier = new PackageIdentifier(Name, _semver);
        }
Example #31
0
 public static FileSystemResult OverwriteFile(this IFile file, Stream readstream, CancellationToken token, IProgress <FileProgress> progress, Dictionary <string, object> properties)
 {
     return(Task.Run(async() => await file.OverwriteFileAsync(readstream, token, progress, properties)).Result);
 }
 protected abstract void OptimizeRefs(IRangeMarker marker, IFile file);
 public PsiContextActionDataProvider([NotNull] ISolution solution, [NotNull] ITextControl textControl, [NotNull] IFile psiFile) : base(solution, textControl, psiFile)
 {
 }
Example #34
0
 public override IFile Merge(IFile main, IFile addition)
 {
     return(MergeInternal((T)main, (T)addition));
 }
Example #35
0
 public override void Import(IFile file, IMod mod, CultureInfo culture)
 {
     ImportInternal((T)file, mod, culture);
 }
Example #36
0
 public FileDataSetEntry(String name, IFile value, String type)
     : base(name, type)
 {
     _value = value;
 }
 public TradeMessageProcessor(IManagerFactory managerFactory, ITradeStore tradeStore, IConsole console, IFile file)
 {
     _managerFactory = managerFactory;
     _tradeStore     = tradeStore;
     _console        = console;
     _file           = file;
 }
Example #38
0
 public async Task <string> ReadFile(IFile f)
 {
     return(await Task.Run(() => f.ReadAllTextAsync()).ConfigureAwait(false));
 }
Example #39
0
 public override void Play(IFile file)
 {
     // for checking
     Console.WriteLine("Play photo file");
 }
Example #40
0
 /// <summary>
 /// </summary>
 /// <param name="file">
 /// </param>
 /// <param name="path">
 /// </param>
 public X509ChainElementCollectionWrap(IFile file,
                                       IPath path)
 {
     this.file = file;
     this.path = path;
 }
        private bool PerformTemplateValidation(SimpleConfigModel templateModel, IFile templateFile, ITemplateEngineHost host)
        {
            //Do some basic checks...
            List <string> errorMessages   = new List <string>();
            List <string> warningMessages = new List <string>();

            if (string.IsNullOrEmpty(templateModel.Identity))
            {
                errorMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "identity", templateFile.FullPath));
            }

            if (string.IsNullOrEmpty(templateModel.Name))
            {
                errorMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "name", templateFile.FullPath));
            }

            if ((templateModel.ShortNameList?.Count ?? 0) == 0)
            {
                errorMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "shortName", templateFile.FullPath));
            }

            if (string.IsNullOrEmpty(templateModel.SourceName))
            {
                warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "sourceName", templateFile.FullPath));
            }

            if (string.IsNullOrEmpty(templateModel.Author))
            {
                warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "author", templateFile.FullPath));
            }

            if (string.IsNullOrEmpty(templateModel.GroupIdentity))
            {
                warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "groupIdentity", templateFile.FullPath));
            }

            if (string.IsNullOrEmpty(templateModel.GeneratorVersions))
            {
                warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "generatorVersions", templateFile.FullPath));
            }

            if (templateModel.Precedence == 0)
            {
                warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "precedence", templateFile.FullPath));
            }

            if ((templateModel.Classifications?.Count ?? 0) == 0)
            {
                warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "classifications", templateFile.FullPath));
            }

            if (templateModel.PostActionModel != null && templateModel.PostActionModel.Any(x => x.ManualInstructionInfo == null || x.ManualInstructionInfo.Count == 0))
            {
                warningMessages.Add(string.Format(LocalizableStrings.Authoring_MalformedPostActionManualInstructions, templateFile.FullPath));
            }

            if (warningMessages.Count > 0)
            {
                host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateMissingCommonInformation, templateFile.FullPath), "Authoring");

                foreach (string message in warningMessages)
                {
                    host.LogDiagnosticMessage("    " + message, "Authoring");
                }
            }

            if (errorMessages.Count > 0)
            {
                host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateNotInstalled, templateFile.FullPath), "Authoring");

                foreach (string message in errorMessages)
                {
                    host.LogDiagnosticMessage("    " + message, "Authoring");
                }

                return(false);
            }

            return(true);
        }
Example #42
0
        private AutosaveOutputFileMover BuildAutosaveFileMover(IFile file)
        {
            var pathUtil = Substitute.For <IPathUtil>();

            return(new AutosaveOutputFileMover(Substitute.For <IDirectory>(), file, pathUtil));
        }
Example #43
0
 public App(IFile file)
 {
     Objects       = new ListOficeObjects <OfficeElement>();
     File          = file;
     File.Elements = Objects;
 }
Example #44
0
 public bool AcceptsFile(IFile file, ITextControl textControl)
 {
     return(file is IT4File && this.MatchTokenType(file, textControl, IsSupportedTokenType));
 }
Example #45
0
        public void Execute()
        {
            var   parser     = new FluentCommandLineParser();
            IFile outputFile = null;

            parser.Setup <string>('o', "output")
            .WithDescription("Output report html file path to be created.")
            .Required()
            .Callback(x => outputFile = FileSystem.ParseFile(x));

            var fileDialog = false;

            parser.Setup <bool>('f', "fileDiaog")
            .WithDescription("Show popup dialog to choose mega SSPG file")
            .Callback(x => fileDialog = x);

            var dirDialog = false;

            parser.Setup <bool>('d', "directoryDiaog")
            .WithDescription("Show popup dialog to choose extracted mega SSPG file")
            .Callback(x => dirDialog = x);

            var openReport = false;

            parser.Setup <bool>('e', "open")
            .WithDescription("Open report after generating")
            .Callback(x => openReport = x);

            IFile mega = null;

            parser.Setup <string>('p', "package")
            .WithDescription("Path to the mega SSPG package file")
            .Callback(x => mega = FileSystem.ParseFile(x));

            var workplaceName = "";

            parser.Setup <string>('n', "name")
            .WithDescription("Workplace name.")
            .Callback(x => workplaceName = x);

            var result = parser.Parse(Options);

            if (result.HelpCalled)
            {
                return;
            }

            var   assemblyName  = Assembly.GetExecutingAssembly().GetName().ToString();
            var   system        = new SystemContext(assemblyName);
            IFile workplaceFile = null;

            SupportPackageDataProvider[] packages = null;
            if (fileDialog)
            {
                var dialog = new OpenFileDialog
                {
                    Filter      = "Mega Support Package|*.zip|Diagnostics Tool Workspace|*.sdt",
                    Multiselect = false,
                };

                IFile file;
                while (true)
                {
                    var dialogResult = dialog.ShowDialog();

                    if (dialogResult == DialogResult.Cancel)
                    {
                        return;
                    }

                    file = FileSystem.ParseFile(dialog.FileName);
                    if (file.Exists)
                    {
                        break;
                    }
                }

                if (file.Extension.Equals(".sdt", StringComparison.OrdinalIgnoreCase))
                {
                    mega          = null;
                    workplaceFile = file;
                }
                else
                {
                    mega = file;
                }
            }
            else if (dirDialog)
            {
                var dialog = new FolderBrowserDialog();

                IDirectory dir;
                while (true)
                {
                    var dialogResult = dialog.ShowDialog();

                    if (dialogResult == DialogResult.Cancel)
                    {
                        return;
                    }

                    dir = FileSystem.ParseDirectory(dialog.SelectedPath);
                    if (dir.Exists)
                    {
                        break;
                    }
                }

                packages = dir.GetDirectories()
                           .ToArray(x =>
                                    new SupportPackageDataProvider(x, null, null));
            }

            if (packages == null)
            {
                if (mega != null)
                {
                    if (!mega.Exists)
                    {
                        Console.WriteLine($"File does not exist: {mega}");

                        return;
                    }

                    packages = PackageHelper.ExtractMegaPackage(mega)
                               .ToArray(x =>
                                        new SupportPackageDataProvider(x, null, null));
                }
            }

            if (packages == null)
            {
                workplaceFile = workplaceFile ?? FileSystem.GetWorkplaceFile(workplaceName);
                if (!workplaceFile.Exists)
                {
                    Program.ShowHelp();
                    return;
                }

                packages = workplaceFile.ReadAllLines()
                           .Select(x => x.Split('?'))
                           .Select(x => new
                {
                    Path  = x[0],
                    Roles = x[1].Split('|')
                            .Select(r => (ServerRole)Enum.Parse(typeof(ServerRole), r))
                            .ToArray()
                })
                           .Select(x =>
                {
                    Console.WriteLine($"Parsing {x.Path}");

                    var file = FileSystem.ParseFile(x.Path);
                    var dir  = FileSystem.ParseDirectory(x.Path);
                    Assert.IsTrue(file.Exists || dir.Exists, "Neither file nor dir exists: " + x.Path);

                    var fileSystemEntry = file.Exists ? (IFileSystemEntry)file : dir;

                    return(new SupportPackageDataProvider(fileSystemEntry, x.Roles, null));
                })
                           .ToArray();
            }

            try
            {
                Console.WriteLine("Running tests...");
                var resultsFile = TestRunner.TestRunner.RunTests(packages, system, (test, index, count) => Console.WriteLine($"Running {test?.Name}..."));

                outputFile.Directory.Create();

                Console.WriteLine("Building report...");

                outputFile.WriteAllText(ReportBuilder.GenerateReport(resultsFile));

                if (openReport)
                {
                    Process.Start("explorer", $"\"{outputFile}\"");
                }
            }
            finally
            {
                foreach (var package in packages)
                {
                    package?.Dispose();
                }
            }
        }
        public bool TryGetTemplateFromConfigInfo(IFileSystemInfo templateFileConfig, out ITemplate template, IFileSystemInfo localeFileConfig = null, IFile hostTemplateConfigFile = null, string baselineName = null)
        {
            IFile templateFile = templateFileConfig as IFile;

            if (templateFile == null)
            {
                template = null;
                return(false);
            }

            IFile localeFile         = localeFileConfig as IFile;
            ITemplateEngineHost host = templateFileConfig.MountPoint.EnvironmentSettings.Host;

            try
            {
                JObject baseSrcObject = ReadJObjectFromIFile(templateFile);
                JObject srcObject     = MergeAdditionalConfiguration(baseSrcObject, templateFileConfig);

                JObject localeSourceObject = null;
                if (localeFile != null)
                {
                    localeSourceObject = ReadJObjectFromIFile(localeFile);
                }

                ISimpleConfigModifiers configModifiers = new SimpleConfigModifiers()
                {
                    BaselineName = baselineName
                };
                SimpleConfigModel templateModel = SimpleConfigModel.FromJObject(templateFile.MountPoint.EnvironmentSettings, srcObject, configModifiers, localeSourceObject);

                if (!PerformTemplateValidation(templateModel, templateFile, host))
                {
                    template = null;
                    return(false);
                }

                if (!CheckGeneratorVersionRequiredByTemplate(templateModel.GeneratorVersions))
                {   // template isn't compatible with this generator version
                    template = null;
                    return(false);
                }

                RunnableProjectTemplate runnableProjectTemplate = new RunnableProjectTemplate(srcObject, this, templateFile, templateModel, null, hostTemplateConfigFile);
                if (!AreAllTemplatePathsValid(templateModel, runnableProjectTemplate))
                {
                    template = null;
                    return(false);
                }

                // Record the timestamp of the template file so we
                // know to reload it if it changes
                if (host.FileSystem is IFileLastWriteTimeSource timeSource)
                {
                    runnableProjectTemplate.ConfigTimestampUtc = timeSource.GetLastWriteTimeUtc(templateFile.FullPath);
                }

                template = runnableProjectTemplate;
                return(true);
            }
            catch (Exception ex)
            {
                host.LogMessage($"Error reading template from file: {templateFile.FullPath} | Error = {ex.Message}");
            }

            template = null;
            return(false);
        }
 /// <summary>
 /// Add a file to the storyboard
 /// </summary>
 /// <param name="fileToAdd"></param>
 public void addFile(IFile fileToAdd, int startTime, int endTime, string type)
 {
     _fileList.Add(new StoryBoardElement(fileToAdd, startTime, endTime, type, fileToAdd.fileName, fileToAdd.fileSize));
 }
Example #48
0
 public PrintingDevice(Job job, PrinterWrapper printer, IFile file, IOsHelper osHelper, ICommandLineUtil commandLineUtil) : base(job, file, osHelper, commandLineUtil)
 {
     _printer = printer;
 }
 public IFileStream(IFile file)
 {
     page      = new byte[Page.pageSize];
     this.file = file;
 }
            public void CompleteTest()
            {
                string rootPath = @"C:\Temp\FileSystems";

                Assert.AreEqual(true, Directory.Exists(rootPath));
                CleanUpFileSystem(rootPath);

                IFileSystem         fileSystem    = new LocalFileSystem(rootPath);
                IFileSystemConstant constants     = fileSystem.WithFileSystemConstant();
                IDirectory          rootDirectory = fileSystem.RootDirectory;

                Assert.AreEqual('\\', constants.DirectorySeparatorChar);

                // Create directory
                IDirectory d1 = rootDirectory.WithDirectoryCreator().Create("D1");

                Assert.AreEqual("D1", d1.Name);
                Assert.AreEqual(Path.Combine(rootPath, "D1"), d1.WithAbsolutePath().AbsolutePath);
                EnsureAncestors(d1.WithAncestorEnumerator(), "FileSystems", "Temp", "C:\\");

                // Rename directory.
                d1.WithDirectoryRenamer().ChangeName("D1.1");
                Assert.AreEqual("D1.1", d1.Name);
                Assert.AreEqual(Path.Combine(rootPath, "D1.1"), d1.WithAbsolutePath().AbsolutePath);
                Assert.AreEqual(false, Directory.Exists(Path.Combine(rootPath, "D1")));
                Assert.AreEqual(true, Directory.Exists(Path.Combine(rootPath, "D1.1")));


                // Create file
                IFile f1 = d1.WithFileCreator().Create("F1", "txt");

                Assert.AreEqual(true, File.Exists(Path.Combine(rootPath, d1.Name, "F1.txt")));
                Assert.AreEqual(Path.Combine(d1.WithAbsolutePath().AbsolutePath, "F1.txt"), f1.WithAbsolutePath().AbsolutePath);
                Assert.AreEqual("F1", f1.Name);
                Assert.AreEqual("txt", f1.Extension);
                Assert.AreEqual(0, f1.WithFileContentSize().FileSize);

                // Write to file
                f1.WithFileContentUpdater().SetContent("Text");
                Assert.AreEqual("Text", File.ReadAllText(f1.WithAbsolutePath().AbsolutePath));

                // Append to file
                f1.WithFileContentAppender().AppendContent(".T1");
                Assert.AreEqual("Text.T1", File.ReadAllText(f1.WithAbsolutePath().AbsolutePath));

                // Override file content
                f1.WithFileContentUpdater().SetContent("T2");
                Assert.AreEqual("T2", File.ReadAllText(f1.WithAbsolutePath().AbsolutePath));

                // Read file content
                Assert.AreEqual("T2", f1.WithFileContentReader().GetContent());
                Assert.AreEqual(2, f1.WithFileContentSize().FileSize);

                // Rename file
                f1.WithFileRenamer().ChangeName("F1.1");
                Assert.AreEqual("F1.1", f1.Name);
                Assert.AreEqual("txt", f1.Extension);
                Assert.AreEqual(Path.Combine(d1.WithAbsolutePath().AbsolutePath, "F1.1.txt"), f1.WithAbsolutePath().AbsolutePath);
                Assert.AreEqual(false, File.Exists(Path.Combine(d1.WithAbsolutePath().AbsolutePath, "F1.txt")));
                Assert.AreEqual(true, File.Exists(Path.Combine(d1.WithAbsolutePath().AbsolutePath, "F1.1.txt")));

                // Enumerate files.
                IFileEnumerator fe1 = d1.WithFileEnumerator();

                Assert.AreEqual(1, fe1.Count());

                // Create files and directories.
                IFile f2 = d1.WithFileCreator().Create("F2", "txt");
                IFile f3 = d1.WithFileCreator().Create("F3", "rtf");
                IFile f4 = d1.WithFileCreator().Create("f4", "rtf");

                IDirectory d12  = d1.WithDirectoryCreator().Create("D2");
                IFile      f121 = d12.WithFileCreator().Create("F1", "txt");
                IFile      f122 = d12.WithFileCreator().Create("F2", "txt");
                IFile      f123 = d12.WithFileCreator().Create("F3", "rtf");
                IFile      f124 = d12.WithFileCreator().Create("f4", "rtf");

                // Enumerate directories.
                IDirectoryEnumerator de1 = d1.WithDirectoryEnumerator();

                Assert.AreEqual(1, de1.Count());

                // Searching directories
                IEnumerable <IDirectory> s1 = rootDirectory.WithDirectoryNameSearch().FindDirectories(TextSearch.CreatePrefixed("D"));

                Assert.AreEqual(1, s1.Count());

                IEnumerable <IDirectory> s2 = rootDirectory.WithDirectoryPathSearch().FindDirectories(TextSearch.CreatePrefixed("D"));

                Assert.AreEqual(2, s2.Count());

                IEnumerable <IDirectory> s3 = rootDirectory.WithDirectoryPathSearch().FindDirectories(TextSearch.CreateSuffixed("2"));

                Assert.AreEqual(1, s3.Count());

                IEnumerable <IDirectory> s4 = rootDirectory.WithDirectoryPathSearch().FindDirectories(TextSearch.CreateEmpty());

                Assert.AreEqual(2, s4.Count());

                // Searching files
                IEnumerable <IFile> s5 = rootDirectory.WithFileNameSearch().FindFiles(TextSearch.CreatePrefixed("f1"), TextSearch.CreateEmpty());

                Assert.AreEqual(0, s5.Count());

                IEnumerable <IFile> s6 = d1.WithFileNameSearch().FindFiles(TextSearch.CreatePrefixed("f1"), TextSearch.CreateEmpty());

                Assert.AreEqual(1, s6.Count());

                IEnumerable <IFile> s7 = d1.WithFileNameSearch().FindFiles(TextSearch.CreateEmpty(), TextSearch.CreateMatched("txt"));

                Assert.AreEqual(2, s7.Count());

                IEnumerable <IFile> s8 = d1.WithFileNameSearch().FindFiles(TextSearch.CreateContained("f"), TextSearch.CreateEmpty());

                Assert.AreEqual(4, s8.Count());

                IEnumerable <IFile> s9 = rootDirectory.WithFilePathSearch().FindFiles(TextSearch.CreateSuffixed("2"), TextSearch.CreateEmpty());

                Assert.AreEqual(2, s9.Count());


                // Delete file
                f1.WithFileDeleter().Delete();

                //Delete directory
                d1.WithDirectoryDeleter().Delete();
                Assert.AreEqual(false, Directory.Exists(Path.Combine(rootPath, "T1")));
            }
        public bool TryCreateTextFile(string Path, string Content, FileCreationPermission CreationPermission, out IFile Result)
        {
            IFile file = this.GetFile(Path);

            if (file.Exists && CreationPermission == FileCreationPermission.AllowOverwrite)
            {
                file.Delete();
            }

            if (!this.TryCreateFile(Path, out Result))
            {
                return(false);
            }

            try {
                using (TextWriter writer = Result.GetTextWriter()) {
                    writer.Write(Content);
                    writer.Flush();
                }
            }
            catch (Exception) {
                return(false);
            }

            return(true);
        }
 public CurrentFileEntry(string fileName, IFile fileStream)
 {
     FileName    = fileName;
     CurrentFile = fileStream;
 }
 static FileSystem()
 {
     _file      = new FileProvider();
     _directory = new DirectoryProvider();
 }
Example #54
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage == "")
            {
                return(GetMessage(501, string.Format("{0} needs a parameter", Command)));
            }

            string sFile = GetPath(sMessage);

            if (!FileNameHelpers.IsValid(sFile) || sFile.EndsWith(@"/"))
            {
                return(GetMessage(553, string.Format("\"{0}\" is not a valid file name", sMessage)));
            }

            if (ConnectionObject.FileSystemObject.FileExists(sFile))
            {
                return(GetMessage(553, string.Format("File \"{0}\" already exists.", sMessage)));
            }

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            IFile file = ConnectionObject.FileSystemObject.OpenFile(sFile, true);

            if (file == null)
            {
                socketData.Close();// close data socket
                return(GetMessage(550, "Couldn't open file"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, GetMessage(150, "Opening connection for data transfer."), ConnectionObject.Encoding);

            string md5Value = string.Empty;

            // TYPE I, default
            if (ConnectionObject.DataType == DataType.Image)
            {
                // md5 hash function
                MD5 md5Hash = MD5.Create();

                var abData = new byte[m_nBufferSize];

                int nReceived = socketData.Receive(abData);

                while (nReceived > 0)
                {
                    int writeSize = file.Write(abData, nReceived);
                    // maybe error
                    if (writeSize != nReceived)
                    {
                        file.Close();
                        socketData.Close();
                        return(GetMessage(451, "Write data to Azure error!"));
                    }
                    md5Hash.TransformBlock(abData, 0, nReceived, null, 0);
                    nReceived = socketData.Receive(abData);
                }
                md5Hash.TransformFinalBlock(new byte[1], 0, 0);
                md5Value = BytesToStr(md5Hash.Hash);
            }
            // TYPE A
            // won't compute md5, because read characters from client stream
            else if (ConnectionObject.DataType == DataType.Ascii)
            {
                int readSize = SocketHelpers.CopyStreamAscii(socketData.Socket.GetStream(), file.BlobStream, m_nBufferSize);
                FtpServerMessageHandler.SendMessage(ConnectionObject.Id, string.Format("Use ascii type success, read {0} chars!", readSize));
            }
            else   // mustn't reach
            {
                file.Close();
                socketData.Close();
                return(GetMessage(451, "Error in transfer data: invalid data type."));
            }

            // upload notification
            ConnectionObject.FileSystemObject.Log4Upload(sFile);

            file.Close();
            socketData.Close();

            // record md5
            ConnectionObject.FileSystemObject.SetFileMd5(sFile, md5Value);

            return(GetMessage(226, string.Format("{0} successful", Command)));
        }
Example #55
0
 public bool AddFile(IFile file)
 {
     filesList.Add(file);
     return(true);
 }
Example #56
0
 public ITextStampAdder(IFile file)
 {
     _fontPathHelper = new FontPathHelper(file);
 }
Example #57
0
 public static FileSystemResult <Stream> OpenRead(this IFile file)
 {
     return(Task.Run(async() => await file.OpenReadAsync()).Result);
 }
Example #58
0
 public bool RemoveFile(IFile file)
 {
     return(filesList.Remove(file));
 }
 internal SpriteManager(IImageProcessor imageProcessor, ICssProcessor cssProcessor, IFile file, IMagickImageHelper magickImageHelper)
 {
     _imageProcessor = imageProcessor;
     _cssProcessor = cssProcessor;
     _file = file;
     _magickImageHelper = magickImageHelper;
 }
Example #60
0
        public IAppender CreateAppender(string appenderType, ILayout layout, Level level, IFile file = null)
        {
            IAppender appender;

            if (appenderType == "ConsoleAppender")
            {
                appender = new ConsoleAppender(layout, level);
            }
            else if (appenderType == "FileAppender" && file != null)
            {
                appender = new FileAppender(layout, level, file);
            }
            else
            {
                throw new InvalidOperationException
                          (GlobalConstants.InvalidAppenderType);
            }

            return(appender);
        }