Exemplo n.º 1
0
        public static void ClearCache(string renderingMode)
        {
            var folder = GetCacheFolder(renderingMode);

            if (C1Directory.Exists(folder))
            {
                Task.Run(() => ClearCacheInt(folder));
            }
        }
Exemplo n.º 2
0
        /// <exclude />
        public static void OnApplicationStart()
        {
            string tempDirectoryName = TempDirectoryPath;

            if (!C1Directory.Exists(tempDirectoryName))
            {
                C1Directory.CreateDirectory(tempDirectoryName);
            }
        }
Exemplo n.º 3
0
        /// <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 static void Init()
        {
            if (!C1Directory.Exists(ModelsFacade.RootPath))
            {
                C1Directory.CreateDirectory(ModelsFacade.RootPath);
            }

            MoveRenderingLayoutToFormsFolder(ModelsFacade.RootPath);
            MoveSubfoldersToRoot(ModelsFacade.RootPath);
        }
        public WorkflowFacadeImpl()
        {
            string serializedWorkflowsDirectory = PathUtil.Resolve(GlobalSettingsFacade.SerializedWorkflowsDirectory);
            string parentDirectory   = Path.GetDirectoryName(serializedWorkflowsDirectory);
            string lockFileDirectory = Path.Combine(parentDirectory, "LockFiles");

            if (!C1Directory.Exists(lockFileDirectory))
            {
                C1Directory.CreateDirectory(lockFileDirectory);
            }
        }
Exemplo n.º 6
0
        public static DateTime GetLastCacheUpdateTime(string mode)
        {
            string folderPath = GetCacheFolder(mode);

            if (!C1Directory.Exists(folderPath))
            {
                C1Directory.CreateDirectory(folderPath);
            }

            return(C1Directory.GetCreationTime(folderPath));
        }
Exemplo n.º 7
0
        static LicenseDefinitionManager()
        {
            _packageLicenseDirectory = PathUtil.Resolve(GlobalSettingsFacade.PackageLicenseDirectory);

            if (!C1Directory.Exists(_packageLicenseDirectory))
            {
                C1Directory.CreateDirectory(_packageLicenseDirectory);
            }

            _maximumProductNameLength = 255 - (GlobalSettingsFacade.MaximumRootPathLength + (GlobalSettingsFacade.PackageLicenseDirectory.Length - 1) + LicenseFileExtension.Length);
        }
 static AdministrativeAuthorizationHttpModule()
 {
     if (C1Directory.Exists(HostingEnvironment.MapPath(UrlUtils.AdminRootPath)))
     {
         LoadConfiguration();
     }
     else
     {
         _allowC1ConsoleRequests = false;
     }
 }
        /// <exclude />
        public void CancelInstallation()
        {
            if (_zipFilename != null && C1File.Exists(_zipFilename))
            {
                C1File.Delete(_zipFilename);
            }

            if (C1Directory.Exists(_packageInstallDirectory))
            {
                C1Directory.Delete(_packageInstallDirectory, true);
            }
        }
Exemplo n.º 10
0
        static DataMetaDataFacade()
        {
            GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush());

            _metaDataPath = PathUtil.Resolve(GlobalSettingsFacade.DataMetaDataDirectory);
            if (!C1Directory.Exists(_metaDataPath))
            {
                C1Directory.CreateDirectory(_metaDataPath);
            }

            UpdateFilenames();
        }
Exemplo n.º 11
0
        public FileLogger(string logDirectoryPath, bool flushImmediately)
        {
            Verify.ArgumentNotNull(logDirectoryPath, "logDirectoryPath");

            _logDirectoryPath = Path.Combine(PathUtil.BaseDirectory, logDirectoryPath);
            if (!C1Directory.Exists(_logDirectoryPath))
            {
                C1Directory.CreateDirectory(_logDirectoryPath);
            }
            _flushImmediately = flushImmediately;

            TouchLockFile();
        }
Exemplo n.º 12
0
        public static IEnumerable <IPackItem> Create(EntityToken entityToken)
        {
            if (entityToken is WebsiteFileElementProviderEntityToken)
            {
                WebsiteFileElementProviderEntityToken token = (WebsiteFileElementProviderEntityToken)entityToken;
                if (C1Directory.Exists(token.Path))
                {
                    yield return(new PCDirectory(Regex.Replace(token.Id, @"^\\", "") + "\\"));

                    yield break;
                }
            }
        }
