Example #1
0
        /// <summary>
        /// Downloads the image.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="urlHash">The URL hash.</param>
        /// <param name="pointerCachePath">The pointer cache path.</param>
        /// <returns>Task.</returns>
        private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath)
        {
            using (var result = await _httpClient.GetResponse(new HttpRequestOptions
            {
                Url = url,
                BufferContent = false
            }).ConfigureAwait(false))
            {
                var ext = result.ContentType.Split('/').Last();

                var fullCachePath = GetFullCachePath(urlHash + "." + ext);

                _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fullCachePath));
                using (var stream = result.Content)
                {
                    using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
                    {
                        await stream.CopyToAsync(filestream).ConfigureAwait(false);
                    }
                }

                _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(pointerCachePath));
                _fileSystem.WriteAllText(pointerCachePath, fullCachePath);
            }
        }
Example #2
0
        private void CacheAddress(IpAddressInfo address)
        {
            if (_cachedIpAddress != null && _cachedIpAddress.Equals(address))
            {
                // no need to update the file if the address has not changed
                return;
            }

            var path = CacheFilePath;

            try
            {
                _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
            }
            catch (Exception ex)
            {
            }

            try
            {
                _fileSystem.WriteAllText(path, _encryption.EncryptString(address.ToString()), Encoding.UTF8);
                _cachedIpAddress = address;
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error saving data", ex);
            }
        }
Example #3
0
        /// <inheritdoc/>
        public void WriteAllText(string relativePath, string content)
        {
            var absolutePath = MapPath(relativePath);

            ThrowIfAccessingOutsideTenantSandbox(relativePath, absolutePath);
            _fileSystem.WriteAllText(absolutePath, content);
        }
        protected void EnsureWriteAccess(string path)
        {
            var file = Path.Combine(path, Guid.NewGuid().ToString());

            _fileSystem.WriteAllText(file, string.Empty);
            _fileSystem.DeleteFile(file);
        }
Example #5
0
        internal bool EnsureVersionHeaderFile(IFileSystem fileSystem, string fullPath)
        {
            if (fileSystem.Exists(fullPath))
            {
                return(true);
            }

            var assemblyInfoSource = templateManager.GetTemplateFor(Path.GetExtension(fullPath));

            if (!string.IsNullOrWhiteSpace(assemblyInfoSource))
            {
                var fileInfo = new FileInfo(fullPath);

                if (!fileSystem.DirectoryExists(fileInfo.Directory.FullName))
                {
                    fileSystem.CreateDirectory(fileInfo.Directory.FullName);
                }

                fileSystem.WriteAllText(fullPath, assemblyInfoSource);
                return(true);
            }

            Logger.WriteWarning($"No version header template available to create source file '{fullPath}'");
            return(false);
        }
        static bool EnsureVersionAssemblyInfoFile(Arguments arguments, IFileSystem fileSystem, string fullPath)
        {
            if (fileSystem.Exists(fullPath))
            {
                return(true);
            }

            if (!arguments.EnsureAssemblyInfo)
            {
                return(false);
            }

            var assemblyInfoSource = AssemblyVersionInfoTemplates.GetAssemblyInfoTemplateFor(fullPath);

            if (!string.IsNullOrWhiteSpace(assemblyInfoSource))
            {
                var fileInfo = new FileInfo(fullPath);
                if (!fileSystem.DirectoryExists(fileInfo.Directory.FullName))
                {
                    fileSystem.CreateDirectory(fileInfo.Directory.FullName);
                }
                fileSystem.WriteAllText(fullPath, assemblyInfoSource);
                return(true);
            }
            Logger.WriteWarning(string.Format("No version assembly info template available to create source file '{0}'", arguments.UpdateAssemblyInfoFileName));
            return(false);
        }
