예제 #1
0
        /// <exclude />
        public static XslCompiledTransform GetCompiledXsltTransform(string stylesheetPath)
        {
            lock (_lock)
            {
                DateTime lastXsltFileWrite = C1File.GetLastWriteTime(stylesheetPath);

                bool compiledVersionExists = _xsltLookup.ContainsKey(stylesheetPath);
                bool reloadFresh           = (DateTime.Now - lastXsltFileWrite).Minutes < 30;

                if (compiledVersionExists == false || lastXsltFileWrite > _xsltFileTimestamps[stylesheetPath] || reloadFresh)
                {
                    XslCompiledTransform xslt = new XslCompiledTransform();
                    using (XmlReader reader = XmlReaderUtils.Create(stylesheetPath))
                    {
                        xslt.Load(reader);
                    }

                    if (compiledVersionExists)
                    {
                        _xsltLookup.Remove(stylesheetPath);
                        _xsltFileTimestamps.Remove(stylesheetPath);
                    }

                    _xsltLookup.Add(stylesheetPath, xslt);
                    _xsltFileTimestamps.Add(stylesheetPath, lastXsltFileWrite);
                }
            }

            return(_xsltLookup[stylesheetPath]);
        }
예제 #2
0
    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 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}");
                    }
                }
            }
        }
        /// <summary>
        /// Returns strings for the specified culture or null if no strings exists.
        /// </summary>
        private Dictionary <string, string> GetStringsForCulture(CultureInfo cultureInfo)
        {
            Dictionary <string, string> stringDictionary;

            using (_resourceLocker.Locker)
            {
                if (_resourceLocker.Resources.CultureFileLastUpdated.ContainsKey(cultureInfo))
                {
                    string unresolvedFileName = _resourceLocker.Resources.CultureToFileLookup[cultureInfo];
                    string resolvedFileName   = PathUtil.Resolve(unresolvedFileName);

                    DateTime lastWrite             = C1File.GetLastWriteTime(resolvedFileName);
                    double   secondsSinceLastWrite = (DateTime.Now - lastWrite).TotalSeconds;

                    if (secondsSinceLastWrite < 300 || lastWrite > _resourceLocker.Resources.CultureFileLastUpdated[cultureInfo])
                    {
                        _resourceLocker.Resources.CultureToTranslation.Remove(cultureInfo);
                        _resourceLocker.Resources.CultureFileLastUpdated[cultureInfo] = lastWrite;
                    }
                }

                if (_resourceLocker.Resources.CultureToTranslation.TryGetValue(cultureInfo, out stringDictionary) == false)
                {
                    string unresolvedFileName;
                    if (_resourceLocker.Resources.CultureToFileLookup.TryGetValue(cultureInfo, out unresolvedFileName) == false)
                    {
                        return(null);
                    }

                    string   resolvedFileName = PathUtil.Resolve(unresolvedFileName);
                    XElement strings          = XElementUtils.Load(resolvedFileName);

                    stringDictionary = new Dictionary <string, string>();

                    foreach (XElement stringElement in strings.Elements())
                    {
                        XAttribute keyAttribute   = stringElement.Attribute("key");
                        XAttribute valueAttribute = stringElement.Attribute("value");

                        if (keyAttribute != null && valueAttribute != null)
                        {
                            if (stringDictionary.ContainsKey(keyAttribute.Value))
                            {
                                throw new InvalidOperationException(string.Format("Duplicate string resource key '{0}' in XML file '{1}'", keyAttribute.Value, unresolvedFileName));
                            }
                            stringDictionary.Add(keyAttribute.Value, valueAttribute.Value);
                        }
                        else
                        {
                            LoggingService.LogError("XmlStringResourceProvider", string.Format("Invalid entry '{0}' in file '{1}'", stringElement.ToString(SaveOptions.DisableFormatting), unresolvedFileName));
                        }
                    }

                    _resourceLocker.Resources.CultureToTranslation.Add(cultureInfo, stringDictionary);
                }
            }

            return(stringDictionary);
        }
        private static void OnFileExternallyChanged(string filePath, FileChangeType changeType)
        {
            filePath = filePath.ToLowerInvariant();

            var fileRecord = _cache[filePath];

            if (fileRecord == null ||
                fileRecord.FileModificationDate == DateTime.MinValue ||
                C1File.GetLastWriteTime(filePath) == fileRecord.FileModificationDate)
            {
                // Ignoring this notification since it's very very probably caused by XmlDataProvider itself
                return;
            }

            lock (_documentEditingSyncRoot)
            {
                lock (_cacheSyncRoot)
                {
                    fileRecord = _cache[filePath];

                    if (fileRecord == null ||
                        fileRecord.FileModificationDate == DateTime.MinValue ||
                        C1File.GetLastWriteTime(filePath) == fileRecord.FileModificationDate)
                    {
                        // Ignoring this notification since it's very very probably caused by XmlDataProvider itself
                        return;
                    }

                    _cache.Remove(filePath);

                    Log.LogVerbose(LogTitle, "File '{0}' changed by another process. Flushing cache.", filePath);

                    if (_externalFileChangeActions.Any(f => f.Key == filePath))
                    {
                        var actions = _externalFileChangeActions.Where(f => f.Key == filePath).Select(f => f.Value).ToList();
                        foreach (var action in actions)
                        {
                            action.Invoke();
                        }
                    }
                    else
                    {
                        Log.LogWarning(LogTitle, "File '{0}' has not been related to a scope - unable to raise store change event", filePath);
                    }
                }
            }
        }