Exemplo n.º 13
0
        /// <exclude />
        public static void SetFunctinoCode(this IInlineFunction function, string content)
        {
            string directoryPath = PathUtil.Resolve(GlobalSettingsFacade.InlineCSharpFunctionDirectory);

            if (C1Directory.Exists(directoryPath) == false)
            {
                C1Directory.CreateDirectory(directoryPath);
            }

            string filepath = Path.Combine(directoryPath, function.CodePath);

            C1File.WriteAllText(filepath, content);
        }
Exemplo n.º 14
0
 private static void CreateDirectoryIfNotExists(string path)
 {
     if (!C1Directory.Exists(path))
     {
         lock (SyncRoot)
         {
             if (!C1Directory.Exists(path))
             {
                 C1Directory.CreateDirectory(path);
             }
         }
     }
 }
Exemplo n.º 15
0
        private State Initialize()
        {
            var sections = new Dictionary <string, Dictionary <CultureInfo, LocalizationFile> >();

            if (C1Directory.Exists(_directory))
            {
                foreach (string xmlFile in C1Directory.GetFiles(_directory, "*.xml", SearchOption.AllDirectories))
                {
                    // File names have format <section name>.<culture name>.xml

                    string fileName = Path.GetFileName(xmlFile);

                    fileName = fileName.Substring(0, fileName.Length - 4); // removing ".xml";

                    if (!fileName.Contains("."))
                    {
                        continue;
                    }

                    string cultureName = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1);

                    CultureInfo cultureInfo;
                    try
                    {
                        cultureInfo = CultureInfo.GetCultureInfo(cultureName);
                    }
                    catch (CultureNotFoundException)
                    {
                        Log.LogInformation(LogTitle, "Skipping file '{0}' as '{1}' is not a valid culture name",
                                           Path.GetFileName(xmlFile), cultureName);
                        continue;
                    }

                    string sectionName = fileName.Substring(0, fileName.Length - cultureName.Length - 1);

                    if (!sections.ContainsKey(sectionName))
                    {
                        sections.Add(sectionName, new Dictionary <CultureInfo, LocalizationFile>());
                    }

                    var localizationFile = new LocalizationFile(xmlFile);
                    sections[sectionName].Add(cultureInfo, localizationFile);
                }
            }

            return(new State {
                Sections = sections
            });
        }
Exemplo n.º 16
0
        /// <summary>
        /// This method is used to record the very first time the system is started.
        /// Ths time can later be used to several things like finding files that have been written to etc.
        /// </summary>
        public static void SetFirstTimeStart()
        {
            if (!C1File.Exists(FirstTimeStartFilePath))
            {
                string directory = Path.GetDirectoryName(FirstTimeStartFilePath);
                if (!C1Directory.Exists(directory))
                {
                    C1Directory.CreateDirectory(directory);
                }

                var doc = new XDocument(new XElement("Root", new XAttribute("time", DateTime.Now)));

                doc.SaveToFile(FirstTimeStartFilePath);
            }
        }
        private static void MoveSubfoldersToRoot(string rootFolder)
        {
            var formsFolder = Path.Combine(rootFolder, "Forms");

            if (C1Directory.Exists(formsFolder))
            {
                MoveSubfoldersToRoot(rootFolder, formsFolder);
            }

            var wizardsFolder = Path.Combine(rootFolder, "Wizards");

            if (C1Directory.Exists(wizardsFolder))
            {
                MoveSubfoldersToRoot(rootFolder, wizardsFolder);
            }
        }
        private void IfFeatureNameFree(object sender, System.Workflow.Activities.ConditionalEventArgs e)
        {
            string name = this.GetBinding <string>("Name");

            if (name.Length > 50)
            {
                e.Result = false;
                this.ShowFieldMessage("Name", StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "AddWorkflow.NameTooLong"));
                return;
            }

            if (!C1Directory.Exists(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory)))
            {
                try
                {
                    C1Directory.CreateDirectory(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory));
                }
                catch (Exception)
                {
                    e.Result = false;
                    this.ShowFieldMessage("Name", string.Format("Can not create directory '{0}'", GlobalSettingsFacade.PageTemplateFeaturesDirectory));
                }
            }

            string xmlFilename  = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), name + ".xml");
            string htmlFilename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), name + ".html");

            e.Result = !C1File.Exists(xmlFilename) && !C1File.Exists(htmlFilename);

            if (!e.Result)
            {
                this.ShowFieldMessage("Name", StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "AddWorkflow.NameInUse"));
                return;
            }

            try
            {
                C1File.WriteAllText(xmlFilename, "tmp");
                C1File.Delete(xmlFilename);
            }
            catch (Exception)
            {
                e.Result = false;
                this.ShowFieldMessage("Name", StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "AddWorkflow.NameNotValidInFilename"));
            }
        }
