Example #1
0
        public async Task WriteAsync(Post post, PostConfig config)
        {
            Logger.Info($"Escrevendo o post {post.Title}...");
            Sanitize(post);

            var content  = GetPostContent(post, config);
            var postName = GetPostName(post);
            var date     = config.Date ?? post.Date;

            Logger.Debug($"Criando a pasta do post...");
            var postFolder = Path.Combine(_jekyllRootFolder, "_posts", date.Year.ToString());

            _fs.CreateDirectory(postFolder);

            Logger.Debug($"Escrevendo o arquivo do post...");
            var postFileName = Path.Combine(postFolder, $"{date.Year}-{date.Month:00}-{date.Day:00}-{postName}.md");

            _fs.WriteFile(postFileName, content);

            Logger.Debug($"Criando a pasta de imagens do post....");
            var imagesFolder = Path.Combine(_jekyllRootFolder, "assets", date.Year.ToString(), date.Month.ToString("00"), date.Day.ToString("00"), postName);

            _fs.CreateDirectory(imagesFolder);

            Logger.Debug($"Realizando o download das imagens e gravando na pasta...");
            foreach (var screenshot in post.Screenshots)
            {
                Logger.Debug($"Screenshot {screenshot}");
                var image = await _web.DownloadImageAsync(screenshot);

                if (image.Data.Length >= config.IgnoreImagesLowerThanBytes)
                {
                    var fileName = Path.Combine(imagesFolder, $"{Path.GetFileNameWithoutExtension(screenshot)}{image.Extension}");

                    Logger.Debug($"Gravando screenshot {fileName}...");
                    _fs.WriteFile(fileName, image.Data);
                }
                else
                {
                    Logger.Warn("Não será gravada, pois é menor que o tamanho mínimo esperado.");
                }
            }

            // Grava o logo.
            if (!String.IsNullOrEmpty(post.Logo))
            {
                var image = await _web.DownloadImageAsync(post.Logo);

                var fileName = Path.Combine(imagesFolder, $"logo{image.Extension}");

                Logger.Debug($"Gravando logo {fileName}...");
                _fs.WriteFile(fileName, image.Data);
            }
        }
Example #2
0
        public void Apply(string script, string settings, bool testOnly = false)
        {
            if (settings != null && !_fileSystem.FileExist(settings))
            {
                _console.Error("Unable to find settings file {file}", settings);
                return;
            }

            if (!Validate(script))
            {
                return;
            }

            try
            {
                _gatherManager.Run();
            }
            catch (Exception e)
            {
                _console.Error("There was an error while running gathers! Error: {error}", e);
                return;
            }

            try
            {
                var settingData = settings == null
                    ? null
                    : JsonConvert.DeserializeObject <Dictionary <string, string> >(_fileSystem.ReadFile(settings));

                var runlist = _configManager.BuildRunList(settingData);
                var results = testOnly ? _configManager.Test(runlist).ToArray() : _configManager.ApplyRunList(runlist).ToArray();

                if (results.Any(r => r.State == ResourceState.NotConfigured))
                {
                    _environmentHelper.SetExitCode(ExitCodes.Error);
                }
                else if (results.Any(r => r.State == ResourceState.NeedReboot))
                {
                    _environmentHelper.SetExitCode(ExitCodes.Reboot);
                }
                else
                {
                    _environmentHelper.SetExitCode(ExitCodes.Ok);
                }

                _fileSystem.WriteFile("data.json", _dataStore.GetPersistString());
                _fileSystem.WriteFile("result.json", JsonConvert.SerializeObject(results));
            }
            catch (Exception e)
            {
                _console.Error("There was an error while trying to read {file} Error: {error}", settings, e);
            }
        }
Example #3
0
        public async Task Commit()
        {
            await _pending.ForEach(async (aggregateType, aggregateID, events) =>
            {
                var aggregatePath = AggregatePath(_root, aggregateType, aggregateID);
                var lines         = events
                                    .Select(e => JsonConvert.SerializeObject(e, JsonSerializerSettings))
                                    .ToArray();

                await _fileSystem.AppendFileLines(aggregatePath, lines);
            });


            var eventsForProjection = _pending.AllEvents.ToArray();

            foreach (var projection in _projections)
            {
                foreach (var @event in eventsForProjection)
                {
                    projection.Apply(@event);

                    var projectionPath = Path.Combine(_root, projection.For.Name + ".json");
                    var projectionJson = JsonConvert.SerializeObject(projection.ToMemento(), Formatting.Indented, JsonSerializerSettings);

                    await _fileSystem.WriteFile(projectionPath, async stream =>
                    {
                        using (var writer = new StreamWriter(stream))
                            await writer.WriteAsync(projectionJson);
                    });
                }
            }

            _pending.Clear();
        }