예제 #6
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
                {
                }
            }
        }
        public XmlStringResourceProvider(string defaultCultureName, Dictionary <CultureInfo, string> cultureToFileLookup, Dictionary <CultureInfo, bool> watchForFileChanges, string providerName)
        {
            using (_resourceLocker.Locker)
            {
                _providerName = providerName;

                _resourceLocker.Resources.DefaultCulture      = new CultureInfo(defaultCultureName);
                _resourceLocker.Resources.CultureToFileLookup = cultureToFileLookup;

                foreach (CultureInfo watchedCulture in watchForFileChanges.Where(f => f.Value).Select(f => f.Key))
                {
                    string unresolvedFileName;
                    if (_resourceLocker.Resources.CultureToFileLookup.TryGetValue(watchedCulture, out unresolvedFileName))
                    {
                        string   resolvedFileName = PathUtil.Resolve(unresolvedFileName);
                        DateTime lastWrite        = C1File.GetLastWriteTime(resolvedFileName);

                        _resourceLocker.Resources.CultureFileLastUpdated.Add(watchedCulture, lastWrite);
                    }
                }
            }
        }
예제 #8
0
        /// <summary>
        /// Add assemblies that are loaded in the app domain.
        /// </summary>
        /// <param name="compilerParameters">The compiler parameters.</param>
        /// <param name="includeAppCode">if set to <c>true</c> reference to App_Code will be included to results.</param>
        public static void AddLoadedAssemblies(this CompilerParameters compilerParameters, bool includeAppCode)
        {
            Dictionary <string, string> foundAssemblyLocations = new Dictionary <string, string>();

            IEnumerable <Assembly> assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(AssemblyHasLocation);

            if (!includeAppCode)
            {
                assemblies = assemblies.Where(asm => !asm.GetName().Name.StartsWith("App_Code"));
            }

            IEnumerable <string> locations = assemblies.Select(a => a.Location);

            foreach (string location in locations)
            {
                string locationKey = Path.GetFileName(location).ToLowerInvariant();


                if (foundAssemblyLocations.ContainsKey(locationKey) == false)
                {
                    foundAssemblyLocations.Add(locationKey, location);
                }
                else
                {
                    string currentUsedLocation = foundAssemblyLocations[locationKey];

                    DateTime currentlyUsedLastWrite     = C1File.GetLastWriteTime(currentUsedLocation);
                    DateTime locationCandidateLastWrite = C1File.GetLastWriteTime(location);

                    if (locationCandidateLastWrite > currentlyUsedLastWrite)
                    {
                        foundAssemblyLocations.Remove(locationKey);
                        foundAssemblyLocations.Add(locationKey, location);
                    }
                }
            }

            compilerParameters.ReferencedAssemblies.AddRangeIfNotContained(foundAssemblyLocations.Values);
        }