Example #7
0
        void WriteConfig(string workingDirectory, IFileSystem fileSystem, string configContents)
        {
            var outputFilename = GetOutputFilename(workingDirectory, fileSystem);

            fileSystem.WriteAllText(outputFilename, configContents);
            Logger.WriteInfo(string.Format("AppVeyor sample config file written to {0}", outputFilename));
        }
        public async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var result = await apiClient.FetchToggles(Etag, cancellationToken).ConfigureAwait(false);

            if (!result.HasChanged)
            {
                return;
            }

            if (string.IsNullOrEmpty(result.Etag))
            {
                return;
            }

            if (result.Etag == Etag)
            {
                return;
            }

            toggleCollection.Instance = result.ToggleCollection;

            using (var fs = fileSystem.FileOpenCreate(toggleFile))
            {
                jsonSerializer.Serialize(fs, result.ToggleCollection);
            }

            Etag = result.Etag;
            fileSystem.WriteAllText(etagFile, Etag);
        }
 public void Store(ToolConfiguration configuration)
 {
     Console.WriteLine(JsonSerializer.Serialize(configuration));
     _fileSystem.WriteAllText(
         UPath.Root / _configurationFileName,
         JsonSerializer.Serialize(configuration));
 }
Example #10
0
        public void Execute(VersionVariables variables, GitVersionInfoContext context)
        {
            var fileName  = context.FileName;
            var directory = context.WorkingDirectory;
            var filePath  = Path.Combine(directory, fileName);

            string originalFileContents = null;

            if (File.Exists(filePath))
            {
                originalFileContents = fileSystem.ReadAllText(filePath);
            }

            var fileExtension = Path.GetExtension(filePath);
            var template      = templateManager.GetTemplateFor(fileExtension);
            var addFormat     = templateManager.GetAddFormatFor(fileExtension);
            var indentation   = GetIndentation(fileExtension);

            var members = string.Join(System.Environment.NewLine, variables.Select(v => string.Format(indentation + addFormat, v.Key, v.Value)));

            var fileContents = string.Format(template, members);

            if (fileContents != originalFileContents)
            {
                fileSystem.WriteAllText(filePath, fileContents);
            }
        }
        void WriteConfig(string workingDirectory, IFileSystem fileSystem, string configContents)
        {
            var outputFilename = GetOutputFilename(workingDirectory, fileSystem);

            fileSystem.WriteAllText(outputFilename, configContents);
            log.Info($"AppVeyor sample config file written to {outputFilename}");
        }
Example #12
0
        public async Task DownloadLatestVersion(ITaskProgress taskProgress)
        {
            cachedResponse ??= await InternalCheckForUpdates();

            if (cachedResponse != null)
            {
                var progress = new Progress <(long downloaded, long?totalBytes)>((v) =>
                {
                    var isDownloaded = (v.totalBytes.HasValue && v.totalBytes.Value == v.downloaded) ||
                                       v.downloaded == -1;
                    var isStatusKnown   = v.totalBytes.HasValue;
                    var currentProgress = v.totalBytes.HasValue ? (int)v.downloaded : (v.downloaded < 0 ? 1 : 0);
                    var maxProgress     = v.totalBytes ?? 1;

                    if (taskProgress.State == TaskState.InProgress)
                    {
                        taskProgress.Report(currentProgress, (int)maxProgress, isDownloaded ?
                                            "finished" :
                                            (isStatusKnown ? $"{v.downloaded / 1_000_000f:0.00}/{maxProgress / 1_000_000f:0.00}MB" : $"{v.downloaded / 1_000_000f:0.00}MB"));
                    }
                });
                var physPath = fileSystem.ResolvePhysicalPath(platformService.UpdateZipFilePath);
                await UpdateClient.DownloadUpdate(cachedResponse, physPath.FullName, progress);

                if (cachedResponse.ChangeLog?.Length > 0)
                {
                    fileSystem.WriteAllText("~/changelog.json", JsonConvert.SerializeObject(cachedResponse.ChangeLog));
                }
            }

            taskProgress.ReportFinished();
        }
        public AssemblyInfoUpdate(IFileSystem fileSystem, GitHubFlowVersionContext context)
        {
            if (!context.Arguments.UpdateAssemblyInfo)
            {
                return;
            }

            var assemblyInfoFiles = fileSystem.GetFiles(context.RepositoryRoot, "AssemblyInfo.cs",
                                                        SearchOption.AllDirectories);

            foreach (var assemblyInfoFile in assemblyInfoFiles)
            {
                var destFileName   = assemblyInfoFile + ".bak";
                var sourceFileName = assemblyInfoFile;
                fileSystem.Copy(assemblyInfoFile, destFileName, true);
                _restoreBackupTasks.Add(() => fileSystem.Move(destFileName, sourceFileName, true));
                _cleanupBackupTasks.Add(() => fileSystem.DeleteFile(destFileName));

                var assemblyVersion     = context.Variables[VariableProvider.AssemblyVersion];
                var assemblyInfoVersion = context.Variables[VariableProvider.AssemblyInformationalVersion];
                var assemblyFileVersion = context.Variables[VariableProvider.AssemblyFileVersion];
                var fileContents        = fileSystem.ReadAllText(sourceFileName)
                                          .RegexReplace(@"AssemblyVersion\(""\d+.\d+.\d+(.\d+|\*)?""\)", string.Format("AssemblyVersion(\"{0}\")", assemblyVersion))
                                          .RegexReplace(@"AssemblyInformationalVersion\(""\d+.\d+.\d+(.\d+|\*)?""\)", string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion))
                                          .RegexReplace(@"AssemblyFileVersion\(""\d+.\d+.\d+(.\d+|\*)?""\)", string.Format("AssemblyFileVersion(\"{0}\")", assemblyFileVersion));

                fileSystem.WriteAllText(sourceFileName, fileContents);
            }
        }