Example #4
0
 /// <summary>
 /// Opens a file on the file system for writing.
 /// </summary>
 /// <param name="fileSystem">Virtual file system</param>
 /// <param name="path">Path to the file stored in the virtual file system</param>
 /// <param name="cancellation">Cancellation token</param>
 /// <returns>Stream that should be used to write to a file.</returns>
 protected virtual Task <Stream> OpenFile(
     IFileSystem fileSystem,
     VirtualPath path,
     CancellationToken cancellation)
 {
     return(fileSystem.WriteFile(path, cancellation));
 }
Example #5
0
        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (!IsValid)
            {
                return;
            }

            var imported = new List <string>();

            using (var zip = new ZipInputStream(fupImport.FileContent))
            {
                for (var entry = zip.GetNextEntry(); entry != null; entry = zip.GetNextEntry())
                {
                    if (entry.IsDirectory)
                    {
                        continue;
                    }
                    var path = rootPath + '/' + entry.FileName;
                    fileSystem.WriteFile(path, zip);
                    imported.Add(path);
                }
            }

            rptImportedFiles.DataSource = imported;
            rptImportedFiles.DataBind();

            mvwImport.ActiveViewIndex = 1;

            Refresh(Selection.SelectedItem, ToolbarArea.Navigation);
        }
        // write summary log file
        private void WriteLog(ReplicationJournal journal)
        {
            var log = journal.ToString();

            using (var ms = new MemoryStream())
                using (var sw = new StreamWriter(ms))
                {
                    sw.Write(log);
                    sw.Flush();
                    ms.Position = 0;

                    var name = String.Format("{0}.{1}.{2}.log",
                                             SerializationUtility.GetLocalhostFqdn(),
                                             (IsMaster) ? "M" : "S",
                                             DateTime.UtcNow.ToString("yyMMdd_HHmmss"));
                    try
                    {
                        if (journal.AffectedCount > 0)
                        {
                            _fileSystem.WriteFile(Path.Combine(_replicationLogPath, name), ms);
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.Error("Could not write remote blog file " + e.Message);
                        _logger.Info(log);
                    }
                }
        }
Example #7
0
        internal static void Copy(this IFileSystem fileSystem, string source, string destination)
        {
            // if copying a file
            if (File.Exists(source))
            {
                fileSystem.WriteFile(destination, File.ReadAllText(source));
                return;
            }

            // if copying a directory
            if (fileSystem.DirectoryExists(destination))
            {
                fileSystem.DeleteDirectory(destination);
            }
            fileSystem.CreateDirectory(destination);

            // Copy dirs recursively
            foreach (var child in Directory.GetDirectories(Path.GetFullPath(source), "*", SearchOption.TopDirectoryOnly).Select(p => Path.GetDirectoryName(p)))
            {
                fileSystem.Copy(Path.Combine(source, child), Path.Combine(destination, child));
            }
            // Copy files
            foreach (var childFile in Directory.GetFiles(Path.GetFullPath(source), "*", SearchOption.TopDirectoryOnly).Select(p => Path.GetFileName(p)))
            {
                fileSystem.Copy(Path.Combine(source, childFile),
                                Path.Combine(destination, childFile));
            }
        }
        public override bool UpdateItem(ContentItem item, Control editor)
        {
            SelectingUploadCompositeControl composite = (SelectingUploadCompositeControl)editor;

            HttpPostedFile postedFile = composite.UploadControl.PostedFile;

            if (postedFile != null && !string.IsNullOrEmpty(postedFile.FileName))
            {
                IFileSystem fs            = Engine.Resolve <IFileSystem>();
                string      directoryPath = Engine.Resolve <IDefaultDirectory>().GetDefaultDirectory(item);
                if (!fs.DirectoryExists(directoryPath))
                {
                    fs.CreateDirectory(directoryPath);
                }

                string fileName = Path.GetFileName(postedFile.FileName);
                fileName = Regex.Replace(fileName, InvalidCharactersExpression, "-");
                string filePath = VirtualPathUtility.Combine(directoryPath, fileName);

                fs.WriteFile(filePath, postedFile.InputStream);

                item[Name] = Url.ToAbsolute(filePath);
                return(true);
            }

            if (composite.SelectorControl.Url != item[Name] as string)
            {
                item[Name] = composite.SelectorControl.Url;
                return(true);
            }

            return(false);
        }
Example #9
0
        private void CreateNamespaceVariables(string projectName, List <IModelData> models)
        {
            // get content of mainCallbacks.c file
            var mainCallbacksFilePath = _fileSystem.CombinePaths(projectName, Constants.DirectoryName.SourceCode, Constants.DirectoryName.ServerApp, Constants.FileName.SourceCode_mainCallbacks_c);

            var mainCallbacksFileContent = new List <string>();

            using (var constantsFileStream = _fileSystem.ReadFile(mainCallbacksFilePath))
            {
                // convert file stream to list of strings
                using (var reader = new StreamReader(constantsFileStream))
                {
                    while (!reader.EndOfStream)
                    {
                        mainCallbacksFileContent.Add(reader.ReadLine());
                    }
                }

                // add namespace variables to content of mainCallbacks.c file
                AddNamespaceVariablesToMainCallbacksFileContent(models, ref mainCallbacksFileContent);
            }

            // write mainCallbacks.c content back to the file
            _fileSystem.WriteFile(mainCallbacksFilePath, mainCallbacksFileContent);
        }
        private void CopyFilesInDirectoryRecursively(string dirPath)
        {
            var files = System.IO.Directory.GetFiles(dirPath);

            foreach (var file in files)
            {
                var relativeFile = FullToRelative(file);

                if (fs.FileExists(relativeFile))
                {
                    continue;
                }

                returnValue += "<br />" + relativeFile;
                using (var fileStream = System.IO.File.OpenRead(file))
                {
                    fs.WriteFile(relativeFile, fileStream);
                    fileStream.Close();
                }
            }

            var subdirs = System.IO.Directory.GetDirectories(dirPath);

            foreach (var subdir in subdirs)
            {
                var relativeDir = FullToRelative(subdir);
                if (!fs.DirectoryExists(relativeDir))
                {
                    returnValue += "<br />" + relativeDir;
                    fs.CreateDirectory(relativeDir);
                }
                CopyFilesInDirectoryRecursively(subdir);
            }
        }
Example #11
0
        private bool UpdateAppioProjFile(string appioprojFilePath, ModelData modelData,
                                         string opcuaAppName, string modelFileName, string modelPath, string typesFileName)
        {
            // deserialize appioproj file
            if (!DeserializeAppioprojFile(appioprojFilePath, out var opcuaappData))
            {
                return(false);
            }

            // build model data
            var opcuaappDataAsServer = opcuaappData as IOpcuaServerApp;

            if (!BuildModelData(ref modelData, opcuaappDataAsServer, opcuaAppName, modelFileName, modelPath, typesFileName))
            {
                return(false);
            }

            // add model to project structure, serialize structure and write to appioproj file
            opcuaappDataAsServer.Models.Add(modelData);
            var appioprojNewContent = JsonConvert.SerializeObject(opcuaappData, Newtonsoft.Json.Formatting.Indented);

            _fileSystem.WriteFile(appioprojFilePath, new List <string> {
                appioprojNewContent
            });
            return(true);
        }
Example #12
0
        /* InstallMollenOS
         * Installs mollenos on to the given filesystem and prepares
         * the proper boot-sectors for the partition */
        static void InstallMollenOS(IFileSystem FileSystem)
        {
            // Make the given filesystem boot
            if (!FileSystem.MakeBoot())
            {
                Console.WriteLine("Failed to make the partition primary boot");
                return;
            }

            // Iterate through and create all directories
            String BaseRoot = "deploy/hdd/";

            Console.WriteLine("Creating system file tree");
            Console.WriteLine("Root: " + System.IO.Directory.GetCurrentDirectory() + "/deploy/hdd/");
            String[] Dirs = Directory.GetDirectories("deploy/hdd/", "*", SearchOption.AllDirectories);

            foreach (String pDir in Dirs)
            {
                String RelPath     = pDir.Substring(BaseRoot.Length).Replace('\\', '/');
                String DirToCreate = pDir.Split(Path.DirectorySeparatorChar).Last();
                Console.WriteLine("Creating: " + RelPath + "  (" + DirToCreate + ")");

                // Create the directory
                if (!FileSystem.WriteFile(RelPath, FileFlags.Directory | FileFlags.System, null))
                {
                    Console.WriteLine("Failed to create directory: " + DirToCreate);
                    return;
                }
            }

            // Iterate through deployment folder and install system files
            Console.WriteLine("Copying system files");
            String[] Files = Directory.GetFiles("deploy/hdd/", "*", SearchOption.AllDirectories);

            foreach (String pFile in Files)
            {
                String RelPath = pFile.Substring(BaseRoot.Length).Replace('\\', '/');
                Console.WriteLine("Copying: " + RelPath);

                // Create the file
                if (!FileSystem.WriteFile(RelPath, FileFlags.System, File.ReadAllBytes(pFile)))
                {
                    Console.WriteLine("Failed to install file: " + RelPath);
                    return;
                }
            }
        }
Example #13
0
        protected void save_Click(object sender, EventArgs e)
        {
            Page.Validate();
            cvAuthenticated.IsValid = IsAuthorized(Page.User);
            if (!Page.IsValid)
            {
                return;
            }

            Items.Addon addon = CurrentItem as Items.Addon;
            if (addon == null)
            {
                addon = Engine.Resolve <ContentActivator>().CreateInstance <Items.Addon>(CurrentPage);
                addon.AuthorUserName = Page.User.Identity.Name;
            }
            else if (!IsAuthor(Page.User, addon))
            {
                cvAuthenticated.IsValid = false;
                return;
            }

            addon.Title = Encode(txtTitle.Text);
            addon.Name  = Engine.Resolve <HtmlFilter>().CleanUrl(txtTitle.Text);

            addon.Text              = Encode(txtDescription.Text);
            addon.AddonVersion      = Encode(txtVersion.Text);
            addon.Category          = (Items.CodeCategory)AssembleSelected(cblCategory.Items);
            addon.ContactEmail      = Encode(txtEmail.Text);
            addon.ContactName       = Encode(txtName.Text);
            addon.HomepageUrl       = Encode(txtHomepage.Text);
            addon.LastTestedVersion = Encode(txtN2Version.Text);
            addon.Requirements      = (Items.Requirement)AssembleSelected(cblRequirements.Items);
            addon.SourceCodeUrl     = Encode(txtSource.Text);
            addon.Summary           = Encode(txtSummary.Text);
            if (fuAddon.PostedFile.ContentLength > 0)
            {
                IFileSystem fs = Engine.Resolve <IFileSystem>();

                if (!string.IsNullOrEmpty(addon.UploadedFileUrl))
                {
                    if (File.Exists(addon.UploadedFileUrl))
                    {
                        File.Delete(addon.UploadedFileUrl);
                    }
                }
                string fileName = Path.GetFileName(fuAddon.PostedFile.FileName);
                Url    folder   = Url.Parse(Engine.EditManager.UploadFolders[0]).AppendSegment("Addons");
                if (!fs.DirectoryExists(folder))
                {
                    fs.CreateDirectory(folder);
                }

                addon.UploadedFileUrl = folder.AppendSegment(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
                fs.WriteFile(addon.UploadedFileUrl, fuAddon.PostedFile.InputStream);
            }

            Engine.Persister.Save(addon);
            Response.Redirect(addon.Url);
        }
        public static int WriteFile(UIntPtr hFile, byte[] buffer, uint bytesToWrite, uint offset, out uint numberBytesWritten)
        {
            GCHandle hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            int      ret     = m_fileSystemIo.WriteFile(hFile, (UIntPtr)((uint)hBuffer.AddrOfPinnedObject() + offset), bytesToWrite, out numberBytesWritten);

            hBuffer.Free();
            return(ret);
        }
Example #15
0
        public void CopyFile(string vfsSrcPath, IFileSystem destFileSystem, string vfsDestPath, bool willOverwrite = false)
        {
            EnsureNotOverwrite(vfsDestPath, willOverwrite);

            using (var srcFileStream = OpenFile(vfsSrcPath, FileMode.Open, FileAccess.Read, FileShare.Read, 10 * 1024))
            {
                destFileSystem.WriteFile(vfsDestPath, srcFileStream);
            }
        }
        public static void WriteFile([NotNull] this IFileSystem fileSystem, [NotNull] string fileName, [NotNull] string content)
        {
            var memoryStream = new MemoryStream();
            var writer       = new StreamWriter(memoryStream);

            writer.WriteAsync(content).GetAwaiter().GetResult();
            writer.FlushAsync().GetAwaiter().GetResult();
            memoryStream.Seek(0, SeekOrigin.Begin);
            fileSystem.WriteFile(fileName, memoryStream);
        }
Example #17
0
        // Adding header file include to server's meson build
        private void AdjustServerMesonBuildCFile(string srcDirectory, string fileNameToInclude)
        {
            var sourceFileSnippet = string.Format(Constants.InformationModelsName.FileSnippet, fileNameToInclude);

            using (var modelsFileStream = _fileSystem.ReadFile(_fileSystem.CombinePaths(srcDirectory, Constants.FileName.SourceCode_meson_build)))
            {
                var currentFileContentLineByLine = ParseStreamToListOfString(modelsFileStream);

                if (!currentFileContentLineByLine.Any(x => x.Contains(sourceFileSnippet)))
                {
                    var lastFunctionLinePosition = currentFileContentLineByLine.FindIndex(x => x.Contains("]"));
                    if (lastFunctionLinePosition != -1)
                    {
                        currentFileContentLineByLine.Insert(lastFunctionLinePosition, sourceFileSnippet);
                    }
                    _fileSystem.WriteFile(_fileSystem.CombinePaths(srcDirectory, Constants.FileName.SourceCode_meson_build), currentFileContentLineByLine);
                }
            }
        }
Example #18
0
        private void SetServerHostnameAndPort(string projectName)
        {
            var appioprojFilePath = _fileSystem.CombinePaths(projectName, projectName + Constants.FileExtension.Appioproject);

            var appioprojOpcuaapp = SlnUtility.DeserializeFile <OpcuaServerApp>(appioprojFilePath, _fileSystem);

            if (appioprojOpcuaapp != null && (appioprojOpcuaapp.Type == Constants.ApplicationType.Server || appioprojOpcuaapp.Type == Constants.ApplicationType.ClientServer))
            {
                var serverConstantsFilePath = _fileSystem.CombinePaths(projectName, Constants.DirectoryName.SourceCode, Constants.DirectoryName.ServerApp, Constants.FileName.SourceCode_constants_h);

                var constantsFileContent = new List <string>();
                using (var constantsFileStream = _fileSystem.ReadFile(serverConstantsFilePath))
                {
                    var reader = new StreamReader(constantsFileStream);
                    while (!reader.EndOfStream)
                    {
                        constantsFileContent.Add(reader.ReadLine());
                    }
                    reader.Dispose();

                    var hostnameLineIndex = constantsFileContent.FindIndex(x => x.Contains(Constants.ServerConstants.ServerAppHostname));
                    if (hostnameLineIndex != -1)
                    {
                        constantsFileContent.RemoveAt(hostnameLineIndex);
                    }

                    var portLineIndex = constantsFileContent.FindIndex(x => x.Contains(Constants.ServerConstants.ServerAppPort));
                    if (portLineIndex != -1)
                    {
                        constantsFileContent.RemoveAt(portLineIndex);
                    }

                    var hostName = new StringBuilder(Constants.ServerConstants.ServerAppHostname).Append(" = \"").Append(appioprojOpcuaapp.Url).Append("\";").ToString();
                    constantsFileContent.Add(hostName);

                    var portNumber = new StringBuilder(Constants.ServerConstants.ServerAppPort).Append(" = ").Append(appioprojOpcuaapp.Port).Append(";").ToString();
                    constantsFileContent.Add(portNumber);
                }
                _fileSystem.WriteFile(serverConstantsFilePath, constantsFileContent);
            }
        }
Example #19
0
        public static string SaveTextFileContents(IFileSystem fs, string filePath, string text)
        {
            // write the content to the file
            fs.WriteFile(filePath, new MemoryStream(Encoding.UTF8.GetBytes(text)));

            // return the public URL
            string publicUrl = null;
            var webAccessible = fs as IWebAccessible;
            if (webAccessible != null)
                publicUrl = webAccessible.GetPublicURL(filePath);
            return publicUrl;
        }
Example #20
0
 public static void CopyFilesRecursively(DirectoryInfo source, string targetVirtualPath, IFileSystem fs)
 {
     foreach (DirectoryInfo dir in source.GetDirectories())
     {
         string newDirVirtualPath = Path.Combine(targetVirtualPath, dir.Name);
         fs.CreateDirectory(newDirVirtualPath);
         CopyFilesRecursively(dir, newDirVirtualPath, fs);
     }
     foreach (FileInfo file in source.GetFiles())
     {
         fs.WriteFile(Path.Combine(targetVirtualPath, file.Name), file.OpenRead());
     }
 }
Example #21
0
 public static void CopyFilesRecursively(DirectoryInfo source, string targetVirtualPath, IFileSystem fs)
 {
     foreach (DirectoryInfo dir in source.GetDirectories())
     {
         string newDirVirtualPath = Path.Combine(targetVirtualPath, dir.Name);
         fs.CreateDirectory(newDirVirtualPath);
         CopyFilesRecursively(dir, newDirVirtualPath, fs);
     }
     foreach (FileInfo file in source.GetFiles())
     {
         fs.WriteFile(Path.Combine(targetVirtualPath, file.Name), file.OpenRead());
     }
 }
        // Upload entire file
        private IEnumerable <FilesStatus> UploadWholeFile(HttpContext context, IFileSystem fs, SelectionUtility selection)
        {
            for (int i = 0; i < context.Request.Files.Count; i++)
            {
                var file        = context.Request.Files[i];
                var fileName    = Path.GetFileName(file.FileName);
                var virtualPath = Url.Combine(((IFileSystemNode)selection.SelectedItem).LocalUrl, fileName);

                fs.WriteFile(virtualPath, file.InputStream);

                yield return(new FilesStatus(virtualPath, file.ContentLength));
            }
        }
Example #23
0
        // Upload entire file
        private IEnumerable<FilesStatus> UploadWholeFile(HttpContext context, IFileSystem fs, SelectionUtility selection)
        {
            for (int i = 0; i < context.Request.Files.Count; i++)
            {
                var file = context.Request.Files[i];
                var fileName = Path.GetFileName(file.FileName);
                var virtualPath = Url.Combine(((IFileSystemNode)selection.SelectedItem).LocalUrl, fileName);

                fs.WriteFile(virtualPath, file.InputStream);

                yield return new FilesStatus(virtualPath, file.ContentLength);
            }
        }
        public override bool UpdateItem(ContentItem item, Control editor)
        {
            SelectingUploadCompositeControl composite = (SelectingUploadCompositeControl)editor;

            HttpPostedFile postedFile = composite.UploadControl.PostedFile;

            if (postedFile != null && !string.IsNullOrEmpty(postedFile.FileName))
            {
                IFileSystem fs = Engine.Resolve <IFileSystem>();

                string directoryPath;
                if (uploadDirectory == string.Empty)
                {
                    directoryPath = Engine.Resolve <IDefaultDirectory>().GetDefaultDirectory(item);
                }
                else
                {
                    directoryPath = uploadDirectory;
                }


                if (!fs.DirectoryExists(directoryPath))
                {
                    fs.CreateDirectory(directoryPath);
                }

                string fileName = Path.GetFileName(postedFile.FileName);
                fileName = Regex.Replace(fileName, InvalidCharactersExpression, "-");
                string filePath = VirtualPathUtility.Combine(directoryPath, fileName);

                if (Engine.Config.Sections.Management.UploadFolders.IsTrusted(fileName))
                {
                    fs.WriteFile(filePath, postedFile.InputStream);
                }
                else
                {
                    throw new Security.PermissionDeniedException("Invalid file name");
                }

                item[Name] = Url.ToAbsolute(filePath);
                return(true);
            }

            if (composite.SelectorControl.Url != item[Name] as string)
            {
                item[Name] = composite.SelectorControl.Url;
                return(true);
            }

            return(false);
        }
        public void Replace(string file)
        {
            if (FileShouldHaveTokensReplaced(file))
            {
                string filedata = _fileSystem.ReadFile(file);

                foreach (var pair in _dictionary)
                {
                    filedata = TokenInserter.WordReplace(filedata, pair.Key, pair.Value);
                }

                _fileSystem.WriteFile(file, filedata);
            }
        }
Example #26
0
 private void saveFileHandler(object sender, EventArgs e)
 {
     try
     {
         _FS.Content = _formUI.TextContent;
         if (!_FS.WriteFile(_formUI.FilePath))
         {
             throw new Exception("Файл не записан");
         }
     }
     catch (Exception er)
     {
         Console.WriteLine(er.Message);
     }
 }
        public void Import(IFileSystem fs, Attachment a)
        {
            if (a.HasContents)
            {
                string path = a.Url;

                if(!fs.DirectoryExists(Path.GetDirectoryName(path)))
                {
                    fs.CreateDirectory(Path.GetDirectoryName(path));
                }

                var memoryStream = new MemoryStream(a.FileContents);
                fs.WriteFile(path, memoryStream);
            }
        }
Example #28
0
        public static string SaveTextFileContents(IFileSystem fs, string filePath, string text)
        {
            // write the content to the file
            fs.WriteFile(filePath, new MemoryStream(Encoding.UTF8.GetBytes(text)));

            // return the public URL
            string publicUrl     = null;
            var    webAccessible = fs as IWebAccessible;

            if (webAccessible != null)
            {
                publicUrl = webAccessible.GetPublicURL(filePath);
            }
            return(publicUrl);
        }
        public void Import(IFileSystem fs, Attachment a)
        {
            if (a.HasContents)
            {
                string path = a.Url;

                if (!fs.DirectoryExists(Path.GetDirectoryName(path)))
                {
                    fs.CreateDirectory(Path.GetDirectoryName(path));
                }

                var memoryStream = new MemoryStream(a.FileContents);
                fs.WriteFile(path, memoryStream);
            }
        }
Example #30
0
            public void Execute(string path)
            {
                try
                {
                    path = Path.GetFullPath(path);

                    using (_console.CreateScope("Generating table of contents..."))
                    {
                        var updatedFilesCounter = 0;
                        var elementParser       = new DocsElementParser();
                        var headerParser        = new HeaderParser();
                        var files = new MarkdownFileLocator(_fileSystem).GetFiles(path);

                        foreach (var file in files)
                        {
                            var lines = _fileSystem.ReadFile(file.FullPath);
                            var toc   = elementParser.Parse(lines, "toc").SingleOrDefault();

                            if (toc == null)
                            {
                                continue;
                            }

                            updatedFilesCounter++;
                            _console.WriteInfo($"Updating {file.RelativePath}");

                            var headers = headerParser.Parse(lines.Skip(toc.ElementLine));

                            lines.RemoveRange(toc.ElementLine, toc.ElementLines);

                            var minLevel = headers.Min(x => x.Level);
                            headers.ForEach(x => x.Level -= minLevel);
                            var formatter  = new LinkFormatter();
                            var tocContent = headers.Select(x =>
                                                            $"{Enumerable.Repeat("  ", x.Level).Join()}* {formatter.Format(x.Text)}");
                            lines.InsertRange(toc.ElementLine, new DocsElementWriter().Write(toc, tocContent));

                            _fileSystem.WriteFile(file.FullPath, lines);
                        }

                        _console.WriteInfo($"Updated {updatedFilesCounter} {(updatedFilesCounter == 1 ? "file" : "files")}.");
                    }
                }
                catch (Exception exception)
                {
                    _console.WriteError(exception.Message);
                }
            }
Example #31
0
 public void SaveFiles(List <IFormFile> files)
 {
     foreach (var file in files)
     {
         if (file.Length > 0)
         {
             using (Stream uploadedFileStream = file.OpenReadStream())
             {
                 byte[] buffer = new byte[uploadedFileStream.Length];
                 uploadedFileStream.Read(buffer, 0, buffer.Length);
                 string name = CreateFileName(file.FileName);
                 _fileSystem.WriteFile($"{UploadsFolder}\\{name}", buffer);
             }
         }
     }
 }
        public async Task <MediaDto> Create(Stream input, string fileName, string contentType)
        {
            using var memoryStream = new MemoryStream();
            await input.CopyToAsync(memoryStream);

            memoryStream.Position = 0;
            var hash = HashHelper.CreateSha256(memoryStream);

            memoryStream.Position = 0;
            var actualFileName = StringHelper.CreateRandom(32);
            var path           = Path.Combine(_options.BasePath, actualFileName);
            await _fileSystem.WriteFile(path, memoryStream, true);

            memoryStream.Position = 0;
            var media = new MediaEntity(fileName, actualFileName, hash, actualFileName, contentType, memoryStream.Length);

            return(ObjectMapper.Map <MediaEntity, MediaDto>(await _repository.InsertAsync(media)));
        }
Example #33
0
        public void Invoke(IOutput output, IFileSystem fileSystem)
        {
            Context context = new Context();

            foreach (var func in _funcs)
            {
                var operation = func(context);

                if (operation is WriteTextOperation)
                {
                    WriteTextOperation writeTextOperation = (WriteTextOperation)operation;
                    output.WriteText(writeTextOperation.Text);
                }
                else if (operation is ContinueIfOperation)
                {
                    var ifOperation = (ContinueIfOperation)operation;
                    if (!ifOperation.IfFunc(context))
                    {
                        break;
                    }
                }
                else if (operation is IfThenElseOperation)
                {
                    var ifThenOperation = (IfThenElseOperation)operation;
                    if (ifThenOperation.IfFunc(context))
                    {
                        ifThenOperation.TrueCommand.Invoke(output, fileSystem);
                    }
                    else
                    {
                        ifThenOperation.FalseCommand?.Invoke(output, fileSystem);
                    }
                }
                else if (operation is WriteFilesOperation)
                {
                    var writeFilesOperation = (WriteFilesOperation)operation;
                    foreach (var fileDef in writeFilesOperation.FileDefs)
                    {
                        fileSystem.WriteFile(fileDef);
                    }
                }
            }
        }
        public bool Lock(int?timerIntervalOverride = null)
        {
            if (!CanLock)
            {
                return(false);
            }

            try
            {
                using (var ms = new MemoryStream())
                    using (var sw = new StreamWriter(ms))
                    {
                        _timer.Stop();

                        if (timerIntervalOverride.HasValue)
                        {
                            _timer.Interval = (double)timerIntervalOverride;
                        }
                        else
                        {
                            _timer.Interval = _timerInterval;
                        }

                        sw.Write(GenerateLockFileContents());
                        sw.Flush();
                        ms.Position = 0;

                        _fs.WriteFile(_lockFullPath, ms, GenerateCreatDateTime());

                        // Unlock after a configured interval
                        _timer.Start();

                        _logger.Info("Locked replication");
                        return(true);
                    }
            }
            catch (Exception ex)
            {
                _logger.Error("Unable to lock replication. " + ex.Message);
                return(false);
            }
        }
Example #35
0
        protected override void OnInit(EventArgs e)
        {
            FS = Engine.Resolve<IFileSystem>();
            Config = Engine.Resolve<ConfigurationManagerWrapper>().Sections.Management;
            Register.JQueryUi(Page);
            var selected = Selection.SelectedItem;
            if (IsPostBack && !string.IsNullOrEmpty(inputFile.PostedFile.FileName))
            {
                string uploadFolder = Request["inputLocation"];
                if(!IsAvailable(uploadFolder))
                    throw new N2Exception("Cannot upload to " + Server.HtmlEncode(uploadFolder));

                string fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
                string filePath = Url.Combine(uploadFolder, fileName);
                FS.WriteFile(filePath, inputFile.PostedFile.InputStream);

                ClientScript.RegisterStartupScript(typeof(Tree), "select", "updateOpenerWithUrlAndClose('" + ResolveUrl(filePath) + "');", true);
            }
            else if (Request["location"] == "files" || Request["location"] == "filesselection")
            {
                IHost host = Engine.Resolve<IHost>();
                HierarchyNode<ContentItem> root = new HierarchyNode<ContentItem>(Engine.Persister.Get(host.DefaultSite.RootItemID));

                var selectionTrail = new List<ContentItem>();
                if (selected is AbstractNode)
                {
                    selectionTrail = new List<ContentItem>(Find.EnumerateParents(selected, null, true));
                }
                else
                {
                    TrySelectingPrevious(ref selected, ref selectionTrail);
                }

                foreach (string uploadFolder in Engine.EditManager.UploadFolders)
                {
                    var dd = FS.GetDirectory(uploadFolder);

                    var dir = Directory.New(dd, root.Current, FS, Engine.Resolve<ImageSizeCache>());
                    var node = CreateDirectoryNode(FS, dir, root, selectionTrail);
                    root.Children.Add(node);
                }

                AddSiteFilesNodes(root, host.DefaultSite, selectionTrail);
                foreach (var site in host.Sites)
                {
                    if (site.StartPageID == host.DefaultSite.StartPageID)
                        continue;

                    AddSiteFilesNodes(root, site, selectionTrail);
                }

                siteTreeView.Nodes = root;
                siteTreeView.SelectedItem = selected;
            }
            else
            {
                var filter = Engine.EditManager.GetEditorFilter(Page.User);
                siteTreeView.Filter = filter;
                siteTreeView.RootNode = Engine.Resolve<Navigator>().Navigate(Request["root"] ?? "/");
                siteTreeView.SelectedItem = selected;
            }

            siteTreeView.SelectableTypes = Request["selectableTypes"];
            siteTreeView.SelectableExtensions = Request["selectableExtensions"];
            siteTreeView.DataBind();

            base.OnInit(e);
        }
Example #36
0
        protected override void OnInit(EventArgs e)
        {
            FS = Engine.Resolve<IFileSystem>();
            Config = Engine.Resolve<ConfigurationManagerWrapper>().Sections.Management;
            Register.JQueryUi(Page);
            var selected = Selection.SelectedItem;
            if (IsPostBack && !string.IsNullOrEmpty(inputFile.PostedFile.FileName))
            {
                string uploadFolder = Request[inputLocation.UniqueID];
                if(!IsAvailable(uploadFolder))
                    throw new N2Exception("Cannot upload to " + Server.HtmlEncode(uploadFolder));

                string fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
                string filePath = Url.Combine(uploadFolder, fileName);

                if (Engine.Config.Sections.Management.UploadFolders.IsTrusted(fileName))
                {
                    FS.WriteFile(filePath, inputFile.PostedFile.InputStream);
                }
                else
                {
                    throw new N2.Security.PermissionDeniedException("Invalid file name");
                }

                ClientScript.RegisterStartupScript(typeof(Tree), "select", "updateOpenerWithUrlAndClose('" + ResolveUrl(filePath) + "');", true);
            }
            else if (Request["location"] == "files" || Request["location"] == "filesselection")
            {
                IHost host = Engine.Resolve<IHost>();
                HierarchyNode<ContentItem> root = new HierarchyNode<ContentItem>(Engine.Persister.Get(host.DefaultSite.RootItemID));

                var selectionTrail = new List<ContentItem>();
                if (selected is AbstractNode)
                {
                    selectionTrail = new List<ContentItem>(Find.EnumerateParents(selected, null, true));
                }
                else
                {
                    TrySelectingPrevious(ref selected, ref selectionTrail);
                }

                foreach (var upload in Engine.Resolve<UploadFolderSource>().GetUploadFoldersForAllSites())
                {
                    var dir = N2.Management.Files.FolderNodeProvider.CreateDirectory(upload, FS, Engine.Persister.Repository, Engine.Resolve<IDependencyInjector>());

                    if (!Engine.SecurityManager.IsAuthorized(dir, User))
                        continue;

                    var node = CreateDirectoryNode(FS, dir, root, selectionTrail);
                    root.Children.Add(node);
                }

                siteTreeView.Nodes = root;
                siteTreeView.SelectedItem = selected;
            }
            else
            {
                var filter = Engine.EditManager.GetEditorFilter(Page.User);
                siteTreeView.Filter = filter;
                siteTreeView.RootNode = Engine.Resolve<Navigator>().Navigate(Request["root"] ?? "/");
                siteTreeView.SelectedItem = selected;
            }

            siteTreeView.SelectableTypes = Request["selectableTypes"];
            siteTreeView.SelectableExtensions = Request["selectableExtensions"];
            siteTreeView.DataBind();

            inputLocation.Value = siteTreeView.SelectedItem.Url;

            base.OnInit(e);
        }