/// <summary> /// Writes data to file. /// </summary> /// <param name="scoreBoardPlayers">Collection of players.</param> /// <param name="fileName">File name in the file system to write in.</param> public void WriteToFile(IEnumerable<IPlayer> scoreBoardPlayers, FileNames fileName) { using (StreamWriter writer = new StreamWriter(string.Format(TxtFilePath, fileName))) { foreach (var player in scoreBoardPlayers) { writer.WriteLine(string.Format(ScoreFormat, player.Name, player.Score)); } } }
/// <summary> /// Serializes the table of contents and its B-Trees. /// </summary> public byte[] Serialize() { using var ms = new MemoryStream(); using var bs = new BinaryStream(ms, ByteConverter.Big); bs.Write(SEGMENT_MAGIC); bs.Position = 16; bs.WriteUInt32((uint)Files.Count); bs.Position += sizeof(uint) * Files.Count; uint fileNamesOffset = (uint)bs.Position; FileNames.Serialize(bs); uint extOffset = (uint)bs.Position; Extensions.Serialize(bs); uint fileInfoOffset = (uint)bs.Position; FileInfos.Serialize(bs); // The list of file entry btrees mostly consist of the relation between files, folder, extensions and data // Thus it is writen at the end // Each tree is a seperate general subdir const int baseListPos = 20; for (int i = 0; i < Files.Count; i++) { FileEntryBTree f = Files[i]; uint treeOffset = (uint)bs.Position; bs.Position = baseListPos + (i * sizeof(uint)); bs.WriteUInt32(treeOffset); bs.Position = treeOffset; f.Serialize(bs, (uint)FileNames.Entries.Count, (uint)Extensions.Entries.Count); } // Go back to write the meta data bs.Position = 4; bs.WriteUInt32(fileNamesOffset); bs.WriteUInt32(extOffset); bs.WriteUInt32(fileInfoOffset); return(ms.ToArray()); }
public static void Prepare(string[] args) { if (args[0].Equals("/lang")) { if (args.Length > 1) { UserSettings.All.LanguageCode = args[1]; } } //Check each arg to know if it's a file. foreach (var arg in args) { if (File.Exists(arg)) { FileNames.Add(arg); } } }
/// <summary> /// Start a expolre request. /// </summary> public async Task <ExploreResponse> ExploreAssemblyAsync(string aAssemblyPath, string aRevitVersion, CancellationToken aCancellationToken) { ExploreResponse response = null; ExploreRequest request = new ExploreRequest { Timestamp = DateTime.Now, Id = GenerateId(), ClientName = mClientName, ClientVersion = mClientVersion, AssemblyPath = aAssemblyPath }; RevitHelper.StartRevit(aRevitVersion); bool isRunnerAvailable = await IsRunnerAvailable(aCancellationToken); if (isRunnerAvailable) { string requestFilePath = FileNames.ExploreRequestFilePath(request.Id); JsonHelper.ToFile(requestFilePath, request); var responseDirectoryPath = await GetResponseDirectory(request.Id); if (Directory.Exists(responseDirectoryPath)) { while (response == null && !aCancellationToken.IsCancellationRequested) { string responseFile = Path.Combine(responseDirectoryPath, FileNames.ExploreResponseFileName); response = JsonHelper.FromFile <ExploreResponse>(responseFile); if (response == null) { await Task.Delay(500, aCancellationToken); } } } else { FileHelper.DeleteWithLock(requestFilePath); } } return(response); }
public void RewriteExtract(Route rout, FolderName folder, FileNames file, ParametricData param) { string scriptIn = folder.scriptsFolder + @"\" + file.extractFileName; string scriptOut = rout.workingDirectory + @"\" + file.extractFileName; try { var reader = new StreamReader(scriptIn); string content = reader.ReadToEnd(); reader.Close(); var writer = new StreamWriter(scriptOut); writer.Write(content); writer.Close(); } catch (Exception e) { MessageBox.Show("Change: ", e.Message); } }
/// <summary> /// Called during creation of the <see cref="IScheduler"/> in order to give /// the <see cref="ISchedulerPlugin"/> a chance to initialize. /// </summary> /// <param name="pluginName">The name.</param> /// <param name="scheduler">The scheduler.</param> /// <throws>SchedulerConfigException </throws> public virtual async Task Initialize(string pluginName, IScheduler scheduler) { Name = pluginName; Scheduler = scheduler; typeLoadHelper = new SimpleTypeLoadHelper(); typeLoadHelper.Initialize(); Log.Info("Registering Quartz Job Initialization Plug-in."); // Create JobFile objects var tokens = FileNames.Split(FileNameDelimiter).Select(x => x.TrimStart()); foreach (string token in tokens) { JobFile jobFile = new JobFile(this, token); await jobFile.Initialize(); jobFiles.Add(new KeyValuePair <string, JobFile>(jobFile.FilePath, jobFile)); } }
public FileBrowser(int x, int y, int width, int height, StorageFolder path, Window.Window parentWindow, bool includeFiles = false, string filterByExtension = null, string id = null, bool traverseDirectories = true) : base(x, y, width, height, parentWindow, id) { _traverseDirectories = traverseDirectories; CurrentPath = path; CurrentlySelectedFile = string.Empty; BackColor = Terminal.LIGHT_CYAN; IncludeFiles = includeFiles; FilterByExtension = filterByExtension ?? ".basic"; Drives = BasicOne.KnownStorageFolders; GetFileNames(); if (FileNames.Any()) { CurrentlySelectedFile = FileNames[0]; } Selectable = true; }
/// <summary> /// Gets the corresponding path of the file name passed /// </summary> /// <param name="fn">the file name defined in FileNames</param> /// <returns>the file path</returns> private static string GetFilePath(FileNames fn) { string path = ""; // stores the path // determines the file if (fn == FileNames.Rotors) { path = FILE_PATH[0]; } else if (fn == FileNames.Output) { path = FILE_PATH[2]; } else { path = FILE_PATH[1]; } return(path); // returns the file }
private XDocument LoadFromStarterPack(string baseDir, string fileName) { var name = $"{baseDir}{fileName}.xml"; ViewModels.MainWindow.Trace.Add(new ViewModels.TraceItem() { Msg = $"Loading {name}" }); XDocument doc = null; try { doc = XDocument.Load($"{baseDir}{fileName}.xml"); FileNames.Add(fileName); doc.Changed += (s, e) => IsDirty = true; } catch (Exception ex) { } return(doc); }
/// <summary> /// Shows the dialog to the user. /// </summary> /// <param name="owner">The window that owns this dialog.</param> public async Task <DialogResult> ShowDialog(Form owner) { var dialog = new Modern.WindowKit.Controls.SaveFileDialog { DefaultExtension = DefaultExtension, Directory = InitialDirectory, InitialFileName = FileName, Title = Title, Filters = filters }; var file = await dialog.ShowAsync(owner.window); FileNames.Clear(); if (file is not null) { FileNames.Add(file); } return(FileNames.Count > 0 ? DialogResult.OK : DialogResult.Cancel); }
/// <summary> /// Shows the dialog to the user. /// </summary> /// <param name="owner">The window that owns this dialog.</param> public async Task <DialogResult> ShowDialog(Form owner) { var dialog = new Modern.WindowKit.Controls.OpenFileDialog { AllowMultiple = AllowMultiple, Directory = InitialDirectory, InitialFileName = FileName, Title = Title, Filters = filters }; var files = await dialog.ShowAsync(owner.window); FileNames.Clear(); if (files?.Any() == true) { FileNames.AddRange(files.Select(f => Path.GetFullPath(f))); } return(FileNames.Count > 0 ? DialogResult.OK : DialogResult.Cancel); }
public async Task <DialogResult> ShowDialog(Window window) { var dialog = new Avalonia.Controls.SaveFileDialog { DefaultExtension = DefaultExtension, Directory = InitialDirectory, InitialFileName = FileName, Title = Title, Filters = filters }; var file = await dialog.ShowAsync(window.window); FileNames.Clear(); if (file != null) { FileNames.Add(file); } return(FileNames.Count > 0 ? DialogResult.OK : DialogResult.Cancel); }
protected void OrderFiles(IEnumerable <T> files) { // ReSharper disable once PossibleMultipleEnumeration FileNames = GetFileNames(files).Where(FileIsImage).OrderBy(c => c).ToArray(); OrderedFileNames = PageOrderMode switch { MainViewModel.PageOrder.Natural => GetFileNames(files) .Where(FileIsImage) .OrderBy(ef => ef, new NaturalSortComparer()) .ToArray(), MainViewModel.PageOrder.Modified => OrderFilesByDateModified(files).Where(FileIsImage).ToArray(), MainViewModel.PageOrder.Ordinal => FileNames.ToArray(), _ => throw new ArgumentOutOfRangeException() }; OrderedShortNames = OrderedFileNames.Select(fn => GetShortName(this is FolderContainer ? ContainerPath : null, fn)).ToArray(); foreach (var pageTag in Item.PageTags) { var index = Array.IndexOf(OrderedShortNames, pageTag.FileName); pageTag.Page = index == -1 ? -1 : index + 1; } }
private void EnsureStream(FileNames file) { if (!streamWriters.ContainsKey(file)) { StreamWriter sw = File.AppendText(file.ToString() + ".log"); lock (sw) { streamWriters[file] = sw; sw.WriteLine(""); sw.WriteLine(""); sw.WriteLine(""); sw.WriteLine(""); sw.WriteLine(""); sw.WriteLine("[" + DateTime.Now.ToString() + "]"); sw.WriteLine("----------------------------------------------------------" + " Session Started " + "----------------------------------------------------------"); sw.WriteLine(""); } } }
public void ExportFileSystem(string fileName) { using (var fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { using (var writer = new BinaryWriter(fStream)) { var count = FileNames.Count; writer.Write(count); var entries = FileNames .Select(x => x.Replace('\\', '/')) .Distinct() .Select(x => new { Hash = x.GetXeHash(), Name = x, Data = Encoding.UTF8.GetBytes(x) }) .OrderBy(x => x.Hash); foreach (var item in entries) { writer.Write(item.Hash); } int offset = 4 + count * 8; foreach (var item in entries) { writer.Write(offset); offset += item.Data.Length + 1; } foreach (var item in entries) { writer.Write(item.Data); writer.Write('\0'); } } } }
/// <summary> /// Get the specific response directory from the <see cref="Response"/> message. /// </summary> private async Task <string> GetResponseDirectory(string aId) { string result = string.Empty; string responseFileName = FileNames.ResponseFilePath(aId); for (int i = 0; i < 10; i++) { var response = JsonHelper.FromFile <Response>(responseFileName); if (response != null && response.Id == aId) { result = response.Directory; FileHelper.DeleteWithLock(responseFileName); break; } await Task.Delay(1000); } return(result); }
private void OnClick(object sender, EventArgs e) { using (System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog()) { ofd.AddExtension = true; ofd.Filter = FilterString; ofd.Multiselect = IsMultiselect; if (ofd.ShowDialog() != DialogResult.OK) { IsFileNameValid = false; } else { FileName = ofd.FileName; IsFileNameValid = true; foreach (string fileName in ofd.FileNames) { FileNames.Add(fileName); } } } }
/// <summary> /// This saves the license in the proper location. /// </summary> /// <param name="licenseFile">The license file to save.</param> /// <param name="key">The encryption key to verify the license.</param> /// <param name="useIsolatedStorage">Save to IsolatedStorage if true if saving in the application data path causes an exception.</param> /// <param name="appDataFilePath">The application data file path.</param> private void Save (LicenseFile licenseFile, RSACryptoServiceProvider key, bool useIsolatedStorage, string appDataFilePath) { Debug.WriteLine("OpenLicenseProvider: Save Function"); try { using (Stream fileStream = FileNames.CreateLicenseFileStream(FileMode.Create, FileAccess.Write, FileShare.Write)) licenseFile.SaveFile(fileStream, key); } catch (Exception ex) { if (!useIsolatedStorage) { throw new LicenseFileException(Resources.ErrStr_SaveLicense_UnableToSaveLicense + ex.Message); } } if (useIsolatedStorage) { using (Stream writer = IsolatedStorageAccess.CreateIsolatedStorageLicenseStream(FileMode.Create)) licenseFile.SaveFile(writer, key); } }
internal OrchestratedBatchSignInput(string outputPath, Dictionary <string, SignInfo> fileSignDataMap, IEnumerable <string> externalFileNames, string publishUri) { OutputPath = outputPath; PublishUri = publishUri; // Use order by to make the output of this tool as predictable as possible. var fileNames = fileSignDataMap.Keys; FileNames = fileNames.OrderBy(x => x).Select(x => new FileName(outputPath, x)).ToImmutableArray(); ExternalFileNames = externalFileNames.OrderBy(x => x).ToImmutableArray(); AssemblyNames = FileNames.Where(x => x.IsAssembly).ToImmutableArray(); ZipContainerNames = FileNames.Where(x => x.IsZipContainer).ToImmutableArray(); OtherNames = FileNames.Where(x => !x.IsAssembly && !x.IsZipContainer).ToImmutableArray(); var builder = ImmutableDictionary.CreateBuilder <FileName, FileSignInfo>(); foreach (var name in FileNames) { var data = fileSignDataMap[name.RelativePath]; builder.Add(name, new FileSignInfo(name, data)); } FileSignInfoMap = builder.ToImmutable(); }
public void UnloadData() { if (SelectedIndex >= 0 && SelectedIndex < Sessions.Count()) { if (savedframedetailIndex != -1 && savedframedetailIndex > SelectedIndex) { displayedIndex--; savedframedetailIndex--; } else if (savedframedetailIndex == SelectedIndex) { displayedIndex = -1; savedframedetailIndex = -1; } CsvPaths.RemoveAt(SelectedIndex); Sessions.RemoveAt(SelectedIndex); FileNames.RemoveAt(SelectedIndex); frameRanges.RemoveAt(SelectedIndex); SelectedIndex = -1; UpdateGraphs(); UpdateColorIdentifier(); } }
public void Build() { OnProgress?.Invoke($"Building {Project.Name}...", 0, 1, false); Log.Message($"Processing {Project.Name} - Developed by {Project.Producer}"); Log.Message($"Version {Project.Version}"); Log.Message($"{Project.Copyright} {Project.Year}"); var entries = Project.GetFiles() .Select(x => new Entry() { Project = Project, ProjectFile = x }) .ToList(); FileNames.Clear(); #if true //DEBUG int filesProcessed = 0; int filesCount = entries.Count; foreach (var entry in entries) { OnProgress?.Invoke($"Processing {entry.ProjectFile.Name}...", filesProcessed, filesCount, false); ProcessEntry(entry, OutputFolder); OnProgress?.Invoke($"Processed {entry.ProjectFile.Name}!", filesProcessed, filesCount, false); } OnProgress?.Invoke($"Build completed.", 1, 1, true); #else var dispatcher = new Dispatcher <Entry>(entries); dispatcher.Process((e) => ProcessEntryAsync(e, OutputFolder)); OnProgress?.Invoke($"Build completed in {dispatcher.ElapsedMilliseconds / 1000.0} seconds.", 1, 1, true); #endif var fileSystemName = Path.Combine(OutputFolder, Path.Combine("data", "filesystem.bin")); ExportFileSystem(fileSystemName); }
public ExtractCommand() { this.Name = GlobalConstants.ExtractName; this.Description = GlobalConstants.ExtractDescription; var sourceApimName = this.Option("--sourceApimName <sourceApimName>", "Source API Management name", CommandOptionType.SingleValue); var destinationAPIManagementName = this.Option("--destinationApimName <destinationApimName>", "Destination API Management name", CommandOptionType.SingleValue); var resourceGroupName = this.Option("--resourceGroup <resourceGroup>", "Resource Group name", CommandOptionType.SingleValue); var fileFolderName = this.Option("--fileFolder <filefolder>", "ARM Template files folder", CommandOptionType.SingleValue); var apiName = this.Option("--apiName <apiName>", "API name", CommandOptionType.SingleValue); var linkedTemplatesBaseUrlName = this.Option("--linkedTemplatesBaseUrl <linkedTemplatesBaseUrl>", "Creates a master template with links", CommandOptionType.SingleValue); var policyXMLBaseUrlName = this.Option("--policyXMLBaseUrl <policyXMLBaseUrl>", "Writes policies to local XML files that require deployment to remote folder", CommandOptionType.SingleValue); this.HelpOption(); this.OnExecute(async() => { try { if (!sourceApimName.HasValue()) { throw new Exception("Missing parameter <sourceApimName>."); } if (!destinationAPIManagementName.HasValue()) { throw new Exception("Missing parameter <destinationApimName>."); } if (!resourceGroupName.HasValue()) { throw new Exception("Missing parameter <resourceGroup>."); } if (!fileFolderName.HasValue()) { throw new Exception("Missing parameter <filefolder>."); } // isolate cli parameters string resourceGroup = resourceGroupName.Values[0].ToString(); string sourceApim = sourceApimName.Values[0].ToString(); string destinationApim = destinationAPIManagementName.Values[0].ToString(); string fileFolder = fileFolderName.Values[0].ToString(); string linkedBaseUrl = linkedTemplatesBaseUrlName.HasValue() ? linkedTemplatesBaseUrlName.Value().ToString() : null; string policyXMLBaseUrl = policyXMLBaseUrlName.HasValue() ? policyXMLBaseUrlName.Value().ToString() : null; string singleApiName = null; if (apiName.Values.Count > 0) { singleApiName = apiName.Values[0].ToString(); } Console.WriteLine("API Management Template"); Console.WriteLine(); Console.WriteLine("Connecting to {0} API Management Service on {1} Resource Group ...", sourceApim, resourceGroup); if (singleApiName != null) { Console.WriteLine("Executing extraction for {0} API ...", singleApiName); } else { Console.WriteLine("Executing full extraction ...", singleApiName); } // initialize file helper classes FileWriter fileWriter = new FileWriter(); FileNameGenerator fileNameGenerator = new FileNameGenerator(); FileNames fileNames = fileNameGenerator.GenerateFileNames(sourceApim); // initialize entity extractor classes APIExtractor apiExtractor = new APIExtractor(fileWriter); APIVersionSetExtractor apiVersionSetExtractor = new APIVersionSetExtractor(); AuthorizationServerExtractor authorizationServerExtractor = new AuthorizationServerExtractor(); BackendExtractor backendExtractor = new BackendExtractor(); LoggerExtractor loggerExtractor = new LoggerExtractor(); PropertyExtractor propertyExtractor = new PropertyExtractor(); ProductExtractor productExtractor = new ProductExtractor(fileWriter); MasterTemplateExtractor masterTemplateExtractor = new MasterTemplateExtractor(); // extract templates from apim service Template apiTemplate = await apiExtractor.GenerateAPIsARMTemplateAsync(sourceApim, resourceGroup, singleApiName, policyXMLBaseUrl, fileFolder); List <TemplateResource> apiTemplateResources = apiTemplate.resources.ToList(); Template apiVersionSetTemplate = await apiVersionSetExtractor.GenerateAPIVersionSetsARMTemplateAsync(sourceApim, resourceGroup, singleApiName, apiTemplateResources, policyXMLBaseUrl); Template authorizationServerTemplate = await authorizationServerExtractor.GenerateAuthorizationServersARMTemplateAsync(sourceApim, resourceGroup, singleApiName, apiTemplateResources, policyXMLBaseUrl); Template loggerTemplate = await loggerExtractor.GenerateLoggerTemplateAsync(sourceApim, resourceGroup, singleApiName, apiTemplateResources, policyXMLBaseUrl); Template productTemplate = await productExtractor.GenerateProductsARMTemplateAsync(sourceApim, resourceGroup, singleApiName, apiTemplateResources, policyXMLBaseUrl, fileFolder); Template namedValueTemplate = await propertyExtractor.GenerateNamedValuesTemplateAsync(sourceApim, resourceGroup, singleApiName, apiTemplateResources, policyXMLBaseUrl); List <TemplateResource> namedValueResources = namedValueTemplate.resources.ToList(); Template backendTemplate = await backendExtractor.GenerateBackendsARMTemplateAsync(sourceApim, resourceGroup, singleApiName, apiTemplateResources, namedValueResources, policyXMLBaseUrl); // create parameters file Template templateParameters = masterTemplateExtractor.CreateMasterTemplateParameterValues(destinationApim, linkedBaseUrl, policyXMLBaseUrl); // write templates to output file location string apiFileName = fileNameGenerator.GenerateExtractorAPIFileName(singleApiName, sourceApim); fileWriter.WriteJSONToFile(apiTemplate, String.Concat(@fileFolder, apiFileName)); fileWriter.WriteJSONToFile(apiVersionSetTemplate, String.Concat(@fileFolder, fileNames.apiVersionSets)); fileWriter.WriteJSONToFile(authorizationServerTemplate, String.Concat(@fileFolder, fileNames.authorizationServers)); fileWriter.WriteJSONToFile(backendTemplate, String.Concat(@fileFolder, fileNames.backends)); fileWriter.WriteJSONToFile(loggerTemplate, String.Concat(@fileFolder, fileNames.loggers)); fileWriter.WriteJSONToFile(namedValueTemplate, String.Concat(@fileFolder, fileNames.namedValues)); fileWriter.WriteJSONToFile(productTemplate, String.Concat(@fileFolder, fileNames.products)); if (linkedBaseUrl != null) { // create a master template that links to all other templates Template masterTemplate = masterTemplateExtractor.GenerateLinkedMasterTemplate(apiTemplate, apiVersionSetTemplate, productTemplate, loggerTemplate, backendTemplate, authorizationServerTemplate, namedValueTemplate, fileNames, apiFileName, policyXMLBaseUrl); fileWriter.WriteJSONToFile(masterTemplate, String.Concat(@fileFolder, fileNames.linkedMaster)); } // write parameters to outputLocation fileWriter.WriteJSONToFile(templateParameters, String.Concat(fileFolder, fileNames.parameters)); Console.WriteLine("Templates written to output location"); Console.WriteLine("Press any key to exit process:"); #if DEBUG Console.ReadKey(); #endif } catch (Exception ex) { Console.WriteLine("Error occured: " + ex.Message); throw; } }); }
public CreateCommand() { this.Name = GlobalConstants.CreateName; this.Description = GlobalConstants.CreateDescription; // list command options CommandOption configFile = this.Option("--configFile <configFile>", "Config YAML file location", CommandOptionType.SingleValue).IsRequired(); this.HelpOption(); this.OnExecute(async() => { // convert config file to CreatorConfig class FileReader fileReader = new FileReader(); CreatorConfig creatorConfig = await fileReader.ConvertConfigYAMLToCreatorConfigAsync(configFile.Value()); // validate creator config CreatorConfigurationValidator creatorConfigurationValidator = new CreatorConfigurationValidator(this); bool isValidCreatorConfig = creatorConfigurationValidator.ValidateCreatorConfig(creatorConfig); if (isValidCreatorConfig == true) { // required parameters have been supplied // initialize file helper classes FileWriter fileWriter = new FileWriter(); FileNameGenerator fileNameGenerator = new FileNameGenerator(); FileNames fileNames = creatorConfig.baseFileName == null ? fileNameGenerator.GenerateFileNames(creatorConfig.apimServiceName) : fileNameGenerator.GenerateFileNames(creatorConfig.baseFileName); // initialize template creator classes APIVersionSetTemplateCreator apiVersionSetTemplateCreator = new APIVersionSetTemplateCreator(); LoggerTemplateCreator loggerTemplateCreator = new LoggerTemplateCreator(); BackendTemplateCreator backendTemplateCreator = new BackendTemplateCreator(); AuthorizationServerTemplateCreator authorizationServerTemplateCreator = new AuthorizationServerTemplateCreator(); ProductAPITemplateCreator productAPITemplateCreator = new ProductAPITemplateCreator(); TagAPITemplateCreator tagAPITemplateCreator = new TagAPITemplateCreator(); PolicyTemplateCreator policyTemplateCreator = new PolicyTemplateCreator(fileReader); ProductGroupTemplateCreator productGroupTemplateCreator = new ProductGroupTemplateCreator(); DiagnosticTemplateCreator diagnosticTemplateCreator = new DiagnosticTemplateCreator(); ReleaseTemplateCreator releaseTemplateCreator = new ReleaseTemplateCreator(); ProductTemplateCreator productTemplateCreator = new ProductTemplateCreator(policyTemplateCreator, productGroupTemplateCreator); PropertyTemplateCreator propertyTemplateCreator = new PropertyTemplateCreator(); TagTemplateCreator tagTemplateCreator = new TagTemplateCreator(); APITemplateCreator apiTemplateCreator = new APITemplateCreator(fileReader, policyTemplateCreator, productAPITemplateCreator, tagAPITemplateCreator, diagnosticTemplateCreator, releaseTemplateCreator); MasterTemplateCreator masterTemplateCreator = new MasterTemplateCreator(); // create templates from provided configuration Console.WriteLine("Creating global service policy template"); Console.WriteLine("------------------------------------------"); Template globalServicePolicyTemplate = creatorConfig.policy != null ? policyTemplateCreator.CreateGlobalServicePolicyTemplate(creatorConfig) : null; Console.WriteLine("Creating API version set template"); Console.WriteLine("------------------------------------------"); Template apiVersionSetsTemplate = creatorConfig.apiVersionSets != null ? apiVersionSetTemplateCreator.CreateAPIVersionSetTemplate(creatorConfig) : null; Console.WriteLine("Creating product template"); Console.WriteLine("------------------------------------------"); Template productsTemplate = creatorConfig.products != null ? productTemplateCreator.CreateProductTemplate(creatorConfig) : null; Console.WriteLine("Creating named values template"); Console.WriteLine("------------------------------------------"); Template propertyTemplate = creatorConfig.namedValues != null ? propertyTemplateCreator.CreatePropertyTemplate(creatorConfig) : null; Console.WriteLine("Creating logger template"); Console.WriteLine("------------------------------------------"); Template loggersTemplate = creatorConfig.loggers != null ? loggerTemplateCreator.CreateLoggerTemplate(creatorConfig) : null; Console.WriteLine("Creating backend template"); Console.WriteLine("------------------------------------------"); Template backendsTemplate = creatorConfig.backends != null ? backendTemplateCreator.CreateBackendTemplate(creatorConfig) : null; Console.WriteLine("Creating authorization server template"); Console.WriteLine("------------------------------------------"); Template authorizationServersTemplate = creatorConfig.authorizationServers != null ? authorizationServerTemplateCreator.CreateAuthorizationServerTemplate(creatorConfig) : null; // store name and whether the api will depend on the version set template each api necessary to build linked templates List <LinkedMasterTemplateAPIInformation> apiInformation = new List <LinkedMasterTemplateAPIInformation>(); List <Template> apiTemplates = new List <Template>(); Console.WriteLine("Creating API templates"); Console.WriteLine("------------------------------------------"); foreach (APIConfig api in creatorConfig.apis) { // create api templates from provided api config - if the api config contains a supplied apiVersion, split the templates into 2 for metadata and swagger content, otherwise create a unified template List <Template> apiTemplateSet = await apiTemplateCreator.CreateAPITemplatesAsync(api); apiTemplates.AddRange(apiTemplateSet); // create the relevant info that will be needed to properly link to the api template(s) from the master template apiInformation.Add(new LinkedMasterTemplateAPIInformation() { name = api.name, isSplit = apiTemplateCreator.isSplitAPI(api), dependsOnGlobalServicePolicies = creatorConfig.policy != null, dependsOnVersionSets = api.apiVersionSetId != null, dependsOnProducts = api.products != null, dependsOnTags = api.tags != null, dependsOnLoggers = await masterTemplateCreator.DetermineIfAPIDependsOnLoggerAsync(api, fileReader), dependsOnAuthorizationServers = api.authenticationSettings != null && api.authenticationSettings.oAuth2 != null && api.authenticationSettings.oAuth2.authorizationServerId != null, dependsOnBackends = await masterTemplateCreator.DetermineIfAPIDependsOnBackendAsync(api, fileReader) }); } Console.WriteLine("Creating tag template"); Console.WriteLine("------------------------------------------"); Template tagTemplate = creatorConfig.tags != null ? tagTemplateCreator.CreateTagTemplate(creatorConfig) : null; // create parameters file Template templateParameters = masterTemplateCreator.CreateMasterTemplateParameterValues(creatorConfig); // write templates to outputLocation if (creatorConfig.linked == true) { // create linked master template Template masterTemplate = masterTemplateCreator.CreateLinkedMasterTemplate(creatorConfig, globalServicePolicyTemplate, apiVersionSetsTemplate, productsTemplate, propertyTemplate, loggersTemplate, backendsTemplate, authorizationServersTemplate, tagTemplate, apiInformation, fileNames, creatorConfig.apimServiceName, fileNameGenerator); fileWriter.WriteJSONToFile(masterTemplate, String.Concat(creatorConfig.outputLocation, fileNames.linkedMaster)); } foreach (Template apiTemplate in apiTemplates) { APITemplateResource apiResource = apiTemplate.resources.FirstOrDefault(resource => resource.type == ResourceTypeConstants.API) as APITemplateResource; APIConfig providedAPIConfiguration = creatorConfig.apis.FirstOrDefault(api => string.Compare(apiResource.name, APITemplateCreator.MakeResourceName(api), true) == 0); // if the api version is not null the api is split into multiple templates. If the template is split and the content value has been set, then the template is for a subsequent api string apiFileName = fileNameGenerator.GenerateCreatorAPIFileName(providedAPIConfiguration.name, apiTemplateCreator.isSplitAPI(providedAPIConfiguration), apiResource.properties.value != null); fileWriter.WriteJSONToFile(apiTemplate, String.Concat(creatorConfig.outputLocation, apiFileName)); } if (globalServicePolicyTemplate != null) { fileWriter.WriteJSONToFile(globalServicePolicyTemplate, String.Concat(creatorConfig.outputLocation, fileNames.globalServicePolicy)); } if (apiVersionSetsTemplate != null) { fileWriter.WriteJSONToFile(apiVersionSetsTemplate, String.Concat(creatorConfig.outputLocation, fileNames.apiVersionSets)); } if (productsTemplate != null) { fileWriter.WriteJSONToFile(productsTemplate, String.Concat(creatorConfig.outputLocation, fileNames.products)); } if (propertyTemplate != null) { fileWriter.WriteJSONToFile(propertyTemplate, String.Concat(creatorConfig.outputLocation, fileNames.namedValues)); } if (loggersTemplate != null) { fileWriter.WriteJSONToFile(loggersTemplate, String.Concat(creatorConfig.outputLocation, fileNames.loggers)); } if (backendsTemplate != null) { fileWriter.WriteJSONToFile(backendsTemplate, String.Concat(creatorConfig.outputLocation, fileNames.backends)); } if (authorizationServersTemplate != null) { fileWriter.WriteJSONToFile(authorizationServersTemplate, String.Concat(creatorConfig.outputLocation, fileNames.authorizationServers)); } if (tagTemplate != null) { fileWriter.WriteJSONToFile(tagTemplate, String.Concat(creatorConfig.outputLocation, fileNames.tags)); } // write parameters to outputLocation fileWriter.WriteJSONToFile(templateParameters, String.Concat(creatorConfig.outputLocation, fileNames.parameters)); Console.WriteLine("Templates written to output location"); } return(0); }); }
public int IndexOf(string filePath) { return(FileNames.IndexOf(filePath)); }
/// <summary> /// Reads data from file to collection. /// </summary> /// <param name="fileName">File name in the file system to read from.</param> /// <returns>ICollection<string> collection of lines in the file.</returns> public ICollection<string> ReadFromFile(FileNames fileName) { ICollection<string> textLines = File.ReadAllLines(string.Format(TxtFilePath, fileName)); return textLines; }
public bool Contains(string filePath) { return(FileNames.Contains(filePath)); }
/// <summary> /// Start a test run request. /// </summary> public async Task StartTestRunAsync(RunRequest aRequest, string aRevitVersion, Action <ProcessResult> aCallback, CancellationToken aCancellationToken) { aRequest.Timestamp = DateTime.Now; aRequest.Id = GenerateId(); aRequest.ClientName = mClientName; aRequest.ClientVersion = mClientVersion; var revit = RevitHelper.StartRevit(aRevitVersion); bool isRunnerAvailable = await IsRunnerAvailable(aCancellationToken); if (isRunnerAvailable) { string requestFilePath = FileNames.RunRequestFilePath(aRequest.Id); JsonHelper.ToFile(requestFilePath, aRequest); var responseDirectoryPath = await GetResponseDirectory(aRequest.Id); if (Directory.Exists(responseDirectoryPath)) { bool run = true; while (run && !aCancellationToken.IsCancellationRequested) { var runResult = JsonHelper.FromFile <RunResult>(Path.Combine(responseDirectoryPath, FileNames.RunResult)); if (runResult != null) { bool isCompleted = runResult.State == TestState.Passed || runResult.State == TestState.Failed; ProcessResult result = new ProcessResult(runResult, isCompleted); aCallback(result); run = !isCompleted; if (run) { await Task.Delay(500, aCancellationToken); } } } } else { FileHelper.DeleteWithLock(requestFilePath); aCallback(new ProcessResult(null, true) { Message = "Tests not executed! Service may not be running." }); } if (revit.IsNew) { RevitHelper.KillRevit(revit.ProcessId); } } else { aCallback(new ProcessResult(null, true) { Message = "Runner not available!" }); } }
private void UpdateURLs(ref JArray jSource) { foreach (JObject jObj in jSource) { try { JToken oContentID; //Empty PreRequisites should be handled by the Client; Fix after 1.6.2.14! //try //{ // if (jObj["PreRequisites"] == null) // { // string[] oReq = new string[0]; // jObj.Add("PreRequisites", JToken.FromObject(oReq)); // } // if (!jObj["PreRequisites"].HasValues) // { // string[] oReq = new string[0]; // jObj["PreRequisites"] = JToken.FromObject(oReq); // } //} //catch { } try { jObj["Manufacturer"] = Base.clean(jObj["Manufacturer"].Value <string>()); jObj["ProductName"] = Base.clean(jObj["ProductName"].Value <string>()); jObj["ProductVersion"] = Base.clean(jObj["ProductVersion"].Value <string>()); } catch { } if (jObj.TryGetValue("ContentID", out oContentID)) { string sContentID = oContentID.Value <string>(); List <string> FileNames = new List <string>(); if (_cache.TryGetValue("files-" + sContentID, out FileNames)) { } else { FileNames = new List <string>(); //No need to load blob if local content exists... if (!Directory.Exists(Path.Combine(Settings["content"], sContentID))) { CloudBlobContainer oRepoContainer = new CloudBlobContainer(new Uri(Settings["contURL"] + "?" + Settings["contSAS"])); var oDir = oRepoContainer.GetDirectoryReference(sContentID); foreach (CloudBlockBlob oItem in oDir.ListBlobsSegmentedAsync(new BlobContinuationToken()).Result.Results) { FileNames.Add(Path.GetFileName(oItem.Name.ToLower())); } var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(SlidingExpiration)); //cache hash for x Seconds _cache.Set("files-" + sContentID, FileNames, cacheEntryOptions); } } foreach (JObject oFiles in jObj["Files"]) { //Skip blob if local content folder exists string sContentPath = Path.Combine(Settings["content"], sContentID); if (File.Exists(Path.Combine(sContentPath, oFiles["FileName"].Value <string>()))) { string sBase = Base.localURL; if (Environment.GetEnvironmentVariable("localURL") != null) { sBase = Environment.GetEnvironmentVariable("localURL"); //If hosted in a container, the localURL represensts the server URL } oFiles["URL"] = sBase + "/rest/v2/GetFile/" + oContentID + "/" + oFiles["FileName"].ToString().Replace("\\", "/"); continue; } if (FileNames.Contains(oFiles["FileName"].Value <string>().ToLower())) { //oFiles["URL"] = Base.localURL + "/rest/v2/GetFile/" + sContentID + "/" + oFiles["FileName"].ToString().Replace("\\", "/"); oFiles["URL"] = "https://cdn.ruckzuck.tools/rest/v2/GetFile/" + sContentID + "/" + oFiles["FileName"].ToString().Replace("\\", "/"); } } } else { continue; } } catch { } } }
IEnumerator IEnumerable.GetEnumerator() { return(FileNames.GetEnumerator()); }
/// <summary>Return our input filenames</summary> public IEnumerable <string> GetReferencedFileNames() { return(FileNames.Select(f => f.Trim())); }
public CreateCommand() { this.Name = GlobalConstants.CreateName; this.Description = GlobalConstants.CreateDescription; CommandOption appInsightsInstrumentationKey = this.Option("--appInsightsInstrumentationKey <appInsightsInstrumentationKey>", "AppInsights intrumentationkey", CommandOptionType.SingleValue); CommandOption appInsightsName = this.Option("--appInsightsName <appInsightsName>", "AppInsights Name", CommandOptionType.SingleValue); // Allow Named values to pass as parameters CommandOption namedValueKeys = this.Option("--namedValues <namedValues>", "Named Values", CommandOptionType.SingleValue); // apimNameValue values to pass as parameters CommandOption apimNameValue = this.Option("--apimNameValue <apimNameValue>", "Apim Name Value", CommandOptionType.SingleValue); // list command options CommandOption configFile = this.Option("--configFile <configFile>", "Config YAML file location", CommandOptionType.SingleValue).IsRequired(); // list command options CommandOption backendurlconfigFile = this.Option("--backendurlconfigFile <backendurlconfigFile>", "backend url json file location", CommandOptionType.SingleValue); // command options CommandOption preferredAPIsForDeployment = this.Option("--preferredAPIsForDeployment <preferredAPIsForDeployment>", "create ARM templates for the given APIs Name(comma separated) else leave this parameter blank then by default all api's will be considered", CommandOptionType.SingleValue); this.HelpOption(); this.OnExecute(async() => { // convert config file to CreatorConfig class FileReader fileReader = new FileReader(); bool considerAllApiForDeployments = true; string[] preferredApis = null; GlobalConstants.CommandStartDateTime = DateTime.Now.ToString("MMyyyydd hh mm ss"); CreatorConfig creatorConfig = await fileReader.ConvertConfigYAMLToCreatorConfigAsync(configFile.Value()); if (apimNameValue != null && !string.IsNullOrEmpty(apimNameValue.Value())) { creatorConfig.apimServiceName = apimNameValue.Value(); } AppInsightsUpdater appInsightsUpdater = new AppInsightsUpdater(); appInsightsUpdater.UpdateAppInsightNameAndInstrumentationKey(creatorConfig, appInsightsInstrumentationKey, appInsightsName); // Overwrite named values from build pipeline NamedValuesUpdater namedValuesUpdater = new NamedValuesUpdater(); namedValuesUpdater.UpdateNamedValueInstances(creatorConfig, namedValueKeys); // validate creator config CreatorConfigurationValidator creatorConfigurationValidator = new CreatorConfigurationValidator(this); //if preferredAPIsForDeployment passed as parameter if (preferredAPIsForDeployment != null && !string.IsNullOrEmpty(preferredAPIsForDeployment.Value())) { considerAllApiForDeployments = false; preferredApis = preferredAPIsForDeployment.Value().Split(","); } //if backendurlfile passed as parameter if (backendurlconfigFile != null && !string.IsNullOrEmpty(backendurlconfigFile.Value())) { CreatorApiBackendUrlUpdater creatorApiBackendUrlUpdater = new CreatorApiBackendUrlUpdater(); creatorConfig = creatorApiBackendUrlUpdater.UpdateBackendServiceUrl(backendurlconfigFile.Value(), creatorConfig); } bool isValidCreatorConfig = creatorConfigurationValidator.ValidateCreatorConfig(creatorConfig); if (isValidCreatorConfig == true) { // required parameters have been supplied // initialize file helper classes FileWriter fileWriter = new FileWriter(); FileNameGenerator fileNameGenerator = new FileNameGenerator(); FileNames fileNames = creatorConfig.baseFileName == null ? fileNameGenerator.GenerateFileNames(creatorConfig.apimServiceName) : fileNameGenerator.GenerateFileNames(creatorConfig.baseFileName); // initialize template creator classes APIVersionSetTemplateCreator apiVersionSetTemplateCreator = new APIVersionSetTemplateCreator(); LoggerTemplateCreator loggerTemplateCreator = new LoggerTemplateCreator(); BackendTemplateCreator backendTemplateCreator = new BackendTemplateCreator(); AuthorizationServerTemplateCreator authorizationServerTemplateCreator = new AuthorizationServerTemplateCreator(); ProductAPITemplateCreator productAPITemplateCreator = new ProductAPITemplateCreator(); TagAPITemplateCreator tagAPITemplateCreator = new TagAPITemplateCreator(); PolicyTemplateCreator policyTemplateCreator = new PolicyTemplateCreator(fileReader); ProductGroupTemplateCreator productGroupTemplateCreator = new ProductGroupTemplateCreator(); SubscriptionTemplateCreator productSubscriptionsTemplateCreator = new SubscriptionTemplateCreator(); DiagnosticTemplateCreator diagnosticTemplateCreator = new DiagnosticTemplateCreator(); ReleaseTemplateCreator releaseTemplateCreator = new ReleaseTemplateCreator(); ProductTemplateCreator productTemplateCreator = new ProductTemplateCreator(policyTemplateCreator, productGroupTemplateCreator, productSubscriptionsTemplateCreator); PropertyTemplateCreator propertyTemplateCreator = new PropertyTemplateCreator(); TagTemplateCreator tagTemplateCreator = new TagTemplateCreator(); APITemplateCreator apiTemplateCreator = new APITemplateCreator(fileReader, policyTemplateCreator, tagAPITemplateCreator, diagnosticTemplateCreator, releaseTemplateCreator); MasterTemplateCreator masterTemplateCreator = new MasterTemplateCreator(); // create templates from provided configuration Console.WriteLine("Creating global service policy template"); Console.WriteLine("------------------------------------------"); Template globalServicePolicyTemplate = creatorConfig.policy != null ? policyTemplateCreator.CreateGlobalServicePolicyTemplate(creatorConfig) : null; Console.WriteLine("Creating API version set template"); Console.WriteLine("------------------------------------------"); Template apiVersionSetsTemplate = creatorConfig.apiVersionSets != null ? apiVersionSetTemplateCreator.CreateAPIVersionSetTemplate(creatorConfig) : null; Console.WriteLine("Creating product template"); Console.WriteLine("------------------------------------------"); Template productsTemplate = creatorConfig.products != null ? productTemplateCreator.CreateProductTemplate(creatorConfig) : null; Console.WriteLine("Creating product/APIs template"); Console.WriteLine("------------------------------------------"); Template productAPIsTemplate = (creatorConfig.products != null && creatorConfig.apis != null) ? productAPITemplateCreator.CreateProductAPITemplate(creatorConfig) : null; Console.WriteLine("Creating named values template"); Console.WriteLine("------------------------------------------"); Template propertyTemplate = creatorConfig.namedValues != null ? propertyTemplateCreator.CreatePropertyTemplate(creatorConfig) : null; Console.WriteLine("Creating logger template"); Console.WriteLine("------------------------------------------"); Template loggersTemplate = creatorConfig.loggers != null ? loggerTemplateCreator.CreateLoggerTemplate(creatorConfig) : null; Console.WriteLine("Creating backend template"); Console.WriteLine("------------------------------------------"); Template backendsTemplate = creatorConfig.backends != null ? backendTemplateCreator.CreateBackendTemplate(creatorConfig) : null; Console.WriteLine("Creating authorization server template"); Console.WriteLine("------------------------------------------"); Template authorizationServersTemplate = creatorConfig.authorizationServers != null ? authorizationServerTemplateCreator.CreateAuthorizationServerTemplate(creatorConfig) : null; // store name and whether the api will depend on the version set template each api necessary to build linked templates List <LinkedMasterTemplateAPIInformation> apiInformation = new List <LinkedMasterTemplateAPIInformation>(); List <Template> apiTemplates = new List <Template>(); Console.WriteLine("Creating API templates"); Console.WriteLine("------------------------------------------"); foreach (APIConfig api in creatorConfig.apis) { if (considerAllApiForDeployments || preferredApis.Contains(api.name)) { // create api templates from provided api config - if the api config contains a supplied apiVersion, split the templates into 2 for metadata and swagger content, otherwise create a unified template List <Template> apiTemplateSet = await apiTemplateCreator.CreateAPITemplatesAsync(api); apiTemplates.AddRange(apiTemplateSet); // create the relevant info that will be needed to properly link to the api template(s) from the master template apiInformation.Add(new LinkedMasterTemplateAPIInformation() { name = api.name, isSplit = apiTemplateCreator.isSplitAPI(api), dependsOnGlobalServicePolicies = creatorConfig.policy != null, dependsOnVersionSets = api.apiVersionSetId != null, dependsOnProducts = api.products != null, dependsOnTags = api.tags != null, dependsOnLoggers = await masterTemplateCreator.DetermineIfAPIDependsOnLoggerAsync(api, fileReader), dependsOnAuthorizationServers = api.authenticationSettings != null && api.authenticationSettings.oAuth2 != null && api.authenticationSettings.oAuth2.authorizationServerId != null, dependsOnBackends = await masterTemplateCreator.DetermineIfAPIDependsOnBackendAsync(api, fileReader) }); } } Console.WriteLine("Creating tag template"); Console.WriteLine("------------------------------------------"); Template tagTemplate = creatorConfig.tags != null ? tagTemplateCreator.CreateTagTemplate(creatorConfig) : null; // create parameters file Template templateParameters = masterTemplateCreator.CreateMasterTemplateParameterValues(creatorConfig); // write templates to outputLocation if (creatorConfig.linked == true) { // create linked master template Template masterTemplate = masterTemplateCreator.CreateLinkedMasterTemplate(creatorConfig, globalServicePolicyTemplate, apiVersionSetsTemplate, productsTemplate, productAPIsTemplate, propertyTemplate, loggersTemplate, backendsTemplate, authorizationServersTemplate, tagTemplate, apiInformation, fileNames, creatorConfig.apimServiceName, fileNameGenerator); fileWriter.WriteJSONToFile(masterTemplate, String.Concat(creatorConfig.outputLocation, fileNames.linkedMaster)); } foreach (Template apiTemplate in apiTemplates) { APITemplateResource apiResource = apiTemplate.resources.FirstOrDefault(resource => resource.type == ResourceTypeConstants.API) as APITemplateResource; APIConfig providedAPIConfiguration = creatorConfig.apis.FirstOrDefault(api => string.Compare(apiResource.name, APITemplateCreator.MakeResourceName(api), true) == 0); // if the api version is not null the api is split into multiple templates. If the template is split and the content value has been set, then the template is for a subsequent api string apiFileName = fileNameGenerator.GenerateCreatorAPIFileName(providedAPIConfiguration.name, apiTemplateCreator.isSplitAPI(providedAPIConfiguration), apiResource.properties.value != null); fileWriter.WriteJSONToFile(apiTemplate, String.Concat(creatorConfig.outputLocation, apiFileName)); } if (globalServicePolicyTemplate != null) { fileWriter.WriteJSONToFile(globalServicePolicyTemplate, String.Concat(creatorConfig.outputLocation, fileNames.globalServicePolicy)); } if (apiVersionSetsTemplate != null) { fileWriter.WriteJSONToFile(apiVersionSetsTemplate, String.Concat(creatorConfig.outputLocation, fileNames.apiVersionSets)); } if (productsTemplate != null) { fileWriter.WriteJSONToFile(productsTemplate, String.Concat(creatorConfig.outputLocation, fileNames.products)); } if (productAPIsTemplate != null) { fileWriter.WriteJSONToFile(productAPIsTemplate, String.Concat(creatorConfig.outputLocation, fileNames.productAPIs)); } if (propertyTemplate != null) { fileWriter.WriteJSONToFile(propertyTemplate, String.Concat(creatorConfig.outputLocation, fileNames.namedValues)); } if (loggersTemplate != null) { fileWriter.WriteJSONToFile(loggersTemplate, String.Concat(creatorConfig.outputLocation, fileNames.loggers)); } if (backendsTemplate != null) { fileWriter.WriteJSONToFile(backendsTemplate, String.Concat(creatorConfig.outputLocation, fileNames.backends)); } if (authorizationServersTemplate != null) { fileWriter.WriteJSONToFile(authorizationServersTemplate, String.Concat(creatorConfig.outputLocation, fileNames.authorizationServers)); } if (tagTemplate != null) { fileWriter.WriteJSONToFile(tagTemplate, String.Concat(creatorConfig.outputLocation, fileNames.tags)); } // write parameters to outputLocation fileWriter.WriteJSONToFile(templateParameters, String.Concat(creatorConfig.outputLocation, fileNames.parameters)); Console.WriteLine("Templates written to output location"); } return(0); }); }
public IEnumerator <string> GetEnumerator() { return(FileNames.GetEnumerator()); }