Example #14
0
        private void OutputResult(XNode node)
        {
            if (node == null)
            {
                Error("", "The output is empty");
                return;
            }

            var settings = new XmlWriterSettings
            {
                Indent             = true,
                OmitXmlDeclaration = true,
                IndentChars        = "  ",
                NamespaceHandling  = NamespaceHandling.OmitDuplicates
            };

            // quite expensive way to insert newline before each xmlns, but it works
            using (var sw = new StringWriter())
            {
                using (var writer = XmlWriter.Create(sw, settings))
                {
                    node.WriteTo(writer);
                }

                var content = AddNewLineAfterXmlns(sw.ToString());
                _fs.WriteAllText(_options.OutPath, content);
            }
        }
        public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, VersionVariables variables, IFileSystem fileSystem)
        {
            if (!args.UpdateAssemblyInfo) return;

            if (args.Output != OutputType.Json)
                Console.WriteLine("Updating assembly info files");

            var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, args, fileSystem);

            foreach (var assemblyInfoFile in assemblyInfoFiles)
            {
                var backupAssemblyInfo = assemblyInfoFile + ".bak";
                var localAssemblyInfo = assemblyInfoFile;
                fileSystem.Copy(assemblyInfoFile, backupAssemblyInfo, true);
                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localAssemblyInfo))
                        fileSystem.Delete(localAssemblyInfo);
                    fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
                });
                cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));

                var assemblyVersion = variables.AssemblySemVer;
                var assemblyInfoVersion = variables.InformationalVersion;
                var assemblyFileVersion = variables.MajorMinorPatch + ".0";
                var fileContents = fileSystem.ReadAllText(assemblyInfoFile)
                    .RegexReplace(@"AssemblyVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyVersion(\"{0}\")", assemblyVersion))
                    .RegexReplace(@"AssemblyInformationalVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion))
                    .RegexReplace(@"AssemblyFileVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyFileVersion(\"{0}\")", assemblyFileVersion));

                fileSystem.WriteAllText(assemblyInfoFile, fileContents);
            }
        }
Example #16
0
        public void Save(IGeneralConfig config, IFileSystem disk, IJsonUtil jsonUtil)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }
            if (disk == null)
            {
                throw new ArgumentNullException(nameof(disk));
            }
            if (jsonUtil == null)
            {
                throw new ArgumentNullException(nameof(jsonUtil));
            }

            var path = config.ResolvePath(UserPath);
            var dir  = Path.GetDirectoryName(path);

            if (!disk.DirectoryExists(dir))
            {
                disk.CreateDirectory(dir);
            }

            var json = jsonUtil.Serialize(this);

            disk.WriteAllText(path, json);
        }