Exemplo n.º 19
0
        public ConsoleMessageQueue(int secondsForItemToLive)
        {
            string directory = PathUtil.Resolve(GlobalSettingsFacade.SerializedConsoleMessagesDirectory);

            if (!C1Directory.Exists(directory))
            {
                C1Directory.CreateDirectory(directory);
            }

            MessageQueueFilePath = Path.Combine(directory, MessageQueueFileName);

            _timeInterval = new TimeSpan(0, 0, secondsForItemToLive);

            DeserializeMessagesFromFileSystem();

            _timer = new Timer(OnWeed, null, new TimeSpan(0, 0, 0), _timeInterval);
        }
Exemplo n.º 20
0
        public FileLogger(string logDirectoryPath, bool flushImmediately)
        {
            Verify.ArgumentNotNull(logDirectoryPath, "logDirectoryPath");

            _logDirectoryPath = Path.Combine(PathUtil.BaseDirectory, logDirectoryPath);
            if (!C1Directory.Exists(_logDirectoryPath))
            {
                C1Directory.CreateDirectory(_logDirectoryPath);
            }
            _flushImmediately = flushImmediately;

            _flushOnIdleTask = Task.Factory.StartNew(FlushOnIdle);

#if UseLockFiles
            TouchLockFile();
#endif
        }
