Example #1
0
        private void BeginCountCurrentCacheSize()
        {
            Task.Factory.StartNew(async() =>
            {
                IReadOnlyList <StorageFile> cacheFiles;
                try
                {
                    var storageFolder = await SF.GetFolderAsync(CacheDirectory);
                    cacheFiles        = await storageFolder.GetFilesAsync();
                }
                catch (Exception)
                {
                    return;
                }

                long cacheSizeInBytes = 0;

                foreach (var cacheFile in cacheFiles)
                {
                    var properties        = await cacheFile.GetBasicPropertiesAsync();
                    var fullCacheFilePath = cacheFile.Name;
                    try
                    {
                        cacheSizeInBytes += (long)properties.Size;
                        _lastAccessTimeDictionary.Add(fullCacheFilePath, properties.DateModified.DateTime.Milliseconds());
                    }
                    catch
                    {
                        ImageLog.Log("[error] can not get cache's file size: " + fullCacheFilePath);
                    }
                }
                CurrentCacheSizeInBytes += cacheSizeInBytes; // Updating current cache size
            });
        }
        /// <summary>The sprite image.</summary>
        /// <param name="scanOutput">The scan Output.</param>
        /// <param name="mapXmlFile">The map xml file</param>
        /// <param name="imageAssemblyAnalysisLog">The image Assembly Analysis Log.</param>
        /// <param name="threadContext">The thread Context.</param>
        /// <param name="spritedImageContentItems">The sprited Image Content Items.</param>
        /// <returns>The <see cref="ImageLog"/>.</returns>
        private ImageLog SpriteImageFromLog(ImageAssemblyScanOutput scanOutput, string mapXmlFile, ImageAssemblyAnalysisLog imageAssemblyAnalysisLog, IWebGreaseContext threadContext, BlockingCollection <ContentItem> spritedImageContentItems)
        {
            if (scanOutput == null || !scanOutput.ImageReferencesToAssemble.Any())
            {
                return(null);
            }

            ImageLog imageLog = null;
            var      imageReferencesToAssemble = scanOutput.ImageReferencesToAssemble;

            if (imageReferencesToAssemble == null || imageReferencesToAssemble.Count == 0)
            {
                return(null);
            }

            var varBySettings = new { imageMap = GetRelativeSpriteCacheKey(imageReferencesToAssemble, threadContext), this.ImageAssemblyPadding };
            var success       = threadContext.SectionedAction(SectionIdParts.MinifyCssActivity, SectionIdParts.Spriting, SectionIdParts.Assembly)
                                .MakeCachable(varBySettings, false, true)
                                .RestoreFromCacheAction(cacheSection =>
            {
                imageLog = RestoreSpritedImagesFromCache(mapXmlFile, cacheSection, spritedImageContentItems, threadContext.Configuration.DestinationDirectory, this.ImageAssembleScanDestinationFile);
                return(imageLog != null);
            })
                                .Execute(cacheSection =>
            {
                imageLog = this.CreateSpritedImages(mapXmlFile, imageAssemblyAnalysisLog, imageReferencesToAssemble, cacheSection, spritedImageContentItems, threadContext);
                return(imageLog != null);
            });

            return
                (success
                ? imageLog
                : null);
        }
        /// <summary>
        /// Saves the file with fullFilePath, uses FileMode.Create, so file create time will be rewrited if needed
        /// If exception has occurred while writing the file, it will delete it
        /// </summary>
        /// <param name="fullFilePath">example: "\\image_cache\\213898adj0jd0asd</param>
        /// <param name="cacheStream">stream to write to the file</param>
        /// <returns>true if file was successfully written, false otherwise</returns>
        protected async virtual Task <bool> InternalSaveAsync(string fullFilePath, IRandomAccessStream cacheStream)
        {
            var storageFile = await SF.CreateFileAsync(fullFilePath, CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream outputStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                try
                {
                    await RandomAccessStream.CopyAsync(
                        cacheStream.GetInputStreamAt(0L),
                        outputStream.GetOutputStreamAt(0L));

                    return(true);
                }
                catch
                {
                    try
                    {
                        // If file was not saved normally, we should delete it
                        await storageFile.DeleteAsync();
                    }
                    catch
                    {
                        ImageLog.Log("[error] can not delete unsaved file: " + fullFilePath);
                    }
                }
            }
            ImageLog.Log("[error] can not save cache to the: " + fullFilePath);
            return(false);
        }