Example #17
0
 public virtual Task Save(string filename, IFileSystem provider)
 {
     provider.WriteAllText(filename, Contents);
     this.Filename = filename;
     FileSaved?.Invoke(this, new EventArgs());
     return(Task.CompletedTask);
 }
Example #18
0
        public void Execute(VersionVariables variables, OutputContext context)
        {
            var gitVersionOptions = options.Value;

            if (gitVersionOptions.Output.Contains(OutputType.BuildServer))
            {
                buildAgent?.WriteIntegration(console.WriteLine, variables, context.UpdateBuildNumber ?? true);
            }
            if (gitVersionOptions.Output.Contains(OutputType.File))
            {
                fileSystem.WriteAllText(context.OutputFile, variables.ToString());
            }
            if (gitVersionOptions.Output.Contains(OutputType.Json))
            {
                switch (gitVersionOptions.ShowVariable)
                {
                case null:
                    console.WriteLine(variables.ToString());
                    break;

                default:
                    if (!variables.TryGetValue(gitVersionOptions.ShowVariable, out var part))
                    {
                        throw new WarningException($"'{gitVersionOptions.ShowVariable}' variable does not exist");
                    }

                    console.WriteLine(part);
                    break;
                }
            }
        }
        protected async Task SaveSettingsToDiskAsync(ILaunchSettings newSettings)
        {
            Dictionary <string, object> serializationData = GetSettingsToSerialize(newSettings);
            string fileName = await GetLaunchSettingsFilePathAsync();

            try
            {
                await EnsureSettingsFolderAsync();

                // We don't want to write null values. We want to keep the file as small as possible
                var settings = new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                };
                string jsonString = JsonConvert.SerializeObject(serializationData, Formatting.Indented, settings);

                IgnoreFileChanges = true;
                _fileSystem.WriteAllText(fileName, jsonString);

                // Update the last write time
                LastSettingsFileSyncTime = _fileSystem.LastFileWriteTime(fileName);
            }
            finally
            {
                IgnoreFileChanges = false;
            }
        }
        public int Run(ExportRuleDocumentationOptions options)
        {
            try
            {
                var rules = CompositionUtilities.GetExports <SarifValidationSkimmerBase>(
                    new Assembly[] { Assembly.GetExecutingAssembly() }).ToList();

                var sb = new StringBuilder();
                sb.AppendLine($"# Rules{Environment.NewLine}");

                foreach (SarifValidationSkimmerBase rule in rules)
                {
                    BuildRule(rule, sb);
                }

                _fileSystem.WriteAllText(options.OutputFilePath, sb.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(FAILURE);
            }

            return(SUCCESS);
        }
Example #21
0
        public static void SaveImageInfo(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem, string musicBrainzId, string url, string size)
        {
            if (appPaths == null)
            {
                throw new ArgumentNullException("appPaths");
            }
            if (string.IsNullOrEmpty(musicBrainzId))
            {
                throw new ArgumentNullException("musicBrainzId");
            }
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            var cachePath = Path.Combine(appPaths.CachePath, "lastfm", musicBrainzId, "image.txt");

            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    fileSystem.DeleteFile(cachePath);
                }
                else
                {
                    fileSystem.CreateDirectory(fileSystem.GetDirectoryName(cachePath));
                    fileSystem.WriteAllText(cachePath, url + "|" + size);
                }
            }
            catch (IOException ex)
            {
                // Don't fail if this is unable to write
                logger.ErrorException("Error saving to {0}", ex, cachePath);
            }
        }