예제 #9
0
            void OnFileWatcherEvent(object sender, FileSystemEventArgs e)
            {
                FileSystemEventHandler hander = FileChangedEvent;

                if (hander != null)
                {
                    lock (_fileUpdateLock)
                    {
                        bool fileExists = true;
                        if (fileExists)
                        {
                            // Supress multiple events fireing by observing last write time
                            DateTime writeTime = C1File.GetLastWriteTime(e.FullPath);
                            if (_lastWriteHandleTime < writeTime)
                            {
                                _lastWriteHandleTime = writeTime;

                                try
                                {
                                    using (ThreadDataManager.EnsureInitialize())
                                    {
                                        hander(sender, e);
                                    }
                                }
                                catch (ThreadAbortException)
                                {
                                }
                                catch (Exception ex)
                                {
                                    Log.LogWarning(LogTitle, "Failed to reload functions on file watcher event");
                                    Log.LogError(LogTitle, ex);
                                }
                            }
                        }
                    }
                }
            }
        /// <summary>
        /// Validates that the current Composite.Generated.dll is not compiled after the given
        /// time. If it is compiled after the given time. Any attempts to recompile Composite.Generated.dll
        /// will be ignored. This is used to stop app domains from shutting each other down by recompiles.
        /// </summary>
        /// <param name="time"></param>
        internal static void ValidateCompositeGenerate(DateTime time)
        {
            if (SuppressGeneration)
            {
                return;
            }

            string filePath = Path.Combine(PathUtil.BaseDirectory, "Bin", "Composite.Generated.dll");

            if (!C1File.Exists(filePath))
            {
                return;
            }

            DateTime lastWrite = C1File.GetLastWriteTime(filePath);

            if (lastWrite <= time)
            {
                return;
            }

            _compositeGeneratedCompiled = true;
            Log.LogVerbose(LogTitle, $"Assembly in this application domain is newer than this application domain ({AppDomain.CurrentDomain.Id})");
        }
        private static StartupHandlerInfo[] GetSubscribedTypes(
            string filePath, List <AssemblyInfo> cachedTypesInfo, ref bool cacheHasBeenUpdated)
        {
            string assemblyName = Path.GetFileNameWithoutExtension(filePath);

            foreach (string assemblyToIgnore in AssembliesToIgnore)
            {
                if (assemblyName == assemblyToIgnore || assemblyName.StartsWith(assemblyToIgnore + ",") ||
                    (assemblyToIgnore.EndsWith(".") && assemblyName.StartsWith(assemblyToIgnore)))
                {
                    return(null);
                }
            }

            DateTime modificationDate = C1File.GetLastWriteTime(filePath);

            var cachedInfo = cachedTypesInfo.FirstOrDefault(asm => asm.AssemblyName == assemblyName);

            if (cachedInfo != null)
            {
                if (cachedInfo.LastModified == modificationDate)
                {
                    string[] subscribedTypesNames = cachedInfo.SubscribedTypes;
                    if (subscribedTypesNames.Length == 0)
                    {
                        return(new StartupHandlerInfo[0]);
                    }

                    var asm = Assembly.LoadFrom(filePath);
                    return((from typeName in subscribedTypesNames
                            let type = asm.GetType(typeName)
                                       where  type != null
                                       let attribute = type.GetCustomAttributes(false)
                                                       .OfType <ApplicationStartupAttribute>()
                                                       .FirstOrDefault()
                                                       where attribute != null
                                                       select new StartupHandlerInfo(type, attribute)).ToArray());
                }

                // Removing cache entry if it is obsolete
                cachedTypesInfo.Remove(cachedInfo);
            }

            Assembly assembly;

            try
            {
                assembly = Assembly.LoadFrom(filePath);
            }
            catch (ReflectionTypeLoadException ex)
            {
                Log.LogWarning(LogTitle, "Failed to load assembly '{0}'".FormatWith(filePath));
                if (ex.LoaderExceptions != null && ex.LoaderExceptions.Length > 0)
                {
                    Log.LogError(LogTitle, ex.LoaderExceptions[0]);
                }

                return(null);
            }

            if (!AssemblyFacade.AssemblyPotentiallyUsesType(assembly, typeof(ApplicationStartupAttribute)))
            {
                return(null);
            }

            Type[] types;

            if (!TryGetTypes(assembly, out types))
            {
                return(new StartupHandlerInfo[0]);
            }

            var result = GetSubscribedTypes(types);

            var newCacheEntry = new AssemblyInfo
            {
                AssemblyName    = assembly.GetName().Name,
                LastModified    = modificationDate,
                SubscribedTypes = result.Select(sh => sh.Type.FullName).ToArray()
            };

            cachedTypesInfo.Add(newCacheEntry);

            cacheHasBeenUpdated = true;

            return(result);
        }
        private static void DoSave(FileRecord fileRecord)
        {
            var root      = new XElement(GetRootElementName(fileRecord.ElementName));
            var xDocument = new XDocument(root);

            var recordSet = fileRecord.RecordSet;
            var elements  = new List <XElement>(recordSet.Index.GetValues());

            Func <IEnumerable <XElement>, IOrderedEnumerable <XElement> > orderer;

            if (TryGetFileOrderer(out orderer, fileRecord.FilePath))
            {
                var orderedElements = orderer(elements);

                orderedElements.ForEach(root.Add);
            }
            else
            {
                elements.ForEach(root.Add);
            }

            Exception thrownException = null;

            // Writing the file in the "catch" block in order to prevent chance of corrupting the file by experiencing ThreadAbortException.
            try
            {
            }
            finally
            {
                try
                {
                    // Saving to temp file and file move to prevent broken saves
                    var xmlWriterSettings = new XmlWriterSettings
                    {
                        CheckCharacters = false,
                        Indent          = true
                    };

                    using (XmlWriter xmlWriter = XmlWriter.Create(fileRecord.TempFilePath, xmlWriterSettings))
                    {
                        xDocument.Save(xmlWriter);
                    }
                    Thread.Sleep(_fileIoDelay);

                    bool      failed        = true;
                    Exception lastException = null;
                    for (int i = 0; i < NumberOfRetries; i++)
                    {
                        DateTime lastSuccessfulFileChange = fileRecord.FileModificationDate;
                        try
                        {
                            fileRecord.FileModificationDate = DateTime.MinValue;
                            File.Copy(fileRecord.TempFilePath, fileRecord.FilePath, true);
                            failed = false;
                            break;
                        }
                        catch (Exception ex)
                        {
                            fileRecord.FileModificationDate = lastSuccessfulFileChange;
                            lastException = ex;
                            Thread.Sleep(10 * (i + 1));
                        }
                    }

                    if (!failed)
                    {
                        Thread.Sleep(_fileIoDelay);
                        File.Delete(fileRecord.TempFilePath);
                    }
                    else
                    {
                        Log.LogCritical(LogTitle, "Failed deleting the file: " + fileRecord.FilePath);
                        if (lastException != null)
                        {
                            throw lastException;
                        }

                        throw new InvalidOperationException("Failed to delete a file, this code shouldn't be reachable");
                    }

                    fileRecord.FileModificationDate = C1File.GetLastWriteTime(fileRecord.FilePath);
                }
                catch (Exception exception)
                {
                    thrownException = exception;
                }
            }
            // ThreadAbortException should have a higher priority, and therefore we're doing rethrow in a separate block
            if (thrownException != null)
            {
                throw thrownException;
            }
        }
        private static Type[] GetSubscribedTypes(string filePath, List <AssemblyInfo> cachedTypesInfo, ref bool cacheHasBeenUpdated)
        {
            string assemblyName = Path.GetFileNameWithoutExtension(filePath);

            foreach (string assemblyToIgnore in AssembliesToIgnore)
            {
                if (assemblyName == assemblyToIgnore || assemblyName.StartsWith(assemblyToIgnore + ",") ||
                    (assemblyToIgnore.EndsWith(".") && assemblyName.StartsWith(assemblyToIgnore)))
                {
                    return(null);
                }
            }

            DateTime modificationDate = C1File.GetLastWriteTime(filePath);

            var cachedInfo = cachedTypesInfo.FirstOrDefault(asm => asm.AssemblyName == assemblyName);

            if (cachedInfo != null)
            {
                if (cachedInfo.LastModified == modificationDate)
                {
                    string[] subscribedTypesNames = cachedInfo.SubscribedTypes;
                    if (subscribedTypesNames.Length == 0)
                    {
                        return(new Type[0]);
                    }

                    Assembly asm = Assembly.LoadFrom(filePath);
                    return(subscribedTypesNames.Select(asm.GetType).ToArray());
                }

                // Removing cache entry if it is obsolete
                cachedTypesInfo.Remove(cachedInfo);
            }

            Assembly assembly;

            try
            {
                assembly = Assembly.LoadFrom(filePath);
            }
            catch (ReflectionTypeLoadException ex)
            {
                Log.LogWarning(LogTitle, "Failed to load assembly '{0}'".FormatWith(filePath));
                if (ex.LoaderExceptions != null && ex.LoaderExceptions.Length > 0)
                {
                    Log.LogError(LogTitle, ex.LoaderExceptions[0]);
                }

                return(null);
            }


            Type[] types;

            if (!TryGetTypes(assembly, out types))
            {
                return(new Type[0]);
            }

            Type[] result = GetSubscribedTypes(types);

            var newCacheEntry = new AssemblyInfo
            {
                AssemblyName    = assembly.GetName().Name,
                LastModified    = modificationDate,
                SubscribedTypes = result.Select(type => type.FullName).ToArray()
            };

            cachedTypesInfo.Add(newCacheEntry);

            cacheHasBeenUpdated = true;

            return(result);
        }