Example #4
0
        public byte[] GetByFriendlyName(string userId, string name)
        {
            ImageLog imageLog = _data.GetImageLogByFriendlyName(userId, name);

            if (imageLog != null)
            {
                return(GetImageFile(userId, imageLog.Id));
            }
            return(null);
        }
        /// <summary>The create sprited images.</summary>
        /// <param name="mapXmlFile">The map xml file.</param>
        /// <param name="imageAssemblyAnalysisLog">The image assembly analysis log.</param>
        /// <param name="imageReferencesToAssemble">The image references to assemble.</param>
        /// <param name="cacheSection">The cache section.</param>
        /// <param name="results">The results.</param>
        /// <param name="threadContext">The thread Context.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        private ImageLog CreateSpritedImages(
            string mapXmlFile,
            ImageAssemblyAnalysisLog imageAssemblyAnalysisLog,
            IEnumerable <InputImage> imageReferencesToAssemble,
            ICacheSection cacheSection,
            BlockingCollection <ContentItem> results,
            IWebGreaseContext threadContext)
        {
            if (!Directory.Exists(this.ImagesOutputDirectory))
            {
                Directory.CreateDirectory(this.ImagesOutputDirectory);
            }

            var imageMap = ImageAssembleGenerator.AssembleImages(
                imageReferencesToAssemble.ToSafeReadOnlyCollection(),
                SpritePackingType.Vertical,
                this.ImagesOutputDirectory,
                string.Empty,
                true,
                threadContext,
                this.ImageAssemblyPadding,
                imageAssemblyAnalysisLog,
                this.ForcedSpritingImageType);

            if (imageMap == null || imageMap.Document == null)
            {
                return(null);
            }

            var destinationDirectory = threadContext.Configuration.DestinationDirectory;

            if (!string.IsNullOrWhiteSpace(this.ImageAssembleScanDestinationFile))
            {
                var scanXml = imageMap.Document.ToString();
                FileHelper.WriteFile(mapXmlFile, scanXml);
                cacheSection.AddResult(ContentItem.FromFile(mapXmlFile), CacheFileCategories.SpriteLogFileXml);
            }

            var imageLog = new ImageLog(imageMap.Document);

            cacheSection.AddResult(ContentItem.FromContent(imageLog.ToJson(true)), CacheFileCategories.SpriteLogFile);

            foreach (var spritedFile in imageLog.InputImages.Select(il => il.OutputFilePath).Distinct())
            {
                var spritedImageContentItem = ContentItem.FromFile(spritedFile, spritedFile.MakeRelativeToDirectory(destinationDirectory));
                results.Add(spritedImageContentItem);
                cacheSection.AddResult(spritedImageContentItem, CacheFileCategories.HashedSpriteImage);
            }

            return(imageLog);
        }
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     modelBuilder.Entity <UserLog>().HasData(Models.UserLog.GetSeederData());
     modelBuilder.Entity <DroneLog>().HasData(DroneLog.GetSeederData());
     modelBuilder.Entity <Payload>().HasData(Payload.GetSeederData());
     modelBuilder.Entity <ImageLog>().HasData(ImageLog.GetSeederData());
     modelBuilder.Entity <VideoLog>().HasData(VideoLog.GetSeederData());
     modelBuilder.Entity <IncidentLog>().HasData(IncidentLog.GetSeederData());
     modelBuilder.Entity <ObjectObserve>().HasData(ObjectObserve.GetSeederData());
     modelBuilder.Entity <StaticalLog>().HasData(StaticalLog.GetSeederData());
     modelBuilder.Entity <WarningLog>().HasData(WarningLog.GetSeederData());
     modelBuilder.Entity <MonitorRegionLog>().HasData(MonitorRegionLog.GetSeederData());
     modelBuilder.Entity <ResolveProblemLog>().HasData(ResolveProblemLog.GetSeederData());
     modelBuilder.Entity <UavConnectLog>().HasData(UavConnectLog.GetSeederData());
 }
        /// <summary>
        /// Checks file existence
        /// </summary>
        /// <param name="cacheKey">Will be used by CacheFileNameGenerator</param>
        /// <returns>true if file with cache exists, false otherwise</returns>
        public virtual async Task <bool> IsCacheExists(string cacheKey)
        {
            var fullFilePath = GetFullFilePath(CacheFileNameGenerator.GenerateCacheName(cacheKey));

            try
            {
                await SF.GetFileAsync(fullFilePath);

                return(true);
            }
            catch
            {
                ImageLog.Log("[error] can not check cache existence, file: " + fullFilePath);
                return(false);
            }
        }