Example #22
0
    public int TrackPublicationChangesOnCDS()
    {
        var resultFlag = -1;

        try {
            string pubUpdateFileCDSPath   = CommonCalls.PubUpdateFileCDSPath;
            string pubUpdateFileLocalPath = CommonCalls.PubUpdateFileLocalPath;
            if (File.Exists(pubUpdateFileCDSPath))
            {
                File.Copy(pubUpdateFileCDSPath, pubUpdateFileLocalPath, true);
            }
            if (File.Exists(pubUpdateFileLocalPath))
            {
                string[] pubRecords            = File.ReadAllLines(pubUpdateFileLocalPath);
                var      pubRecordsExceptToday = pubRecords.Where(p => !p.Trim().EndsWith(DateTime.Now.ToString("dd/MM/yy"))).ToList();
                resultFlag = diskDeliveryDAO.TrackPublicationChangesOnCDS(pubRecordsExceptToday);
                File.WriteAllText(pubUpdateFileLocalPath, string.Empty);
                string[] pubRecordsCDS      = File.ReadAllLines(pubUpdateFileCDSPath);
                var      pubRecordsTodayCDS = pubRecordsCDS.Where(p => p.Trim().EndsWith(DateTime.Now.ToString("dd/MM/yy"))).ToList();
                File.WriteAllLines(pubUpdateFileCDSPath, pubRecordsTodayCDS);
            }
            return(resultFlag);
        } catch (Exception) {
            return(-1);
        }
    }
Example #23
0
        private async Task <AcmeContext> GetOrCreateAcmeContext(Uri acmeDirectoryUri, string email)
        {
            AcmeContext acme     = null;
            string      filename = $"account{email}--{acmeDirectoryUri.Host}.pem";

            if (!await fileSystem.Exists(filename))
            {
                acme = new AcmeContext(acmeDirectoryUri);
                var account = acme.NewAccount(email, true);

                // Save the account key for later use
                var pemKey = acme.AccountKey.ToPem();
                await fileSystem.WriteAllText(filename, pemKey);

                await Task.Delay(10000); //Wait a little before using the new account.

                acme = new AcmeContext(acmeDirectoryUri, acme.AccountKey, new AcmeHttpClient(acmeDirectoryUri, new HttpClient()));
            }
            else
            {
                var pemKey = await fileSystem.ReadAllText(filename);

                var accountKey = KeyFactory.FromPem(pemKey);
                acme = new AcmeContext(acmeDirectoryUri, accountKey, new AcmeHttpClient(acmeDirectoryUri, new HttpClient()));
            }

            return(acme);
        }