예제 #14
0
        /// <summary>
        /// Gets the resized image.
        /// </summary>
        /// <param name="httpServerUtility">An instance of <see cref="System.Web.HttpServerUtility" />.</param>
        /// <param name="file">The media file.</param>
        /// <param name="resizingOptions">The resizing options.</param>
        /// <param name="targetImageFormat">The target image format.</param>
        /// <returns>A full file path to a resized image; null if there's no need to resize the image</returns>
        public static string GetResizedImage(HttpServerUtility httpServerUtility, IMediaFile file, ResizingOptions resizingOptions, ImageFormat targetImageFormat)
        {
            Verify.ArgumentNotNull(file, "file");
            Verify.That(ImageFormatIsSupported(targetImageFormat), "Unsupported image format '{0}'", targetImageFormat);

            if (_resizedImagesDirectoryPath == null)
            {
                _resizedImagesDirectoryPath = httpServerUtility.MapPath(ResizedImagesCacheDirectory);

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

            string imageKey = file.CompositePath;

            bool isNativeProvider = file is FileSystemFileBase;

            string imageSizeCacheKey = "ShowMedia.ashx image size " + imageKey;
            Size?  imageSize         = HttpRuntime.Cache.Get(imageSizeCacheKey) as Size?;

            Bitmap bitmap     = null;
            Stream fileStream = null;

            try
            {
                if (imageSize == null)
                {
                    fileStream = file.GetReadStream();

                    Size calculatedSize;
                    if (!ImageSizeReader.TryGetSize(fileStream, out calculatedSize))
                    {
                        fileStream.Dispose();
                        fileStream = file.GetReadStream();

                        bitmap         = new Bitmap(fileStream);
                        calculatedSize = new Size {
                            Width = bitmap.Width, Height = bitmap.Height
                        };
                    }
                    imageSize = calculatedSize;

                    // We can provider cache dependency only for the native media provider
                    var cacheDependency = isNativeProvider ? new CacheDependency((file as FileSystemFileBase).SystemPath) : null;

                    HttpRuntime.Cache.Add(imageSizeCacheKey, imageSize, cacheDependency, DateTime.MaxValue, CacheExpirationTimeSpan, CacheItemPriority.Normal, null);
                }

                int  newWidth, newHeight;
                bool centerCrop;
                bool needToResize = CalculateSize(imageSize.Value.Width, imageSize.Value.Height, resizingOptions, out newWidth, out newHeight, out centerCrop);

                needToResize = needToResize || resizingOptions.CustomQuality;

                if (!needToResize)
                {
                    return(null);
                }

                int filePathHash = imageKey.GetHashCode();

                string centerCroppedString = centerCrop ? "c" : string.Empty;

                string fileExtension        = _ImageFormat2Extension[targetImageFormat];
                string resizedImageFileName = string.Format("{0}x{1}_{2}{3}_{4}.{5}", newWidth, newHeight, filePathHash, centerCroppedString, resizingOptions.Quality, fileExtension);

                string imageFullPath = Path.Combine(_resizedImagesDirectoryPath, resizedImageFileName);

                if (!C1File.Exists(imageFullPath) || C1File.GetLastWriteTime(imageFullPath) != file.LastWriteTime)
                {
                    if (bitmap == null)
                    {
                        fileStream = file.GetReadStream();
                        bitmap     = new Bitmap(fileStream);
                    }

                    ResizeImage(bitmap, imageFullPath, newWidth, newHeight, centerCrop, targetImageFormat, resizingOptions.Quality);

                    if (file.LastWriteTime.HasValue)
                    {
                        C1File.SetLastWriteTime(imageFullPath, file.LastWriteTime.Value);
                    }
                }

                return(imageFullPath);
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }

                if (fileStream != null)
                {
                    fileStream.Dispose();
                }
            }
        }