internal static Manifest GetFileManifest(FolderUri folder) { try { Manifest manifest = null; var file = new FileUri(folder.UrlFolder, "manifest.json"); if (file.FileExists) { string cacheKey = folder.UrlFolder + "manifest.json"; manifest = (Manifest)DataCache.GetCache(cacheKey); if (manifest == null) { string content = File.ReadAllText(file.PhysicalFilePath); manifest = JsonConvert.DeserializeObject <Manifest>(content); DataCache.SetCache(cacheKey, manifest, new DNNCacheDependency(file.PhysicalFilePath)); } } return(manifest); } catch (Exception ex) { Log.Logger.Error($"Failed to load manifest from folder {folder.UrlFolder}. Error: {ex}"); throw; } }
internal ReplicationFolder GetReplicationFolder(Guid storageID, string folderUrl) { if (storageID == Guid.Empty) { throw new ArgumentNullException("storageID"); } if (string.IsNullOrEmpty(folderUrl)) { throw new ArgumentNullException("folderUrl"); } ReplicationFolder replicationFolder = null; if (_replicationFolders.ContainsKey(storageID)) { Dictionary <string, ReplicationFolder> storageFolders = _replicationFolders[storageID]; FolderUri uri = new FolderUri(folderUrl); if (storageFolders.ContainsKey(uri.UrlLower)) { replicationFolder = storageFolders[uri.UrlLower]; } } return(replicationFolder); }
/// <summary> /// Возвращает папку по имени. /// </summary> /// <param name="name">Имя папки.</param> /// <param name="parentFolder">Дочерняя папка.</param> /// <returns></returns> internal Folder EnsureFolder(string name, Folder parentFolder = null) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } this.Logger.WriteFormatMessage("EnsureFolder:Начало получения папки, name: {0}", name); FolderUri folderUri; if (parentFolder != null) { folderUri = new FolderUri(name, parentFolder.Url); } else { folderUri = new FolderUri(name, null); } string key = string.Format("EnsureFolder_{0}", folderUri.Url); Folder folder = this.Cache.GetObject <Folder>(key); if (folder == null) { IFolderMetadata folderMetadata = this.MetadataAdapter.EnsureFolder(folderUri.Url); folder = new Folder(this, folderMetadata, parentFolder); this.Cache.AddObject(key, folder, EngineConsts.Lifetimes.Folder); } this.Logger.WriteFormatMessage("EnsureFolder:Окончание получения папки, name: {0}", name); return(folder); }
public static void EnableImageLoader(IImageLoaderPlatform imageLoaderPlatform) { FolderUri storageUri = _filesystem.CreateFolderUri(AppController.Globals.ImageCacheFolderPath); _imageLoader = new ImageLoader(imageLoaderPlatform, 12); _imageLoader.StorageUri = storageUri; }
public static JObject LoadLocalizationJsonV2(FolderUri templateDir, string culture) { var localizationFilename = new FileUri(templateDir, $"localization.{culture}.json"); JObject localizationJson = JsonUtils.LoadJsonFromCacheOrDisk(localizationFilename) as JObject; return(localizationJson); }
public static JObject LoadLocalizationJsonV1(FolderUri templateDir, string culture) { // try loading localization files without prefix (for backwards compatibility) var localizationFilename = new FileUri(templateDir, $"{culture}.json"); var localizationJson = JsonUtils.LoadJsonFromCacheOrDisk(localizationFilename) as JObject; return(localizationJson); }
internal static JObject GetSchemaAndOptionsJson(FolderUri desktopFolder, FolderUri portalFolder, string prefix) { JObject json = new JObject(); if (!portalFolder.FolderExists) { Directory.CreateDirectory(portalFolder.PhysicalFullDirectory); } if (!string.IsNullOrEmpty(prefix)) { prefix = prefix + "-"; } // schema string schemaFilename = portalFolder.PhysicalFullDirectory + "\\" + prefix + "schema.json"; if (!File.Exists(schemaFilename)) { schemaFilename = desktopFolder.PhysicalFullDirectory + "\\" + prefix + "schema.json"; } JObject schemaJson = JObject.Parse(File.ReadAllText(schemaFilename)); json["schema"] = schemaJson; // default options string optionsFilename = portalFolder.PhysicalFullDirectory + "\\" + prefix + "options.json"; if (!File.Exists(optionsFilename)) { optionsFilename = desktopFolder.PhysicalFullDirectory + "\\" + prefix + "options.json"; } if (File.Exists(optionsFilename)) { string fileContent = File.ReadAllText(optionsFilename); if (!string.IsNullOrWhiteSpace(fileContent)) { JObject optionsJson = JObject.Parse(fileContent); json["options"] = optionsJson; } } // language options optionsFilename = portalFolder.PhysicalFullDirectory + "\\" + prefix + "options." + DnnLanguageUtils.GetCurrentCultureCode() + ".json"; if (!File.Exists(optionsFilename)) { optionsFilename = desktopFolder.PhysicalFullDirectory + "\\" + prefix + "options." + DnnLanguageUtils.GetCurrentCultureCode() + ".json"; } if (File.Exists(optionsFilename)) { string fileContent = File.ReadAllText(optionsFilename); if (!string.IsNullOrWhiteSpace(fileContent)) { JObject optionsJson = JObject.Parse(fileContent); json["options"] = json["options"].JsonMerge(optionsJson); } } return(json); }
public static JObject LoadLocalizationJson(FolderUri templateDir, string culture) { var localizationJson = LoadLocalizationJsonV2(templateDir, culture); if (localizationJson == null) { // try loading localization files without prefix (for backwards compatibility) localizationJson = LoadLocalizationJsonV1(templateDir, culture); } return(localizationJson); }
public bool ContainsFolder(string url) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } FolderUri uri = new FolderUri(url); bool contains = this.UniqueFolders.ContainsKey(uri.UrlLower); return(contains); }
/// <summary> /// Возвращает дочернюю папку по имени. /// </summary> /// <param name="name">Имя дочерней папки.</param> /// <param name="throwIfNotExists">Выбросить исключение, если папка не существует.</param> /// <returns></returns> public IFolder GetFolder(string name, bool throwIfNotExists = true) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } FolderUri folderUri = new FolderUri(name, this.Url); IFolder folder = this.TypedStorage.GetFolderInternal(folderUri.Url, throwIfNotExists); return(folder); }
private void AddReplicationFolder(ReplicationFolder replicationFolder) { if (replicationFolder == null) { throw new ArgumentNullException("replicationFolder"); } Dictionary <string, ReplicationFolder> nodeReplicationFolders = null; bool added = false; if (!_replicationFolders.ContainsKey(replicationFolder.SourceStorage.UniqueID)) { lock (_checkReplicationFolderLocker) { if (!_replicationFolders.ContainsKey(replicationFolder.SourceStorage.UniqueID)) { nodeReplicationFolders = new Dictionary <string, ReplicationFolder>(); FolderUri uri = new FolderUri(replicationFolder.TypedFolder.Url); nodeReplicationFolders.Add(uri.UrlLower, replicationFolder); _replicationFolders.Add(replicationFolder.SourceStorage.UniqueID, nodeReplicationFolders); //запускаем поток по репликации папки this.StartFilesThread(replicationFolder); added = true; } } } if (!added) { //внутренний словарь должен был либо добавиться выше, либо уже существовать if (!_replicationFolders.ContainsKey(replicationFolder.SourceStorage.UniqueID)) { throw new Exception(string.Format("Не удалось добавить папку репликации, неизвестная ошибка.")); } nodeReplicationFolders = _replicationFolders[replicationFolder.SourceStorage.UniqueID]; FolderUri uri = new FolderUri(replicationFolder.TypedFolder.Url); if (!nodeReplicationFolders.ContainsKey(uri.UrlLower)) { lock (_checkReplicationFolderLocker) { if (!nodeReplicationFolders.ContainsKey(uri.UrlLower)) { nodeReplicationFolders.Add(uri.UrlLower, replicationFolder); this.StartFilesThread(replicationFolder); } } } } }
public void GenerateXmlDictionaries(FolderUri outputUri) { var fs = _localizatorPlatform.GetFileSystem(); if (!fs.FolderExists(outputUri)) { fs.CreateFolder(outputUri); } foreach (var a in _localizatorPlatform.GetAssemblies()) { foreach (var t in a.DefinedTypes) { if (t.BaseType == typeof(LocalizationDictionary)) { var pa = (LocalizationDictionaryAttribute)t .GetCustomAttributes(typeof(LocalizationDictionaryAttribute), true) .FirstOrDefault(); if (pa != null) { var dictionary = (LocalizationDictionary)Activator.CreateInstance(t.AsType()); XDocument xdoc = new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), new XElement("dictionary", new XAttribute("targetCulture", pa.TargetCulture), new XElement("entries", dictionary.Entries.Select( kvp => { return(new XElement("entry", new XElement("key", kvp.Key), new XElement("value", kvp.Value))); }) .ToArray()))); string dictionaryPath = String.Concat(Path.Combine(outputUri.Uri, pa.TargetCulture), ".xml"); FileUri dictionaryUri = _localizatorPlatform.GetFileSystem().CreateFileUri(dictionaryPath); if (fs.FileExists(dictionaryUri)) { fs.DeleteFile(dictionaryUri); } using (Stream s = fs.OpenFile(dictionaryUri, UniversalFileMode.CreateNew, UniversalFileAccess.Write)) xdoc.Save(s); } } } } }
internal static Manifest LoadManifestFileFromCacheOrDisk(FolderUri folder) { try { var file = new FileUri(folder, "manifest.json"); var manifest = JsonUtils.LoadJsonFileFromCacheOrDisk <Manifest>(file); return(manifest); } catch (Exception ex) { App.Services.Logger.Error($"Failed to load manifest from folder {folder.UrlFolder}. Error: {ex}"); throw; } }
private void AddWeakRelation(Guid storageID, string host, string folderUrl) { if (string.IsNullOrEmpty(folderUrl)) { throw new ArgumentNullException("folderUrl"); } if (string.IsNullOrEmpty(host)) { throw new ArgumentNullException("host"); } bool exists = false; foreach (Dictionary <string, ReplicationFolder> storageReplicationFolders in _replicationFolders.Values) { FolderUri uri = new FolderUri(folderUrl); exists = storageReplicationFolders.ContainsKey(uri.UrlLower); if (exists) { break; } } //настройка существует, но может существовать для другого узла //в таком случае нужно создать if (exists) { //но для текущего элемента схемы ее нет ReplicationFolder replicationFolder = this.GetReplicationFolder(storageID, folderUrl); lock (_updateFolderLocker) { replicationFolder = this.GetReplicationFolder(storageID, folderUrl); if (replicationFolder == null) { //создание узла для элемента схемы bool justCreated; StorageNode schemaItemNode = this.EnsureNode(storageID, host, out justCreated); bool replicationFolderJustCreated; replicationFolder = this.EnsureReplicationFolder(schemaItemNode, folderUrl, false, out replicationFolderJustCreated); } } } }
internal static Manifest GetFileManifest(FolderUri folder) { try { Manifest manifest = null; var file = new FileUri(folder.UrlFolder, "manifest.json"); if (file.FileExists) { string content = File.ReadAllText(file.PhysicalFilePath); manifest = JsonConvert.DeserializeObject <Manifest>(content); } return(manifest); } catch (Exception ex) { Log.Logger.ErrorFormat("Failed to load manifest from folder {0}. Error:{1}", folder.UrlFolder, ex.ToString()); throw ex; } }
/// <summary> /// Возвращает папку по адресу. Если папки не существует, то она будет создана. /// </summary> /// <param name="url">Адрес папки.</param> /// <returns></returns> internal Folder EnsureFolderInternal(string url) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } this.Logger.WriteFormatMessage("EnsureFolderInternal:Начало получение папки, url: {0}", url); Folder folder = null; FolderUri folderUri = new FolderUri(url); Folder rootFolder = this.EnsureFolder(folderUri.RootUri.Url, null); if (folderUri.IsRoot) { folder = rootFolder; } else { bool allChainCreated = false; FolderUri tmpFolderUri = folderUri; Folder lastCreatedFolder = rootFolder; while (!allChainCreated) { while (tmpFolderUri.ParentUri != null && tmpFolderUri.ParentUri.Url != lastCreatedFolder.Url) { tmpFolderUri = tmpFolderUri.ParentUri; } FolderUri firstNotCreatedUrl = tmpFolderUri; lastCreatedFolder = this.EnsureFolder(firstNotCreatedUrl.FolderName, lastCreatedFolder); allChainCreated = lastCreatedFolder.Url == url; tmpFolderUri = folderUri; } folder = lastCreatedFolder; } this.Logger.WriteFormatMessage("EnsureFolderInternal:Окончание получение папки, url: {0}", url); return(folder); }
/// <summary> /// Обновляет или создает новую запись в БД. /// </summary> /// <param name="folder">Метаданные папки.</param> internal void UpdateFolder(FolderMetadata folder) { if (folder == null) { throw new ArgumentNullException("folder"); } if (folder.ID == 0) { if (String.IsNullOrEmpty(folder.Url)) { throw new Exception("Не задан Url папки."); } if (!this.IsUniqueFolderUri(folder)) { throw new Exception(String.Format("Невозможно создать папку с неуникальным Url '{0}'", folder.Url)); } folder.UniqueID = Guid.NewGuid(); FolderUri urlBuilder = new FolderUri(folder.Url); folder.Name = urlBuilder.FolderName; if (urlBuilder.ParentUri != null) { FolderMetadata parentFolder = this.GetFolder(String.Format("[Url] = N'{0}'", urlBuilder.ParentUri.Url)); if (parentFolder != null) { folder.ParentID = parentFolder.ID; } } folder.ID = this.InsertObject(folder); } else { this.UpdateObject(folder); } }
/// <summary> /// Возвращает папку по адресу. /// </summary> /// <param name="url">Адрес папки.</param> /// <param name="throwIfNotExists">Выбросить исключение, если папка не существует.</param> /// <returns></returns> internal Folder GetFolderInternal(string url, bool throwIfNotExists = true) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } this.Logger.WriteFormatMessage("GetFolderInternal:Начало получения папки, url: {0}", url); //построение и обход дерева сегментов url FolderUri folderUri = new FolderUri(url); List <FolderUri> segments = new List <FolderUri>(); FolderUri tmpFolderUri = folderUri; while (tmpFolderUri != null) { segments.Add(tmpFolderUri); tmpFolderUri = tmpFolderUri.ParentUri; } //сортировка для обхода с корневой папки IOrderedEnumerable <FolderUri> sortedSegments = segments.OrderBy(s => s.Url.Length); ICollection <IFolderMetadata> foldersMetadata = this.MetadataAdapter.GetFolders(sortedSegments.Select(s => s.Url).ToArray()); Dictionary <string, IFolderMetadata> foldersMetadataByUrl = new Dictionary <string, IFolderMetadata>(); if (foldersMetadata != null) { foreach (IFolderMetadata folderMetadata in foldersMetadata) { if (!foldersMetadataByUrl.ContainsKey(folderMetadata.Url)) { foldersMetadataByUrl.Add(folderMetadata.Url.ToLower(), folderMetadata); } } } Folder resultFolder = null; Folder lastSegmentFolder = null; foreach (FolderUri segment in sortedSegments) { IFolderMetadata folderMetadata = null; string urlLower = segment.Url.ToLower(); if (foldersMetadataByUrl.ContainsKey(urlLower)) { folderMetadata = foldersMetadataByUrl[urlLower]; } //цепочка оборвалась if (folderMetadata == null) { if (throwIfNotExists) { throw new Exception(string.Format("Не удалось найти папку по адресу {0}", segment.Url)); } else { lastSegmentFolder = null; break; } } else { lastSegmentFolder = new Folder(this, folderMetadata, lastSegmentFolder); } } resultFolder = lastSegmentFolder; this.Logger.WriteFormatMessage("GetFolderInternal:Окончание получения папки, url: {0}", url); return(resultFolder); }
public FormBuilder(FolderUri templateUri) { this._templateUri = templateUri; }
/// <summary> /// Обновляет текущую схему репликацию сети, по схеме репликации другого узла сети. /// </summary> /// <param name="remoteSchema">Схема репликации другого узла сети.</param> internal void UpdateSchema(IReplicationSchema remoteSchema) { if (remoteSchema == null) { throw new ArgumentNullException("remoteSchema"); } //remote схема содержит ссылки на текущий узел bool remoteSchemaContainsCurrentStorage = false; //обновляем схему по схеме соседнего узла по следующей логике //что пришло со строгой ссылкой, то всегда создаем (значит эта настройка соседнего узла) //со слабой ссылкой создаем только папки, по которым мы пересекаемся if (remoteSchema.StrongItems != null) { foreach (IReplicationSchemaItem schemaItem in remoteSchema.StrongItems) { bool forCurrentStorage = schemaItem.StorageID == this.Engine.CurrentNode.UniqueID; if (!remoteSchemaContainsCurrentStorage) { remoteSchemaContainsCurrentStorage = forCurrentStorage; } this.UpdateSchemaItem(remoteSchema, schemaItem); } } if (remoteSchema.WeakItems != null) { foreach (IReplicationSchemaItem schemaItem in remoteSchema.WeakItems) { bool forCurrentStorage = schemaItem.StorageID == this.Engine.CurrentNode.UniqueID; if (!remoteSchemaContainsCurrentStorage) { remoteSchemaContainsCurrentStorage = forCurrentStorage; } this.UpdateSchemaItem(remoteSchema, schemaItem); } } if (remoteSchemaContainsCurrentStorage) { //схема remote узла содержит текущий узел bool justCreated; StorageNode remoteNode = this.EnsureNode(remoteSchema.StorageID, remoteSchema.Host, out justCreated); remoteNode.LastAccessTime = DateTime.Now; remoteNode.Update(); } //удаление текущий настроек по remote схеме //для этого нужно пройтись по всем настройкам схемы текущего узла для remote узла if (_replicationFolders.ContainsKey(remoteSchema.StorageID)) { #region Удаление из текущей схемы Dictionary <string, ReplicationFolder> replicationFoldersForRemoteSchema = _replicationFolders[remoteSchema.StorageID]; foreach (ReplicationFolder replicationFolder in replicationFoldersForRemoteSchema.Values) { if (replicationFolder.IsCurrentNodeSettings) { //в схеме текущего узла репликация с remote узлом задана в настройке (STRONG) //такие настройки удалять не нужно continue; } bool containsInRemoteSchema = false; FolderUri localUri = new FolderUri(replicationFolder.Folder.Url); //содержаться может и в STRONG и в WEAK виде if (remoteSchema.StrongItems != null) { foreach (IReplicationSchemaItem schemaItem in remoteSchema.StrongItems) { if (schemaItem.Folders != null) { foreach (string folderUrl in schemaItem.Folders) { FolderUri remoteUri = new FolderUri(folderUrl); if (localUri.UrlLower == remoteUri.UrlLower) { containsInRemoteSchema = true; break; } } } if (containsInRemoteSchema) { break; } } } if (!containsInRemoteSchema && remoteSchema.WeakItems != null) { foreach (IReplicationSchemaItem schemaItem in remoteSchema.WeakItems) { if (schemaItem.Folders != null) { foreach (string folderUrl in schemaItem.Folders) { FolderUri remoteUri = new FolderUri(folderUrl); if (localUri.UrlLower == remoteUri.UrlLower) { containsInRemoteSchema = true; break; } } } if (containsInRemoteSchema) { break; } } } //в remote схеме нет репликации с папками из схемы текущего узла if (!containsInRemoteSchema) { replicationFolder.Deleted = true; replicationFolder.Update(); } } #endregion } }