Example #24
0
        private JsonMapNode LoadOrRebuildMap(PageOptions options)
        {
            JsonMapNode root;
            Stopwatch   w = Stopwatch.StartNew();

            string mapPath = Path.ChangeExtension(options.InputFilePath, ".map.json");

            if (_fileSystem.FileExists(mapPath) && _fileSystem.GetLastWriteTime(mapPath) > _fileSystem.GetLastWriteTime(options.InputFilePath))
            {
                // If map exists and is up-to-date, just reload it
                Console.WriteLine($"Loading Json Map \"{mapPath}\"...");
                root = JsonConvert.DeserializeObject <JsonMapNode>(_fileSystem.ReadAllText(mapPath));
            }
            else
            {
                // Otherwise, build the map and save it (1% -> 10MB limit)
                double mapSizeLimit = 10 * JsonMapSettings.Megabyte * (options.TargetMapSizeRatio / 0.01);

                Console.WriteLine($"Building {options.TargetMapSizeRatio:p0} Json Map of \"{options.InputFilePath}\" into \"{mapPath}\"...");
                root = JsonMapBuilder.Build(() => _fileSystem.OpenRead(options.InputFilePath), new JsonMapSettings(options.TargetMapSizeRatio, mapSizeLimit));

                if (root != null)
                {
                    _fileSystem.WriteAllText(mapPath, JsonConvert.SerializeObject(root, Formatting.None));
                }
            }

            w.Stop();
            Console.WriteLine($"Done in {w.Elapsed.TotalSeconds:n1}s.");

            return(root);
        }
        private bool EnsureVersionAssemblyInfoFile(bool ensureAssemblyInfo, IFileSystem fileSystem, string fullPath)
        {
            if (fileSystem.Exists(fullPath))
            {
                return(true);
            }

            if (!ensureAssemblyInfo)
            {
                return(false);
            }

            var assemblyInfoSource = templateManager.GetTemplateFor(Path.GetExtension(fullPath));

            if (!string.IsNullOrWhiteSpace(assemblyInfoSource))
            {
                var fileInfo = new FileInfo(fullPath);

                if (fileInfo.Directory != null && !fileSystem.DirectoryExists(fileInfo.Directory.FullName))
                {
                    fileSystem.CreateDirectory(fileInfo.Directory.FullName);
                }

                fileSystem.WriteAllText(fullPath, assemblyInfoSource);
                return(true);
            }

            log.Warning($"No version assembly info template available to create source file '{fullPath}'");
            return(false);
        }
        public BeginCreatePostResult BeginCreatePost(string markdownContent, string title)
        {
            var postId = this.randomIdGenerator.GenerateId(8);

            var tempPath = GetPostDirectory(postId);

            fileSystem.CreateDirectory(tempPath);

            List <string> localImageUrls = null;

            (localImageUrls, markdownContent) = ExtractAndReplaceClientCachedImages(postId, markdownContent);

            List <string> serverCachedImagesNames = null;

            (serverCachedImagesNames, markdownContent) = ExtractAndReplaceServerCachedImages(postId, markdownContent);

            var imageDirectory = Path.Combine(Path.Combine(tempPath, "img"));

            if (serverCachedImagesNames.Count > 0)
            {
                fileSystem.CreateDirectory(imageDirectory);
            }

            foreach (var serverImageName in serverCachedImagesNames)
            {
                var fromFilename = Path.Combine(this.blogSettings.LocalImageTempFolder, serverImageName);
                var toFileName   = Path.Combine(Path.Combine(tempPath, "img"), serverImageName);
                fileSystem.MoveFile(fromFilename, toFileName);
            }

            fileSystem.WriteAllText(Path.Combine(tempPath, "content.md"), markdownContent);
            //TODO: PublicationDate should be deferred until commit so we should move metadata to commit in the future.
            var metadata = new PostMetadata
            {
                Title           = title,
                PostId          = postId,
                PublicationDate = this.clock.Now
            };

            fileSystem.WriteAllText(Path.Combine(tempPath, "metadata.json"), JsonConvert.SerializeObject(metadata));

            return(new BeginCreatePostResult
            {
                PostId = postId,
                LocalImageUrls = localImageUrls
            });
        }
        /// <summary>
        /// Applies overrides to an endpoints.json file
        /// </summary>
        /// <param name="endpointsJsonSourceFilePath">The endpoints-original.json source location</param>
        /// <param name="endpointsOverrideFilePath">The path to the endpoints override json file</param>
        /// <returns>String: the new endpoints.json input text.</returns>
        public string ApplyOverrides(string endpointsJsonSourceFilePath, string endpointsOverrideFilePath)
        {
            // Retrieve the current endpoints-original.json file
            string input = _fs.ReadAllText(endpointsJsonSourceFilePath);


            JObject endpointsData = JObject.Parse(input);

            // Retrieve the endpoints-override.json file
            string overrideJson = _fs.ReadAllText(endpointsOverrideFilePath);

            if (!string.IsNullOrWhiteSpace(overrideJson))
            {
                JObject configuration = JObject.Parse(overrideJson);
                if (configuration != null)
                {
                    foreach (var service in configuration.Children())
                    {
                        var    servicePrefix = service.Path;
                        JToken serviceNode   = endpointsData["partitions"][0]["services"][servicePrefix];
                        if (serviceNode != null)
                        {
                            JObject endpointsNode = serviceNode["endpoints"] as JObject;

                            var endpointsToRemove = configuration.SelectTokens($"{servicePrefix}.remove");
                            foreach (var endpointToRemove in endpointsToRemove.Children())
                            {
                                endpointsNode.Remove(endpointToRemove.ToObject <string>());
                            }
                            var endpointsToAdd = configuration.SelectTokens($"{servicePrefix}.add");
                            foreach (var endpointToAdd in endpointsToAdd.Children())
                            {
                                // We can not have two properties with the same name
                                var endpointProperty = endpointToAdd as JProperty;
                                var exists           = endpointsNode.Properties().ToList().Exists(p => p.Name == endpointProperty.Name);
                                if (!exists)
                                {
                                    endpointsNode.Add(endpointToAdd);
                                }
                                else
                                {
                                    throw new InvalidOperationException($"The endpoint {endpointProperty.Name} already exists for service {servicePrefix}");
                                }
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException($"The service {servicePrefix} does not exist in the endpoints.json file");
                        }
                    }
                }
            }

            var    targetPath = Path.Combine(Path.GetDirectoryName(endpointsJsonSourceFilePath), "endpoints.json");
            string output     = JsonConvert.SerializeObject(endpointsData, Formatting.Indented);

            _fs.WriteAllText(targetPath, output);
            return(output);
        }
        /// <summary>
        /// Writes the DbContext to disk using the given Roslyn SyntaxTree.
        /// The method expects that SyntaxTree has a file path associated with it.
        /// Handles both writing a new file and editing an existing file.
        /// </summary>
        /// <param name="newTree"></param>
        private void PersistSyntaxTree(SyntaxTree newTree)
        {
            Debug.Assert(newTree != null);
            Debug.Assert(!String.IsNullOrEmpty(newTree.FilePath));

            _fileSystem.CreateDirectory(Path.GetDirectoryName(newTree.FilePath));
            _fileSystem.WriteAllText(newTree.FilePath, newTree.GetText().ToString());
        }
Example #29
0
        private void Save(PanelViewModel document, string filePath)
        {
            document.FilePath = filePath;
            fileSystem.WriteAllText(filePath, document.FileContent);
            document.Saved();

            AddRecentScript(filePath);
        }
        internal static void EncryptFile(this IEJsonCrypto eJsonCrypto, string fileName, IFileSystem fileSystem)
        {
            fileSystem = fileSystem ?? new FileSystemWrapper();
            var json      = fileSystem.ReadAllText(fileName);
            var encrypted = eJsonCrypto.GetEncryptedJson(json);

            fileSystem.WriteAllText(fileName, encrypted);
        }
        string SetupConfigFileContent(string text, string fileName, string path)
        {
            var fullPath = Path.Combine(path, fileName);

            fileSystem.WriteAllText(fullPath, text);

            return(fullPath);
        }
        public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, VersionVariables variables, IFileSystem fileSystem)
        {
            if (!args.UpdateAssemblyInfo) return;

            if (args.Output != OutputType.Json)
                Logger.WriteInfo("Updating assembly info files");

            var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, args, fileSystem).ToList();
            Logger.WriteInfo(string.Format("Found {0} files", assemblyInfoFiles.Count));

            var assemblyVersion = variables.AssemblySemVer;
            var assemblyVersionRegex = new Regex(@"AssemblyVersion\s*\(\s*""[^""]*""\s*\)");
            var assemblyVersionString = !string.IsNullOrWhiteSpace(assemblyVersion) ? string.Format("AssemblyVersion(\"{0}\")", assemblyVersion) : null;
            var assemblyInfoVersion = variables.InformationalVersion;
            var assemblyInfoVersionRegex = new Regex(@"AssemblyInformationalVersion\s*\(\s*""[^""]*""\s*\)");
            var assemblyInfoVersionString = string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion);
            var assemblyFileVersion = variables.MajorMinorPatch + ".0";
            var assemblyFileVersionRegex = new Regex(@"AssemblyFileVersion\s*\(\s*""[^""]*""\s*\)");
            var assemblyFileVersionString = string.Format("AssemblyFileVersion(\"{0}\")", assemblyFileVersion);

            foreach (var assemblyInfoFile in assemblyInfoFiles)
            {
                var backupAssemblyInfo = assemblyInfoFile.FullName + ".bak";
                var localAssemblyInfo = assemblyInfoFile.FullName;
                fileSystem.Copy(assemblyInfoFile.FullName, backupAssemblyInfo, true);
                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localAssemblyInfo))
                        fileSystem.Delete(localAssemblyInfo);
                    fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
                });
                cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));

                var fileContents = fileSystem.ReadAllText(assemblyInfoFile.FullName);
                var appendedAttributes = false;
                if (!string.IsNullOrWhiteSpace(assemblyVersion))
                {
                    fileContents = ReplaceOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
                }
                fileContents = ReplaceOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
                fileContents = ReplaceOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString, assemblyInfoFile.Extension, ref appendedAttributes);

                if (appendedAttributes)
                {
                    // If we appended any attributes, put a new line after them
                    fileContents += Environment.NewLine;
                }
                fileSystem.WriteAllText(assemblyInfoFile.FullName, fileContents);
            }
        }
        public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, VersionVariables variables, IFileSystem fileSystem)
        {
            if (!args.UpdateAssemblyInfo) return;

            if (args.Output != OutputType.Json)
                Logger.WriteInfo("Updating assembly info files");

            var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, args, fileSystem);
            Logger.WriteInfo(string.Format("Found {0} files", assemblyInfoFiles.Count()));

            var assemblyVersion = variables.AssemblySemVer;
            var assemblyVersionRegex = new Regex(@"AssemblyVersion\(""[^""]*""\)");
            var assemblyVersionString = string.Format("AssemblyVersion(\"{0}\")", assemblyVersion);
            var assemblyInfoVersion = variables.InformationalVersion;
            var assemblyInfoVersionRegex = new Regex(@"AssemblyInformationalVersion\(""[^""]*""\)");
            var assemblyInfoVersionString = string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion);
            var assemblyFileVersion = variables.MajorMinorPatch + ".0";
            var assemblyFileVersionRegex = new Regex(@"AssemblyFileVersion\(""[^""]*""\)");
            var assemblyFileVersionString = string.Format("AssemblyFileVersion(\"{0}\")", assemblyFileVersion);

            foreach (var assemblyInfoFile in assemblyInfoFiles.Select(f => new FileInfo(f)))
            {
                var backupAssemblyInfo = assemblyInfoFile.FullName + ".bak";
                var localAssemblyInfo = assemblyInfoFile.FullName;
                fileSystem.Copy(assemblyInfoFile.FullName, backupAssemblyInfo, true);
                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localAssemblyInfo))
                        fileSystem.Delete(localAssemblyInfo);
                    fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
                });
                cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));

                var fileContents = fileSystem.ReadAllText(assemblyInfoFile.FullName);
                fileContents = ReplaceOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString);
                fileContents = ReplaceOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString);
                fileContents = ReplaceOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString);

                fileSystem.WriteAllText(assemblyInfoFile.FullName, fileContents);
            }
        }
        static bool EnsureVersionAssemblyInfoFile(Arguments arguments, IFileSystem fileSystem, string fullPath)
        {
            if (fileSystem.Exists(fullPath)) return true;

            if (!arguments.EnsureAssemblyInfo) return false;

            var assemblyInfoSource = AssemblyVersionInfoTemplates.GetAssemblyInfoTemplateFor(fullPath);
            if (!string.IsNullOrWhiteSpace(assemblyInfoSource))
            {
                var fileInfo = new FileInfo(fullPath);
                if (!fileSystem.DirectoryExists(fileInfo.Directory.FullName))
                {
                    fileSystem.CreateDirectory(fileInfo.Directory.FullName);
                }
                fileSystem.WriteAllText(fullPath, assemblyInfoSource);
                return true;
            }
            Logger.WriteWarning(string.Format("No version assembly info template available to create source file '{0}'", arguments.UpdateAssemblyInfoFileName));
            return false;
        }
Example #35
0
 void WriteConfig(string workingDirectory, IFileSystem fileSystem, string configContents)
 {
     var outputFilename = GetOutputFilename(workingDirectory, fileSystem);
     fileSystem.WriteAllText(outputFilename, configContents);
     Logger.WriteInfo(string.Format("AppVeyor sample config file written to {0}", outputFilename));
 }
Example #36
0
 public void Save(IFileSystem fs)
 {
     fs.WriteAllText(FileName, Text);
     Dirty = false;
 }
 private static void AddTextFileToProject(Project project, IFileSystem fileSystem, string projectRelativePath, string text)
 {
     // Need to be sure the folder exists first
     var outputDirPath = Path.GetDirectoryName(projectRelativePath);
     var projectDir = project.GetOrCreateProjectItems(outputDirPath, true /* create */, fileSystem);
     var diskPath = Path.Combine(project.GetFullPath(), projectRelativePath);
     fileSystem.WriteAllText(diskPath, text);
     projectDir.AddFromFile(diskPath);
 }