Example #8
0
        /// <summary>
        /// Removing oldest cache file (file, which last access time is smaller)
        /// </summary>
        private async Task <bool> RemoveOldestCacheFile()
        {
            if (_lastAccessTimeDictionary.Count == 0)
            {
                return(false);
            }

            var oldestCacheFilePath = _lastAccessTimeDictionary.Aggregate((pair1, pair2) => (pair1.Value < pair2.Value) ? pair1 : pair2).Key;

            if (string.IsNullOrEmpty(oldestCacheFilePath))
            {
                return(false);
            }

            oldestCacheFilePath = Path.Combine(CacheDirectory, oldestCacheFilePath);

            try
            {
                long fileSizeInBytes;
                var  storageFile = await SF.GetFileAsync(oldestCacheFilePath);

                var properties = await storageFile.GetBasicPropertiesAsync();

                fileSizeInBytes = (long)properties.Size;

                try
                {
                    await storageFile.DeleteAsync();

                    _lastAccessTimeDictionary.Remove(oldestCacheFilePath);
                    CurrentCacheSizeInBytes -= fileSizeInBytes; // Updating current cache size
                    ImageLog.Log("[delete] cache file " + oldestCacheFilePath);
                    return(true);
                }
                catch
                {
                    ImageLog.Log("[error] can not delete oldest cache file: " + oldestCacheFilePath);
                }
            }
            catch (Exception)
            {
                ImageLog.Log("[error] can not get olders cache's file size: " + oldestCacheFilePath);
            }

            return(false);
        }
        /// <summary>
        /// Checks is cache existst and its last write time &lt;= CacheMaxLifetimeInMillis
        /// </summary>
        /// <param name="cacheKey">Will be used by CacheFileNameGenerator</param>
        /// <returns>true if cache exists and alive, false otherwise</returns>
        public virtual async Task <bool> IsCacheExistsAndAlive(string cacheKey)
        {
            var fullFilePath = GetFullFilePath(CacheFileNameGenerator.GenerateCacheName(cacheKey));

            try
            {
                var storageFile = await SF.GetFileAsync(fullFilePath);

                return(CacheMaxLifetimeInMillis <= 0 ? true :
                       ((DateTime.Now - storageFile.DateCreated.DateTime).TotalMilliseconds < CacheMaxLifetimeInMillis));
            }
            catch
            {
                ImageLog.Log("[error] can not check is cache exists and alive, file: " + fullFilePath);
            }
            return(false);
        }
Example #10
0
 ImageLog IBasicOperation <ImageLog> .Update(ImageLog entity)
 {
     if (string.IsNullOrEmpty(entity.Id))
     {
         throw new ArgumentException("Entity does not have a populated Id value.  Use the Create function to save a new entity to the database.", "entity");
     }
     using (var t = _ctx.Database.BeginTransaction())
     {
         try
         {
             _ctx.ImageLogs.Update(entity);
             _ctx.SaveChanges();
             t.Commit();
             return(_ctx.ImageLogs.Find(entity.Id));
         }
         catch
         {
             t.Rollback();
             throw;
         }
     }
 }
Example #11
0
 ImageLog IBasicOperation <ImageLog> .Create(ImageLog entity)
 {
     if (!string.IsNullOrEmpty(entity.Id))
     {
         throw new ArgumentException("Entity already has a populated Id value.  Use the Update method to update an existing entity.", "entity");
     }
     using (var t = _ctx.Database.BeginTransaction())
     {
         try
         {
             entity.Id = Guid.NewGuid().ToString();
             _ctx.ImageLogs.Add(entity);
             _ctx.SaveChanges();
             t.Commit();
             return(_ctx.ImageLogs.Find(entity.Id));
         }
         catch
         {
             t.Rollback();
             throw;
         }
     }
 }
        /// <summary>
        /// Async gets file stream by the cacheKey (cacheKey will be converted using CacheFileNameGenerator)
        /// </summary>
        /// <param name="cacheKey">key will be used by CacheFileNameGenerator to get cache's file name</param>
        /// <returns>Stream of that file or null, if it does not exists</returns>
        public async virtual Task <IRandomAccessStream> LoadCacheStreamAsync(string cacheKey)
        {
            var fullFilePath = GetFullFilePath(CacheFileNameGenerator.GenerateCacheName(cacheKey));

            try
            {
                var cacheFileMemoryStream = new InMemoryRandomAccessStream();
                var storageFile           = await SF.GetFileAsync(fullFilePath);

                using (var cacheFileStream = await storageFile.OpenAsync(FileAccessMode.Read))
                {
                    await RandomAccessStream.CopyAsync(
                        cacheFileStream.GetInputStreamAt(0L),
                        cacheFileMemoryStream.GetOutputStreamAt(0L));

                    return(cacheFileMemoryStream);
                }
            }
            catch (Exception ex)
            {
                ImageLog.Log("[error] can not load file stream from: " + fullFilePath);
                return(null);
            }
        }