private static void CompressFolder(string absolutePath, ZipArchive zipArchive, int folderOffset) { var files = C1Directory.GetFiles(absolutePath); foreach (string filename in files) { try { using (var streamReader = File.OpenRead(filename)) { var fi = new FileInfo(filename); var entryName = filename.Remove(0, folderOffset); var zipEntry = zipArchive.CreateEntry(entryName, CompressionLevel.Fastest); zipEntry.LastWriteTime = fi.LastWriteTime; using (var stream = zipEntry.Open()) { streamReader.CopyTo(stream, 4096); } } } catch (IOException) { } } var folders = C1Directory.GetDirectories(absolutePath); foreach (var folder in folders) { CompressFolder(folder, zipArchive, folderOffset); } }
protected void Page_Load(object sender, EventArgs e) { var xsdFiles = C1Directory.GetFiles(this.MapPath(""), "*.xsd"); XElement xsdFilesTable = new XElement("table", new XElement("tr", new XElement("td", "Namespace"), new XElement("td", "Last generated"))); foreach (string xsdFile in xsdFiles) { DateTime lastWrite = C1File.GetLastWriteTime(xsdFile); XDocument schemaDocument = XDocumentUtils.Load(xsdFile); string targetNamespace = schemaDocument.Root.Attribute("targetNamespace").Value; xsdFilesTable.Add( new XElement("tr", new XElement("td", new XElement("a", new XAttribute("href", Path.GetFileName(xsdFile)), targetNamespace)), new XElement("td", lastWrite))); } XsdTable.Controls.Add(new LiteralControl(xsdFilesTable.ToString())); GenerateButton.Click += new EventHandler(GenerateButton_Click); }
private IEnumerable <WebsiteFolder> GetFoldersOnPath(string parentPath, SearchToken searchToken) { IEnumerable <WebsiteFolder> folders = from folderPath in C1Directory.GetDirectories(parentPath) orderby folderPath select new WebsiteFolder(folderPath); if (searchToken.IsValidKeyword()) { folders = from folder in folders where folder.FolderName.ToLowerInvariant().Contains(searchToken.Keyword.ToLowerInvariant()) select folder; } if (string.IsNullOrEmpty(_folderWhiteListKeyName) == false) { List <IFolderWhiteList> whiteList = DataFacade.GetData <IFolderWhiteList>().Where(f => f.KeyName == _folderWhiteListKeyName).ToList(); folders = from folder in folders.ToList() where whiteList.Any(f => folder.FullPath.StartsWith(f.GetFullPath()) || f.GetFullPath().StartsWith(folder.FullPath)) select folder; } return(folders); }
private static void Initialize() { if (_dataTypeDescriptorCache != null) { return; } lock (_lock) { _dataTypeDescriptorCache = new Dictionary <Guid, DataTypeDescriptor>(); _dataTypeDescriptorFilesnamesCache = new Dictionary <Guid, string>(); string[] filepaths = C1Directory.GetFiles(_metaDataPath, "*.xml"); foreach (string filepath in filepaths) { var dataTypeDescriptor = LoadFromFile(filepath); Verify.That(!_dataTypeDescriptorCache.ContainsKey(dataTypeDescriptor.DataTypeId), "Data type with id '{0}' is already added. File: '{1}'", dataTypeDescriptor.DataTypeId, filepath); _dataTypeDescriptorCache.Add(dataTypeDescriptor.DataTypeId, dataTypeDescriptor); _dataTypeDescriptorFilesnamesCache.Add(dataTypeDescriptor.DataTypeId, filepath); } } }
public IDataProvider Assemble(IBuilderContext context, DataProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { MediaArchiveDataProviderData configuration = objectConfiguration as MediaArchiveDataProviderData; if (configuration == null) { throw new ArgumentException("Expected configuration to be of type MediaFileDataProviderData", "objectConfiguration"); } string resolvedRootDirectory = PathUtil.Resolve(configuration.RootDirectory); if (C1Directory.Exists(resolvedRootDirectory) == false) { string directoryNotFoundMsg = string.Format("Directory '{0}' not found", configuration.RootDirectory); throw new ConfigurationErrorsException(directoryNotFoundMsg, configuration.ElementInformation.Source, configuration.ElementInformation.LineNumber); } if (resolvedRootDirectory.EndsWith("\\")) { resolvedRootDirectory = Path.GetDirectoryName(resolvedRootDirectory); } string[] excludedDirs; if (configuration.ExcludedDirectories == null) { excludedDirs = new string[0]; } else { excludedDirs = configuration.ExcludedDirectories.Split(';'); } return(new FileSystemMediaFileProvider(resolvedRootDirectory, excludedDirs, configuration.StoreId, configuration.StoreDescription, configuration.StoreTitle)); }
private static void MoveRenderingLayoutToFormsFolder(string baseFolder) { var layoutsFolder = Path.Combine(baseFolder, "FormRenderingLayouts"); if (!C1Directory.Exists(layoutsFolder)) { return; } foreach (var file in C1Directory.GetFiles(layoutsFolder, "*.xml")) { var fileName = Path.GetFileNameWithoutExtension(file); if (fileName == null) { continue; } var folder = Path.Combine(baseFolder, fileName); if (!C1Directory.Exists(folder)) { C1Directory.CreateDirectory(folder); } var newFilePath = Path.Combine(folder, "RenderingLayout.xml"); File.Move(file, newFilePath); } C1Directory.Delete(layoutsFolder); }
private void FolderExists(object sender, ConditionalEventArgs e) { string currentPath = GetCurrentPath(); string newFolderName = this.GetBinding <string>("NewFolderName"); e.Result = C1Directory.Exists(Path.Combine(currentPath, newFolderName)); }
/// <summary> /// Gets the Composite.Generated assembly from the "~/Bin" folder /// </summary> /// <exclude /> public static Assembly GetGeneratedAssemblyFromBin() { foreach (string binFilePath in C1Directory.GetFiles(PathUtil.Resolve(GlobalSettingsFacade.BinDirectory), "*.dll")) { string assemblyFileName = Path.GetFileName(binFilePath); if (assemblyFileName.IndexOf(CodeGenerationManager.CompositeGeneratedFileName, StringComparison.OrdinalIgnoreCase) < 0) { continue; } try { return(Assembly.LoadFrom(binFilePath)); } catch (Exception ex) { if (!_compositeGeneratedErrorLogged) { Log.LogInformation(LogTitle, "Failed to load ~/Bin/Composite.Generated.dll "); Log.LogWarning(LogTitle, ex); _compositeGeneratedErrorLogged = true; } } } return(null); }
static CodeGenerationManager() { string assemblyTempPath = null; try { assemblyTempPath = PathUtil.Resolve(GlobalSettingsFacade.GeneratedAssembliesDirectory); } catch { // NOTE: We don't want this static constructor fail if GlobalSettingsFacade failed to load. } if (assemblyTempPath != null) { if (!C1Directory.Exists(assemblyTempPath)) { C1Directory.CreateDirectory(assemblyTempPath); } } GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); GlobalEventSystemFacade.SubscribeToShutDownEvent(args => ClearOldTempFiles()); }
public IPageTemplateProvider Assemble(Microsoft.Practices.ObjectBuilder.IBuilderContext context, PageTemplateProviderData objectConfiguration, Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = objectConfiguration as MasterPagePageTemplateProviderData; if (data == null) { throw new ArgumentException("Expected configuration to be of type " + typeof(MasterPagePageTemplateProviderAssembler).Name, "objectConfiguration"); } Type addNewTemplateWorkflow = null; if (!string.IsNullOrEmpty(data.AddNewTemplateWorkflow)) { try { addNewTemplateWorkflow = TypeManager.GetType(data.AddNewTemplateWorkflow); } catch (Exception ex) { Log.LogError(this.GetType().FullName, ex); } } string folderPath = PathUtil.Resolve(data.Directory); if (!C1Directory.Exists(folderPath)) { throw new ConfigurationErrorsException("Folder '{0}' does not exists".FormatWith(folderPath), objectConfiguration.ElementInformation.Source, objectConfiguration.ElementInformation.LineNumber); } return(new MasterPagePageTemplateProvider(data.Name, data.Directory, data.AddNewTemplateLabel, addNewTemplateWorkflow)); }
public override IEnumerable <XElement> Install() { if (_files == null && _directories == null) { throw new InvalidOperationException(GetType().Name + " has not been validated"); } if (_files != null) { foreach (var file in _files) { C1File.Delete(file); } } if (_directories != null) { foreach (var directory in _directories) { C1Directory.Delete(directory, true); } } return(Configuration); }
private void SaveTypesCache(List <AssemblyInfo> cachedTypesInfo) { SubscribedTypesCache root = null; if (cachedTypesInfo.Count > 0) { root = new SubscribedTypesCache { Assemblies = cachedTypesInfo.ToArray() }; } try { if (root == null) { File.Delete(CacheFilePath); } else { if (!C1Directory.Exists(CacheDirectoryPath)) { C1Directory.CreateDirectory(CacheDirectoryPath); } using (var fileStream = File.Open(CacheFilePath, FileMode.Create)) { GetSerializer().Serialize(fileStream, root); } } } catch (UnauthorizedAccessException) { Log.LogWarning(LogTitle, "Failed to open file '{0}'".FormatWith(CacheFilePath)); } }
private IEnumerable <PackageFragmentValidationResult> LoadPackageFragmentInstallerBinaries() { string binariesDirectory = Path.Combine(this.PackageInstallationDirectory, PackageSystemSettings.BinariesDirectoryName); if (!C1Directory.Exists(binariesDirectory)) { yield break; } foreach (string filename in C1Directory.GetFiles(binariesDirectory)) { string newFilename = Path.Combine(this.TempDirectory, Path.GetFileName(filename)); C1File.Copy(filename, newFilename); Log.LogVerbose("PackageUninstaller", "Loading package uninstaller fragment assembly '{0}'", newFilename); Exception exception = null; try { PackageAssemblyHandler.AddAssembly(newFilename); } catch (Exception ex) { exception = ex; } if (exception != null) { yield return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, exception)); } } }
private IEnumerable <PackageFragmentValidationResult> FinalizeProcess() { try { if (_packageInstallDirectory != null && (_preUninstallValidationResult == null || _preUninstallValidationResult.Count == 0) && (_validationResult == null || _validationResult.Count == 0) && (_uninstallationResult == null || _uninstallationResult.Count == 0)) { if (C1Directory.Exists(_packageInstallDirectory)) { C1Directory.Delete(_packageInstallDirectory, true); } Log.LogInformation(LogTitle, "Package successfully uninstalled"); } return(new List <PackageFragmentValidationResult>()); } catch (Exception ex) { return(new List <PackageFragmentValidationResult> { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex) }); } }
private void SaveTypesCache(List <AssemblyInfo> cachedTypesInfo) { SubscribedTypesCache root = null; if (cachedTypesInfo.Count > 0) { root = new SubscribedTypesCache { Assemblies = cachedTypesInfo.ToArray() }; } try { if (root == null) { File.Delete(CacheFilePath); } else { if (!C1Directory.Exists(CacheDirectoryPath)) { C1Directory.CreateDirectory(CacheDirectoryPath); } using (var fileStream = File.Open(CacheFilePath, FileMode.Create)) { GetSerializer().Serialize(fileStream, root); } } } catch (Exception) { Log.LogWarning(LogTitle, $"Failed to open file '{CacheFilePath}' for writing - this may lead to slower start up times, if this issue persist. In that case, check that this file is accessible to the web application for writes."); } }
internal static Dictionary <Guid, string> GetInstalledPackages() { var result = new Dictionary <Guid, string>(); string baseDirectory = PathUtil.Resolve(GlobalSettingsFacade.PackageDirectory); if (!C1Directory.Exists(baseDirectory)) { return(result); } string[] packageDirectories = C1Directory.GetDirectories(baseDirectory); foreach (string packageDirecoty in packageDirectories) { if (C1File.Exists(Path.Combine(packageDirecoty, PackageSystemSettings.InstalledFilename))) { string filename = Path.Combine(packageDirecoty, PackageSystemSettings.PackageInformationFilename); if (C1File.Exists(filename)) { string path = packageDirecoty.Remove(0, baseDirectory.Length); if (path.StartsWith("\\")) { path = path.Remove(0, 1); } Guid id = new Guid(path); result.Add(id, filename); } } } return(result); }
private void DeleteOldWorkflows() { using (GlobalInitializerFacade.CoreIsInitializedScope) { foreach (string filename in C1Directory.GetFiles(SerializedWorkflowsDirectory)) { DateTime creationTime = C1File.GetLastWriteTime(filename); if (DateTime.Now.Subtract(creationTime) > OldFileExistenceTimeout) { Guid instanceId = new Guid(Path.GetFileNameWithoutExtension(filename)); if (Path.GetExtension(filename) == "bin") { try { WorkflowRuntime.GetWorkflow(instanceId); AbortWorkflow(instanceId); } catch (Exception) { } } C1File.Delete(filename); Log.LogVerbose(LogTitle, $"Old workflow instance file deleted {filename}"); } } } }
public void Delete(IEnumerable <DataSourceId> dataSourceIds) { foreach (DataSourceId dataSourceId in dataSourceIds) { if (dataSourceId == null) { throw new ArgumentException("DataSourceIds must me non-null"); } } foreach (DataSourceId dataSourceId in dataSourceIds) { MediaDataId dataId = dataSourceId.DataId as MediaDataId; if (dataId.MediaType == _fileType) { if (IsReadOnlyFolder(dataId.Path)) { throw new ArgumentException("Cannot delete read only file " + dataId.FileName); } C1File.Delete(GetAbsolutePath(dataId)); } else { if (IsReadOnlyFolder(dataId.Path)) { throw new ArgumentException("Cannot delete read only folder " + dataId.Path); } C1Directory.Delete(GetAbsolutePath(dataId), true); } } }
public IEnumerable <EntityToken> GetParents(EntityToken entityToken) { WebsiteFileElementProviderEntityToken castedEntityToken = (WebsiteFileElementProviderEntityToken)entityToken; if ((C1File.Exists(castedEntityToken.Path) == false) && (C1Directory.Exists(castedEntityToken.Path) == false)) { return(null); } string newFolderPath = Path.GetDirectoryName(castedEntityToken.Path); string rootFolder = castedEntityToken.RootPath; if (newFolderPath != rootFolder) { Verify.That(newFolderPath.Length > rootFolder.Length, "File/folder path '{0}' does not much root folder '{1}'", newFolderPath, rootFolder); return(new EntityToken[] { new WebsiteFileElementProviderEntityToken(castedEntityToken.Source, newFolderPath, castedEntityToken.RootPath) }); } return(new EntityToken[] { new WebsiteFileElementProviderRootEntityToken(castedEntityToken.Source, castedEntityToken.RootPath) }); }
public static PackageLicenseDefinition[] GetLicenseDefinitions(Guid productId) { var result = new List <PackageLicenseDefinition>(); foreach (var file in C1Directory.GetFiles(_packageLicenseDirectory, "*" + LicenseFileExtension, SearchOption.TopDirectoryOnly)) { var license = TryLoadLicenseFile(file); if (license != null && license.ProductId == productId) { result.Add(license); } } string obsoloteFilename = GetObsoleteLicenseFilename(productId); if (C1File.Exists(obsoloteFilename)) { var license = TryLoadLicenseFile(obsoloteFilename); if (license != null) { if (license.ProductId == productId) { result.Add(license); } else { Log.LogError(LogTitle, "The license for the product '{0}' does not match the product in the license file '{1}'", productId, license.ProductId); } } } return(result.ToArray()); }
private IQueryable <T> GetFiles <T>() where T : class, IData { var result = from file in C1Directory.GetFiles(_resolvedRootDirectory, _fileSearchPattern, _fileSearchOptions) select BuildNewFileSystemFile <T>(file); return(result.AsQueryable()); }
/// <exclude /> public static string CreateTempDirectory() { string directory = Path.Combine(TempDirectoryPath, UrlUtils.CompressGuid(Guid.NewGuid())); C1Directory.CreateDirectory(directory); return(directory); }
/// <summary> /// Used for processing xml/sql data providers configuration build by C1 vesrion older than 3.0 /// </summary> internal static Dictionary <string, Guid> GetTypeManagerTypeNameToTypeIdMap() { string metaDataFolderPath = PathUtil.Resolve(GlobalSettingsFacade.DataMetaDataDirectory); List <string> filepaths = C1Directory.GetFiles(metaDataFolderPath, "*.xml").ToList(); var result = new Dictionary <string, Guid>(); foreach (string filepath in filepaths) { try { XDocument doc = XDocumentUtils.Load(filepath); XAttribute dataTypeIdAttr = doc.Root.Attribute("dataTypeId"); XAttribute typeManagerTypeNameAttr = doc.Root.Attribute("typeManagerTypeName"); if (dataTypeIdAttr == null || typeManagerTypeNameAttr == null) { continue; } string typeManagerTypeName = typeManagerTypeNameAttr.Value; Guid dataTypeId = new Guid(dataTypeIdAttr.Value); const string redundantSuffix = ",Composite.Generated"; if (typeManagerTypeName.EndsWith(redundantSuffix, StringComparison.OrdinalIgnoreCase)) { typeManagerTypeName = typeManagerTypeName.Substring(0, typeManagerTypeName.Length - redundantSuffix.Length); } if (!result.ContainsKey(typeManagerTypeName)) { result.Add(typeManagerTypeName, dataTypeId); } if (!typeManagerTypeName.Contains(",") && !typeManagerTypeName.StartsWith("DynamicType:")) { string fixedTypeManagerTypeName = "DynamicType:" + typeManagerTypeName; if (!result.ContainsKey(fixedTypeManagerTypeName)) { result.Add(fixedTypeManagerTypeName, dataTypeId); } } } catch (Exception ex) { Log.LogWarning(LogTitle, "Error while parsing meta data file '{0}'".FormatWith(filepath)); Log.LogWarning(LogTitle, ex); } } // Backward compatibility for configuraiton files. (Breaking change C1 3.2 -> C1 4.0) result["Composite.Data.Types.IPageTemplate,Composite"] = new Guid("7b54d7d2-6be6-48a6-9ae1-2e0373073d1d"); return(result); }
public static void ClearCache(string renderingMode) { var folder = GetCacheFolder(renderingMode); if (C1Directory.Exists(folder)) { Task.Run(() => ClearCacheInt(folder)); } }
/// <exclude /> public static void OnApplicationStart() { string tempDirectoryName = TempDirectoryPath; if (!C1Directory.Exists(tempDirectoryName)) { C1Directory.CreateDirectory(tempDirectoryName); } }
static ModelsFacade() { Providers = CompositionContainerFacade.GetExportedValues <IModelsProvider>().ToList(); if (!C1Directory.Exists(RootPath)) { C1Directory.CreateDirectory(RootPath); } }
/// <summary> /// Renders a url and return a full path to a rendered image, or <value>null</value> when rendering process is failing or inaccessible. /// </summary> public static async Task <RenderingResult> RenderUrlAsync(HttpContext context, string url, string mode) { string dropFolder = GetCacheFolder(mode); if (!C1Directory.Exists(dropFolder)) { C1Directory.CreateDirectory(dropFolder); } string urlHash = Convert.ToBase64String(BitConverter.GetBytes(url.GetHashCode())).Substring(0, 6).Replace('+', '-').Replace('/', '_'); string outputImageFileName = Path.Combine(dropFolder, urlHash + ".png"); string outputFileName = Path.Combine(dropFolder, urlHash + ".output"); string redirectLogFileName = Path.Combine(dropFolder, urlHash + ".redirect"); string errorFileName = Path.Combine(dropFolder, urlHash + ".error"); if (C1File.Exists(outputImageFileName) || C1File.Exists(outputFileName)) { #if BrowserRender_NoCache File.Delete(outputFileName); #else string[] output = C1File.Exists(outputFileName) ? C1File.ReadAllLines(outputFileName) : null; return(new RenderingResult { FilePath = outputImageFileName, Output = output, Status = RenderingResultStatus.Success }); #endif } if (!Enabled) { return(null); } var result = await MakePreviewRequestAsync(context, url, outputImageFileName, mode); if (result.Status >= RenderingResultStatus.Error) { C1File.WriteAllLines(errorFileName, result.Output); } if (!Enabled) { return(null); } if (result.Status == RenderingResultStatus.Success) { C1File.WriteAllLines(outputFileName, result.Output); } else if (result.Status == RenderingResultStatus.Redirect) { C1File.WriteAllLines(redirectLogFileName, result.Output); } return(result); }
private void LoadPersistedFormData() { using (_resourceLocker.Locker) { foreach (string filename in C1Directory.GetFiles(SerializedWorkflowsDirectory, "*.xml")) { TryLoadPersistedFormData(filename); } } }
private static void Init() { if (!C1Directory.Exists(ModelsFacade.RootPath)) { C1Directory.CreateDirectory(ModelsFacade.RootPath); } MoveRenderingLayoutToFormsFolder(ModelsFacade.RootPath); MoveSubfoldersToRoot(ModelsFacade.RootPath); }
public IEnumerable <Guid> GetPersistedWorkflows() { foreach (string filePath in C1Directory.GetFiles(_baseDirectory, "*.bin")) { Guid workflowId; if (TryParseWorkflowId(filePath, out workflowId)) { yield return(workflowId); } } }