Exemplo n.º 21
0
        public IPageTemplateProvider Assemble(IBuilderContext context, PageTemplateProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
        {
            var data = objectConfiguration as MvcTemplateProviderData;

            if (data == null)
            {
                throw new ArgumentException("Expected configuration to be of type " + typeof(MvcTemplateProviderData).Name, "objectConfiguration");
            }

            var path = PathUtil.Resolve(data.Directory);

            if (!C1Directory.Exists(path))
            {
                throw new ConfigurationErrorsException(String.Format("Folder '{0}' does not exists", path), objectConfiguration.ElementInformation.Source, objectConfiguration.ElementInformation.LineNumber);
            }

            return(new MvcTemplateProvider(data.Name, data.Directory));
        }
Exemplo n.º 22
0
        internal MediaFileProvider(string rootDirectory, string storeId, string storeDescription, string storeTitle)
        {
            _workingDirectory = PathUtil.Resolve(rootDirectory);
            if (!C1Directory.Exists(_workingDirectory))
            {
                C1Directory.CreateDirectory(_workingDirectory);
            }

            _storeId          = storeId;
            _storeTitle       = storeTitle;
            _storeDescription = storeDescription;

            DataEventSystemFacade.SubscribeToStoreChanged <IMediaFileData>(ClearQueryCache, false);
            DataEventSystemFacade.SubscribeToStoreChanged <IMediaFolderData>(ClearQueryCache, false);

            _mediaUrlProvider = new DefaultMediaUrlProvider(storeId);
            MediaUrls.RegisterMediaUrlProvider(storeId, _mediaUrlProvider);
        }
Exemplo n.º 23
0
        private static XElement GetPredefinedResizingOptions()
        {
            XElement xel = HttpRuntime.Cache.Get("ResizedImageKeys") as XElement;

            //If it's not there, load the xml document and then add it to the cache
            if (xel == null)
            {
                if (_resizedImageKeysFilePath == null)
                {
                    _resizedImageKeysFilePath = PathUtil.Resolve(ResizedImageKeys);
                }

                if (!C1File.Exists(_resizedImageKeysFilePath))
                {
                    string directoryPath = Path.GetDirectoryName(_resizedImageKeysFilePath);
                    if (!C1Directory.Exists(directoryPath))
                    {
                        C1Directory.CreateDirectory(directoryPath);
                    }

                    var config = new XElement("ResizedImages",
                                              new XElement("image",
                                                           new XAttribute("name", "thumbnail"),
                                                           new XAttribute("maxwidth", "100"),
                                                           new XAttribute("maxheight", "100")),
                                              new XElement("image",
                                                           new XAttribute("name", "normal"),
                                                           new XAttribute("maxwidth", "200")),
                                              new XElement("image",
                                                           new XAttribute("name", "large"),
                                                           new XAttribute("maxheight", "300"))
                                              );

                    config.SaveToPath(_resizedImageKeysFilePath);
                }

                xel = XElementUtils.Load(_resizedImageKeysFilePath);
                var cd = new CacheDependency(_resizedImageKeysFilePath);
                var cacheExpirationTimeSpan = new TimeSpan(24, 0, 0);
                HttpRuntime.Cache.Add("ResizedImageKeys", xel, cd, Cache.NoAbsoluteExpiration, cacheExpirationTimeSpan, CacheItemPriority.Default, null);
            }

            return(xel);
        }
Exemplo n.º 24
0
        internal static void CreateStore(string providerName, DataScopeConfigurationElement scopeElement)
        {
            string filename = ResolvePath(scopeElement.Filename, providerName);

            string directoryPath = Path.GetDirectoryName(filename);

            if (!C1Directory.Exists(directoryPath))
            {
                C1Directory.CreateDirectory(directoryPath);
            }

            bool   keepExistingFile        = false;
            string rootLocalName           = XmlDataProviderDocumentWriter.GetRootElementName(scopeElement.ElementName);
            string obsoleteRootElementName = scopeElement.ElementName + "s";

            if (C1File.Exists(filename))
            {
                try
                {
                    XDocument existingDocument = XDocumentUtils.Load(filename);
                    if (existingDocument.Root.Name.LocalName == rootLocalName ||
                        existingDocument.Root.Name.LocalName == obsoleteRootElementName)
                    {
                        keepExistingFile = true;
                    }
                }
                catch (Exception)
                {
                    keepExistingFile = false;
                }

                if (!keepExistingFile)
                {
                    C1File.Delete(filename);
                }
            }

            if (!keepExistingFile)
            {
                var document = new XDocument();
                document.Add(new XElement(rootLocalName));
                XDocumentUtils.Save(document, filename);
            }
        }
Exemplo n.º 25
0
        private static void InitializeNewFile(string filepath)
        {
            _installationId = Guid.NewGuid();

            string directory = Path.GetDirectoryName(filepath);

            if (C1Directory.Exists(directory) == false)
            {
                C1Directory.CreateDirectory(directory);
            }

            XDocument doc = new XDocument(
                new XElement("InstallationInformation",
                             new XAttribute("installationId", _installationId)
                             )
                );

            doc.SaveToFile(filepath);
        }
Exemplo n.º 26
0
        public XmlLocalizationProvider(string directoryVirtualPath, CultureInfo defaultCulture)
        {
            _defaultCulture = defaultCulture;
            _directory      = PathUtil.Resolve(directoryVirtualPath);

            if (!C1Directory.Exists(_directory))
            {
                Log.LogVerbose(LogTitle, "Directory '{0}' does not exist", directoryVirtualPath);
                return;
            }

            _watcher = new C1FileSystemWatcher(_directory, "*.xml");

            _watcher.Created += (sender, args) => Reset();
            _watcher.Changed += (sender, args) => Reset();
            _watcher.Deleted += (sender, args) => Reset();

            _watcher.EnableRaisingEvents = true;
        }
        private ICollection <PackageFragmentValidationResult> FinalizeProcess(bool install)
        {
            try
            {
                if (_zipFilename != null && C1File.Exists(_zipFilename))
                {
                    C1File.Delete(_zipFilename);
                }

                Func <IList <PackageFragmentValidationResult>, bool> isNotEmpty = list => list != null && list.Count > 0;

                bool installationFailed = isNotEmpty(_preInstallValidationResult) ||
                                          isNotEmpty(_validationResult) ||
                                          isNotEmpty(_installationResult);

                if (installationFailed && C1Directory.Exists(_packageInstallDirectory))
                {
                    C1Directory.Delete(_packageInstallDirectory, true);
                }

                if (!installationFailed && install)
                {
                    Log.LogInformation(LogTitle, "Package successfully installed");

                    C1File.WriteAllText(Path.Combine(_packageInstallDirectory, PackageSystemSettings.InstalledFilename), "");

                    // Moving package files to a proper location, if an newer version of an already installed package is installed
                    if (_originalPackageInstallDirectory != null)
                    {
                        C1Directory.Delete(_originalPackageInstallDirectory, true);

                        C1Directory.Move(_packageInstallDirectory, _originalPackageInstallDirectory);
                    }
                }

                return(new PackageFragmentValidationResult[0]);
            }
            catch (Exception ex)
            {
                return(new [] { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex) });
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileRelatedDataCache{T}" /> class.
        /// </summary>
        /// <param name="cacheDirectoryName">Name of the folder to which cached files will be put.</param>
        /// <param name="cacheName">Name of the cache, used in the naming of cached files.</param>
        /// <param name="toFileSerializer">To file serializer.</param>
        /// <param name="fromFileDeserializer">From file deserializer.</param>
        public FileRelatedDataCache(string cacheDirectoryName, string cacheName, Action <CachedData, string> toFileSerializer, Func <string, CachedData> fromFileDeserializer)
        {
            _cacheName    = cacheName;
            _serializer   = toFileSerializer;
            _deserializer = fromFileDeserializer;

            string path = PathUtil.Resolve(GlobalSettingsFacade.CacheDirectory);

            if (!string.IsNullOrEmpty(cacheDirectoryName))
            {
                path = Path.Combine(path, cacheDirectoryName);
            }

            _cachefolder = path;

            if (!C1Directory.Exists(_cachefolder))
            {
                C1Directory.CreateDirectory(_cachefolder);
            }
        }
Exemplo n.º 29
0
        /// <exclude />
        public static void OnApplicationEnd()
        {
            // Deleting everything that is older than 24 hours
            string tempDirectoryName = TempDirectoryPath;

            if (!C1Directory.Exists(tempDirectoryName))
            {
                return;
            }



            foreach (string filename in C1Directory.GetFiles(tempDirectoryName))
            {
                try
                {
                    if (DateTime.Now > C1File.GetLastWriteTime(filename) + TemporaryFileExpirationTimeSpan)
                    {
                        C1File.Delete(filename);
                    }
                }
                catch
                {
                }
            }

            foreach (string directoryPath in C1Directory.GetDirectories(tempDirectoryName))
            {
                try
                {
                    if (DateTime.Now > C1Directory.GetCreationTime(directoryPath) + TemporaryFileExpirationTimeSpan)
                    {
                        C1Directory.Delete(directoryPath, true);
                    }
                }
                catch
                {
                }
            }
        }
        protected FileBasedFunctionProvider(string name, string folder)
        {
            _name = name;

            VirtualPath  = folder;
            PhysicalPath = PathUtil.Resolve(VirtualPath);

            if (!C1Directory.Exists(PhysicalPath))
            {
                return;
            }

            string folderToWatch = PhysicalPath;

            try
            {
                if (ReparsePointUtils.DirectoryIsReparsePoint(folderToWatch))
                {
                    folderToWatch = ReparsePointUtils.GetDirectoryReparsePointTarget(folderToWatch);
                }

                _watcher = new C1FileSystemWatcher(folderToWatch, "*")
                {
                    IncludeSubdirectories = true
                };

                _watcher.Created += Watcher_OnChanged;
                _watcher.Deleted += Watcher_OnChanged;
                _watcher.Changed += Watcher_OnChanged;
                _watcher.Renamed += Watcher_OnChanged;

                _watcher.EnableRaisingEvents = true;
            }
            catch (Exception ex)
            {
                Log.LogWarning(LogTitle, "Failed to create a file system watcher for path '{0}'", folderToWatch);
                Log.LogWarning(LogTitle, ex);
            }
        }