Esempio n. 1
0
        /// <summary>
        /// Author: Kunuk Nykjaer
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            const string key = "key";
            const string filepath = @"c:\temp\file.json";

            IObjectCache cache1 = new FileCache(filepath);
            IObjectCache cache2 = new ObjectCacheWrapper(MemoryCache.Default);

            var dataBeforeLoaded1 = cache1.Get<IDictionary<string, List<string>>>(key);
            var dataBeforeLoaded2 = cache2.Get<IDictionary<string, List<string>>>(key);

            if (dataBeforeLoaded1 != null) Console.WriteLine("dataBeforeLoaded1 was loaded count: {0}", dataBeforeLoaded1.Count);
            if (dataBeforeLoaded2 != null) Console.WriteLine("dataBeforeLoaded2 was loaded count: {0}", dataBeforeLoaded2.Count);

            IDictionary<string, List<string>> dataSaved = new Dictionary<string, List<string>>
            {
                {"a", new List<string>{"a1","a2"}},
                {"b", new List<string>{"b1","b2"}}
            };

            cache1.Set(key, dataSaved, DateTimeOffset.MaxValue);
            cache2.Set(key, dataSaved, DateTimeOffset.MaxValue);

            var dataAfter1 = cache1.Get<IDictionary<string, List<string>>>(key);
            var dataAfter2 = cache2.Get<IDictionary<string, List<string>>>(key);

            if (dataAfter1 != null) Console.WriteLine("dataAfter1 was loaded count: {0}", dataAfter1.Count);
            if (dataAfter2 != null) Console.WriteLine("dataAfter2 was loaded count: {0}", dataAfter2.Count);

            Console.WriteLine("press a key...");
            Console.ReadKey();
        }
 public void GetFileContents()
 {
     lock(this.assemblerLock)
     try
     {
         this.fullFileName   = new StringBuilder();
         this.content        = new MemoryStream();
         this.AddFileContents(byParent: this.RequestDirectoryPath+this.FileExtension, fromPath: this.RequestDirectoryPath);
         this.fullFileName.Append("|"+this.lastModified.ConvertToEpoch().ToString());
         if
         (
             !VirtualFileAssembler.fileCache.TryGetValue(this.RequestDirectoryPath+this.FileExtension, out this.CachedFile)
             ||
             this.lastModified > this.CachedFile.lastModified
         )
         {
             this.loadContent.ForEach(a=>a());
             VirtualFileAssembler.fileCache[this.RequestDirectoryPath+this.FileExtension]    =
             this.CachedFile =
             new FileCache()
             {
                 etag            = this.fullFileName.ToString(),
                 contents        = this.content,
                 lastModified    = this.lastModified
             };
         }
     }
     finally
     {
         this.content    = null;
     }
 }
Esempio n. 3
0
 public SimpleFileFetcher(ITileSource tileSource, FileCache filecache)
 {
     if (tileSource == null) throw new ArgumentNullException("tileSource");
     if (filecache == null) throw new ArgumentNullException("filecache");
     _tileSource = tileSource;
     _fileCache = filecache;
 }
Esempio n. 4
0
 public InfoSet()
 {
     Hashtable.Synchronized((Hashtable) this._stringDictionaries);
     Hashtable.Synchronized((Hashtable) this._objectDictionaries);
     this._fileCache = FileCache.CreateInstance();
     this._fileCache.Add(this);
 }
 public CacheFileDependency(string[] files)
 {
     if (files == null)
     {
         throw new ArgumentNullException("files");
     }
     this._files = files;
     this._cache = FileCache.CreateInstance();
     this._cache.Add(this);
     this._hasChanged = false;
 }
Esempio n. 6
0
        public TileManager(string tileServerName, string tileServerUrl, WmsServerInfo wmsServerInfo)
        {
            if (tileServerName == null) throw new ArgumentNullException("tileServerName");

            _tileServerUrl = tileServerUrl;
            _tileServerName = tileServerName;
            WmsServerInfo = wmsServerInfo;
            TileCache = new FileCache(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "TileCache", _tileServerName), "", new TimeSpan(30, 0, 0, 0));
            _tileSource = InitializeBrutileProvider();
        }
        public override void OnClick()
        {
            //var bruTileAboutBox = new BruTileAboutBox();
            //bruTileAboutBox.ShowDialog(new ArcMapWindow(_application));

            var fileCache = new FileCache(@"c:\aaa\tiles", "png");
            var osmTileSource = new OsmTileSource();
            var mxdoc = (IMxDocument)_application.Document;
            var map = mxdoc.FocusMap;
            var brutileCustomLayer = new BruTileCustomLayer(_application, osmTileSource,fileCache) {Name = "testlayer"};
            map.AddLayer(brutileCustomLayer);
        }
Esempio n. 8
0
        public void GetTile_WhenTilePresent_ShouldReturnTile()
        {
            // arrange
            var tileCache = new FileCache(".", "png", new TimeSpan(long.MaxValue));
            tileCache.Add(new TileIndex(4, 5, 8),new byte[243]);
            var fileTileProvider = new FileTileProvider(".", "png", new TimeSpan(long.MaxValue));

            // act
            var tile = fileTileProvider.GetTile(new TileInfo { Index = new TileIndex(4, 5, 8) });

            // assert
            Assert.AreEqual(tile.Length, 243);
        }
Esempio n. 9
0
 public SceneManager(byte[] backgroundSound, string sceneTitle, string sentences)
 {
     stringRes.AddRange(SplitSentences(sentences));
     countOfSentenceVisiable = stringRes.Count;
     Task.Run(() =>
     {
         backgroundSoundFile = new FileCache(backgroundSound, "mp3");
         SoundManager.GetInstance().PlayFile(backgroundSoundFile.FilePath, true);
     });
     MovableStyle4Object titleObj = new MovableStyle4Object(50.0f, 100.0f, sceneTitle,
         Color.DeepPink, new Font(FontFamily.GenericSansSerif, 30.0f));
     titleObj.SpeedX = 0.4f;
     objects.Add(titleObj);
 }
Esempio n. 10
0
        public async Task HotGet(ServiceArgument args, Action <CollectHot> callback)
        {
            var pair = new Dictionary <string, object>();

            pair.Add("id", args.id);
            pair.Add("type", 1);
            pair.Add("feature", args.feature);
            pair.Add("page", args.page);
            pair.Add("language", DeviceUtil.Language);
            pair.Add("client_id", DeviceUtil.DEVICE_CLIENTID);
            pair.Add("device_id", DeviceUtil.UniqueId);
            pair.Add("version", DeviceUtil.Version);
            pair.Add("channel", DeviceUtil.Channel);
            pair.Add("model", "N918St");
            args.Dic = pair;
            args.Uri = Const_def.API_Category;

            await Get(args, response =>
            {
                switch (response.Statused)
                {
                case HttpErrorStatus.Success:
                    {
                        //缓存分开
                        //异步写入数据库 不使用文件保存 下次加载缓存数据从数据库加载
                        var taskCache = FileCache.SaveFile(Const_def.db_CacheDir, response.Data);

                        //序列化
                        BaseDeserializer serializer = DeserializerManager.Instance.BuildHotDeserializer();
                        CollectHot list             = serializer.ReadList(response.Data) as CollectHot;

                        callback?.Invoke(list);
                        break;
                    }

                case HttpErrorStatus.JsonError:
                    break;

                case HttpErrorStatus.NetworkError:
                    break;

                case HttpErrorStatus.UnknownError:
                    break;

                case HttpErrorStatus.UserCancelOperation:
                    break;
                }
            });
        }
Esempio n. 11
0
        public void Put(string remotename, System.IO.Stream stream)
        {
            var overwrite = FileCache.ContainsKey(remotename);
            var fileid    = overwrite ? m_filecache[remotename] : null;

            var url = string.Format(overwrite ? "{0}/nodes/{1}/content?suppress=deduplication" : "{0}/nodes?suppress=deduplication", ContentUrl, fileid);

            var createreq = new CreateItemRequest()
            {
                Name    = remotename,
                Kind    = CONTENT_KIND_FILE,
                Labels  = m_labels,
                Parents = new string[] { CurrentDirectory.ID }
            };

            try
            {
                var item = m_oauth.PostMultipartAndGetJSONData <ResourceModel>(
                    url,

                    req =>
                {
                    req.Method = overwrite ? "PUT" : "POST";
                },

                    new MultipartItem(createreq, name: "metadata"),
                    new MultipartItem(stream, name: "content", filename: remotename)

                    );

                if (m_filecache != null)
                {
                    m_filecache[item.Name] = item.ID;
                }
            }
            catch (Exception ex)
            {
                #if DEBUG
                if (ex is WebException)
                {
                    using (var sr = new StreamReader((ex as WebException).Response.GetResponseStream()))
                        Console.WriteLine(sr.ReadToEnd());
                }
                #endif

                m_filecache = null;
                throw;
            }
        }
Esempio n. 12
0
        public static void Main(string[] args)
        {
            ClientConfig config = new ClientConfig ("C# Hoccer Demo");
            config.UseProductionServers (); // enables communication to real Hoccer Clients (iOS & Android)

            Linccer linccer = new Linccer ();
            linccer.Config = config;

            // set geo position (must be changed to work on other locations than Molkenmarkt 2 in Berlin, Germany)
            //41.38690, 2.16532
            linccer.Gps = new LocationInfo { Latitude = 41.38690, Longitude = 2.16532, Accuracy = 1000 };
            linccer.SubmitEnvironment ();

            // inialize filecache for temporary up- and downloading large files (not used jet)
            FileCache cache = new FileCache ();
            cache.Config = config;

            // countdown to not miss the time when the drag-in or -out gesture must take place on the mobile
            for (int i = 3; i > 0; i--) {
                System.Console.Write (i + "... ");
                Thread.Sleep (1 * 1000);
            }

            if (args.Length > 0) {

                // create a plain message
                Hoc hoc = new Hoc ();
                hoc.DataList.Add(
                  new HocData {Content = "yaya", Type = "text/plain"}
                );

                // share it 1:1, in the Hoccer mobile App, you need to perform a drag in
                // gesture to receive the message  (one-to-many is throw/catch)
                linccer.Share ("one-to-one", hoc);

            } else {
                System.Console.WriteLine ("Waiting for sender");
                Hoc hoc;

                // receive 1:1, in the Hoccer mobile App, you need to perform a drag out
                // gesture to send something to this client (one-to-many is throw/catch)
                hoc = linccer.Receive<Hoc> ("one-to-one");

                if (hoc == null)
                    System.Console.WriteLine ("no sender found");
                else
                    System.Console.WriteLine (hoc);
            }
        }
Esempio n. 13
0
        private async Task <T> GetWithDebugCaching <T>(Func <Task <T> > get, string methodName, string debugCacheKey)
        {
            debugCacheKey = methodName + debugCacheKey;
            var cache = new FileCache();

            if (cache[debugCacheKey] != null)
            {
                return(((string)cache[debugCacheKey]).FromJson <T>());
            }

            var result = await get.Invoke();

            cache.Add(debugCacheKey, result.ToJson(), DateTimeOffset.Now.AddDays(1));
            return(result);
        }
Esempio n. 14
0
        //public static bool TryGetValue<TItem>(this FsCache cache, object key, out TItem value)
        //{
        //    if (cache.TryGetValue(key, out object result))
        //    {
        //        if (result is TItem item)
        //        {
        //            value = item;
        //            return true;
        //        }
        //    }

        //    value = default;
        //    return false;
        //}

        public static TItem Set <TItem>(this FileCache cache, object key, TItem value)
        {
            var entry = cache.CreateEntry(key);

            entry.Value = value;
            entry.Dispose();

            if (cache.Get(key) != null)
            {
                cache.Persist <TItem>(entry);
            }


            return(value);
        }
Esempio n. 15
0
        public void MaxCacheSizeTest()
        {
            FileCache target = new FileCache("MaxCacheSizeTest");

            target.MaxCacheSize = 0;
            bool isEventCalled = false;

            target.MaxCacheSizeReached += delegate(object sender, FileCacheEventArgs e)
            {
                isEventCalled = true;
            };
            target["foo"] = "bar";

            Assert.AreEqual(true, isEventCalled);
        }
Esempio n. 16
0
        public void CacheSizeTest()
        {
            FileCache target = new FileCache("CacheSizeTest");

            target["foo"] = "bar";
            target["foo"] = "foobar";

            long cacheSize = target.GetCacheSize();

            Assert.AreNotEqual(0, cacheSize);

            target.Remove("foo");
            cacheSize = target.CurrentCacheSize;
            Assert.AreEqual(0, cacheSize);
        }
Esempio n. 17
0
        public ImagesService(DiscordSocketClient client, FileCache fileCache, IHttpClientFactory httpClientFactory)
        {
            Client            = client;
            Cache             = fileCache;
            HttpClientFactory = httpClientFactory;

            WhipFrames  = GetFramesFromResources <WhipResources>();
            BonkFrames  = GetFramesFromResources <BonkResources>();
            PatFrames   = GetFramesFromResources <PatResources>();
            SpankFrames = GetFramesFromResources <SpankResources>();

            PeepoloveBodyFrame  = new MagickImage(PeepoloveResources.body);
            PeepoloveHandsFrame = new MagickImage(PeepoloveResources.hands);
            PeepoangryFrame     = new MagickImage(PeepoangryResources.peepoangry);
        }
Esempio n. 18
0
        public void TestCacheRead()
        {
            var uc = _buildCache();

            uc.save("c:\\tmp\\cache.json");

            uc = FileCache.Load("c:\\tmp\\cache.json");
            var blardir = uc.getdir("blarg");

            Assert.IsNotNull(blardir);
            var item = blardir.FirstOrDefault();

            Assert.IsNotNull(item);
            Assert.AreEqual("blarg/blarg1.obj", item.path);
        }
Esempio n. 19
0
        public SceneManager(byte[] backgroundSound, string sceneTitle, string sentences)
        {
            stringRes.AddRange(SplitSentences(sentences));
            countOfSentenceVisiable = stringRes.Count;
            Task.Run(() =>
            {
                backgroundSoundFile = new FileCache(backgroundSound, "mp3");
                SoundManager.GetInstance().PlayFile(backgroundSoundFile.FilePath, true);
            });
            MovableStyle4Object titleObj = new MovableStyle4Object(50.0f, 100.0f, sceneTitle,
                                                                   Color.DeepPink, new Font(FontFamily.GenericSansSerif, 30.0f));

            titleObj.SpeedX = 0.4f;
            objects.Add(titleObj);
        }
Esempio n. 20
0
        public void CacheSizeTest()
        {
            _cache = new FileCache("CacheSizeTest");

            _cache["foo"] = "bar";
            _cache["foo"] = "foobar";

            long cacheSize = _cache.GetCacheSize();

            cacheSize.Should().NotBe(0);

            _cache.Remove("foo");
            cacheSize = _cache.CurrentCacheSize;
            cacheSize.Should().Be(0);
        }
        private LuceneLoggerBackend()
        {
            indexDirectory = Path.Combine(TemporaryFilesManager.Instance.EmulatorTemporaryPath, "index");
            var directory = FSDirectory.Open(indexDirectory);

            analyzer = new StandardAnalyzer(LuceneNet.Util.Version.LUCENE_30);
            writer   = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.LIMITED);

            writer.UseCompoundFile = false;

            logLevel = LogLevel.Noisy;
            searcher = new Searcher(directory, analyzer);

            cache = new FileCache();
        }
Esempio n. 22
0
        public void When_flushing_cache_it_should_clear_all_cache_files()
        {
            // Arrange
            var fileSystem = A.Fake <IFileSystem>();

            A.CallTo(() => fileSystem.FileExists(A <string> ._)).Returns(false);

            var fileCache = new FileCache(fileSystem);

            // Act
            fileCache.Flush();

            // Assert
            A.CallTo(() => fileSystem.RemoveFolder(A <string> .That.EndsWith(RelativeCacheFolder))).MustHaveHappened();
        }
        public File GetFileById(object id)
        {
            var key  = "spointf-" + MakeId(id);
            var file = FileCache.Get <File>(key);

            if (file == null)
            {
                file = GetFile(id);
                if (file != null)
                {
                    FileCache.Insert(key, file, DateTime.UtcNow.Add(CacheExpiration));
                }
            }
            return(file);
        }
Esempio n. 24
0
        public void FlushTest()
        {
            _cache = new FileCache("FlushTest");

            _cache["foo"] = "bar";
            Thread.Sleep(500);

            //attempt flush
            _cache.Flush(DateTime.Now.AddDays(1));

            Thread.Sleep(500);

            //check to see if size ends up at zero (expected result)
            _cache.GetCacheSize().Should().Be(0);
        }
Esempio n. 25
0
        public void DefaultRegionTest()
        {
            FileCache cacheWithDefaultRegion = new FileCache();

            cacheWithDefaultRegion.DefaultRegion = "foo";
            FileCache defaultCache = new FileCache();

            cacheWithDefaultRegion["foo"] = "bar";
            object pull = defaultCache.Get("foo", "foo");

            pull.ToString().Should().Be("bar");

            cacheWithDefaultRegion.Flush();
            defaultCache.Flush();
        }
Esempio n. 26
0
        public async Task Validate_ValidKey_ExpectAuthenticationResult()
        {
            string authority = "https://login.microsoftonline.com/<Your tenant id>/";
            string clientId  = "<your client id>";
            string resource  = "https://graph.microsoft.com/";
            string userId    = "<your user id>";

            IDistributedCache distributedCache = new FileCache();

            var tokenHelper = new TokenHelper();

            var result = await tokenHelper.Validate(distributedCache, userId, authority, resource, clientId);

            Assert.IsNotNull(result);
        }
Esempio n. 27
0
        public Authentication()
        {
            //set up DB
            _db = OsbideContext.DefaultWebConnection;

            //set up cache
            _cache = FileCacheHelper.GetGlobalCacheInstance();
            _cache.DefaultRegion = "AuthenticationService";

            //have our cache kill things after 2 days
            _cache.DefaultPolicy = new CacheItemPolicy()
            {
                SlidingExpiration = new TimeSpan(2, 0, 0, 0, 0)
            };
        }
Esempio n. 28
0
 public OsbideToolWindowManager(FileCache cache, Package vsPackage)
 {
     _cache     = cache;
     _vsPackage = vsPackage;
     _interceptor.NavigationRequested += NavigationRequested;
     _chatVm.Url                = StringConstants.ChatUrl;
     _profileVm.Url             = StringConstants.ProfileUrl;
     _communityVm.Url           = StringConstants.CommunityUrl;
     _activityFeedVm.Url        = StringConstants.ActivityFeedUrl;
     _activityFeedDetailsVm.Url = StringConstants.ActivityFeedUrl;
     _createAccountVm.Url       = StringConstants.CreateAccountUrl;
     _askTheProfessorVm.Url     = StringConstants.AskTheProfessorUrl;
     _genericWindowVm.Url       = StringConstants.ProfileUrl;
     _interventionVm.Url        = StringConstants.InterventionUrl;
 }
Esempio n. 29
0
        private static async Task ExportOsu()
        {
            var path = "F:\\milkitic\\Songs\\" +
                       "1346316 Nekomata Master feat. Mimi Nyami - TWINKLING\\" +
                       "Nekomata Master feat. Mimi Nyami - TWINKLING (yf_bmp) [Another].osu";

            //var path = "E:\\Games\\osu!\\Songs\\3198 Rhapsody - Emerald Sword\\" +
            //           //"1376486 Risshuu feat. Choko - Take\\" +
            //           "Rhapsody - Emerald Sword (Reikin) [net].osu";

            var folder  = Path.GetDirectoryName(path);
            var osuFile = await OsuFile.ReadFromFileAsync(path);

            if (!osuFile.ReadSuccess)
            {
                throw osuFile.ReadException;
            }

            using var engine = new AudioPlaybackEngine();
            var mp3Path = Path.Combine(folder, osuFile?.General.AudioFilename ?? ".");

            var fileCache = new FileCache();

            await using var directChannel   = new DirectChannel(mp3Path, osuFile.General.AudioLeadIn, engine);
            await using var hitsoundChannel = new HitsoundChannel(osuFile, engine, fileCache)
                        {
                            ManualOffset = 50,
                        };
            await using var sampleChannel = new SampleChannel(osuFile, engine, new Subchannel[]
            {
                directChannel, hitsoundChannel
            }, fileCache)
                        {
                            ManualOffset = 50,
                        };

            var    exporter = new Mp3Exporter(new MultiElementsChannel[] { directChannel, hitsoundChannel, sampleChannel }, engine);
            string pre      = null;
            await exporter.ExportAsync("test.mp3", progress =>
            {
                var p = $"Progress: {progress:P0}";
                if (pre != p)
                {
                    Console.WriteLine(p);
                    pre = p;
                }
            });
        }
        /// <summary>
        /// Standard constructor for the tool window.
        /// </summary>
        public ActivityFeedDetailsToolWindow() :
            base(null)
        {
            // Set the window title reading it from the resources.
            this.Caption = "Feed Details";
            // Set the image that will appear on the tab of the window frame
            // when docked with an other window
            // The resource ID correspond to the one defined in the resx file
            // while the Index is the offset in the bitmap strip. Each image in
            // the strip being 16x16.
            this.BitmapResourceID = 301;
            this.BitmapIndex      = 1;

            // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable,
            // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on
            // the object returned by the Content property.
            BrowserView view = new BrowserView();

            view.BrowserViewModelChanged += view_BrowserViewModelChanged;
            FileCache cache = Cache.CacheInstance;
            string    url   = "";

            try
            {
                url = cache[OsbideVsComponent.FeedDetails.ToString()].ToString();
            }
            catch (Exception)
            {
                url = "";
            }
            string authKey = "";

            try
            {
                authKey = cache[StringConstants.AuthenticationCacheKey].ToString();
            }
            catch (Exception)
            {
                authKey = "";
            }
            view.ViewModel = new Controls.ViewModels.BrowserViewModel()
            {
                Url     = url,
                AuthKey = authKey
            };
            view.ViewModel.PropertyChanged += ViewModel_PropertyChanged;
            base.Content = view;
        }
Esempio n. 31
0
    private IEnumerator LoadModels(string mapname, List <RSW.ModelDescriptor> modelDescriptors, Action <string, string, object> callback)
    {
        /**
         * Divide by 3 because of each loop in which we increase progress
         */
        float remainingProgress = 100 - Progress;
        float modelProgress     = remainingProgress / modelDescriptors.Count / 3;

        for (int i = 0; i < modelDescriptors.Count; i++)
        {
            var model = modelDescriptors[i];
            model.filename = "data/model/" + model.filename;

            FileManager.Load(model.filename);
            Progress += modelProgress;

            if (i % BATCH_SIZE == 0)
            {
                yield return(new WaitForEndOfFrame());
            }
        }

        //create model instances
        HashSet <RSM> objectsSet = new HashSet <RSM>();

        for (int i = 0; i < modelDescriptors.Count; ++i)
        {
            RSM model = (RSM)FileManager.Load(modelDescriptors[i].filename);
            if (model != null)
            {
                model.CreateInstance(modelDescriptors[i]);
                objectsSet.Add(model);
            }
            Progress += modelProgress;

            if (i % BATCH_SIZE == 0)
            {
                yield return(new WaitForEndOfFrame());
            }
        }
        FileCache.ClearAllWithExt("rsm");
        RSM[] objects = new RSM[objectsSet.Count];
        objectsSet.CopyTo(objects);

        yield return(CompileModels(objects, modelProgress, (List <RSM.CompiledModel> compiledModels) => {
            callback.Invoke(mapname, "MAP_MODELS", compiledModels);
        }));
    }
Esempio n. 32
0
        /// <summary>
        /// https://newapi.meipai.com/common/square_medias_categories.json?
        /// section=3&topic=1&filter=0&language=zh-Hans&client_id=1089857302&device_id=865773028434070&version=300&channel=bao360&model=N918St
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="args"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public async Task OnCommon <T>(ServiceArgument args, Action <BindableCollection <T> > callback)
        {
            var pair = new Dictionary <string, object>();

            pair.Add("section", 3);
            pair.Add("topic", 1);
            pair.Add("filter", 0);
            pair.Add("language", DeviceUtil.Language);
            pair.Add("client_id", DeviceUtil.DEVICE_CLIENTID);
            pair.Add("device_id", DeviceUtil.UniqueId);
            pair.Add("version", DeviceUtil.Version);
            pair.Add("channel", DeviceUtil.Channel);
            pair.Add("model", "N918St");
            args.Dic = pair;
            args.Uri = Const_def.API_Common;


            await Get(args, response =>
            {
                switch (response.Statused)
                {
                case HttpErrorStatus.Success:
                    {
                        //缓存分开
                        //异步写入数据库 不使用文件保存 下次加载缓存数据从数据库加载
                        var taskCache = FileCache.SaveFile(Const_def.db_CacheDir, response.Data);

                        //序列化
                        var taskModels = JsonConvert.DeserializeObject <BindableCollection <T> >(response.Data);

                        callback?.Invoke(taskModels);
                        break;
                    }

                case HttpErrorStatus.JsonError:
                    break;

                case HttpErrorStatus.NetworkError:
                    break;

                case HttpErrorStatus.UnknownError:
                    break;

                case HttpErrorStatus.UserCancelOperation:
                    break;
                }
            });
        }
 public ArcGISTileCompactLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, FileCache fileCache, ImageFormat imgFormat)
     : base(tileSource,layerName,transparentColor,showErrorInTile,fileCache,imgFormat)
 {
     //this._imageAttributes = new ImageAttributes();
     //this._bitmaps = new MemoryCache<Bitmap>(100, 200);
     //this._showErrorInTile = true;
     //this._source = tileSource;
     //base.LayerName = layerName;
     //if (!transparentColor.IsEmpty)
     //{
     //    this._imageAttributes.SetColorKey(transparentColor, transparentColor);
     //}
     //this._showErrorInTile = showErrorInTile;
     //this._fileCache = fileCache;
     //this._ImageFormat = imgFormat;
 }
Esempio n. 34
0
        public FeedItem(FileCache cache, FeedItemResponse response)
        {
            Response = response;

            Thumb = new Lazy <MediaData>(() => cache[MediaPresentation.Thumb].Any(x => x.Id == response.Id) ?
                                         cache[MediaPresentation.Thumb].First(x => x.Id == response.Id) :
                                         DownloadMedia(cache, MediaType.Image, MediaPresentation.Thumb, response.Thumb));

            Image = new Lazy <MediaData>(() => cache[MediaPresentation.Image].Any(x => x.Id == response.Id) ?
                                         cache[MediaPresentation.Image].First(x => x.Id == response.Id) :
                                         DownloadMedia(cache, Type, MediaPresentation.Image, response.Image));

            Fullsize = new Lazy <MediaData>(() => cache[MediaPresentation.Fullsize].Any(x => x.Id == response.Id) ?
                                            cache[MediaPresentation.Fullsize].First(x => x.Id == response.Id) :
                                            DownloadMedia(cache, MediaType.Image, MediaPresentation.Fullsize, response.Fullsize));
        }
        public void GetTile_WhenTilePresent_ShouldReturnTile()
        {
            // arrange
            var tileCache = new FileCache(".", "png", new TimeSpan(long.MaxValue));

            tileCache.Add(new TileIndex(4, 5, "8"), new byte[243]);
            var fileTileProvider = new FileTileProvider(".", "png", new TimeSpan(long.MaxValue));

            // act
            var tile = fileTileProvider.GetTile(new TileInfo {
                Index = new TileIndex(4, 5, "8")
            });

            // assert
            Assert.AreEqual(tile.Length, 243);
        }
Esempio n. 36
0
 /// <summary>
 /// Helper for tidying up local state and driver state e.g. if rate controller shuts down.
 /// </summary>
 private void Reset()
 {
     lock (LockFlows)
     {
         runtime.RuntimeReset();
         DictFlowCreateParams = null;
         DictRapCreateParams  = null;
         DictIoFlow           = new Dictionary <uint, IoFlow>();
         if (this.cache != null && this.cache.threadPrintStatsTest != null)
         {
             this.cache.shouldPrintStats = false;
         }
         this.cache = null; //Throws away the entire file cache and all its contents
         GC.Collect();
     }
 }
Esempio n. 37
0
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var petID = values[0] as uint? ?? 0;
            var alive = values[1] as bool? ?? false;

            if (petID <= 0 || petID > 11)
            {
                return(null);
            }
            return(!alive
                ? null
                : FileCache.Hit($"https://CDN.automute.us/svg/Pets/{petID}.svg"));
            //return !alive
            //    ? null
            //    : $"https://cdn.automute.us/Pets/{petID}.png";
        }
Esempio n. 38
0
        public void FlushTest()
        {
            _cache = new FileCache("FlushTest");

            _cache.Add("Key1", "Value1", _cache.DefaultPolicy);
            _cache.Add("Key2", "Value2", DateTime.Now.AddDays(1), "Region1");
            Thread.Sleep(500);

            //attempt flush
            _cache.Flush(DateTime.Now.AddDays(1));

            Thread.Sleep(500);

            //check to see if size ends up at zero (expected result)
            _cache.GetCacheSize().Should().Be(0);
        }
Esempio n. 39
0
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        /// <param name="tileSource">the source to get the tiles from</param>
        /// <param name="layerName">name of the layer</param>
        /// <param name="transparentColor">transparent color off</param>
        /// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
        /// <param name="fileCache">If the layer should use a file-cache so store tiles, set this to a fileCacheProvider. Set to null to avoid filecache</param>
        /// <param name="imgFormat">Set the format of the tiles to be used</param>
        public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, BruTile.Cache.FileCache fileCache, ImageFormat imgFormat)
        {
            _source   = tileSource;
            LayerName = layerName;
            if (!transparentColor.IsEmpty)
            {
                _imageAttributes.SetColorKey(transparentColor, transparentColor);
            }
            _showErrorInTile = showErrorInTile;

#if !PocketPC
            _imageAttributes.SetWrapMode(WrapMode.TileFlipXY);
#endif
            _fileCache   = fileCache;
            _ImageFormat = imgFormat;
        }
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            var persistentCache = new FileCache(HostingEnvironment.MapPath("~/.cache"));
            var cacheBuilder    =
                new CacheBuilder(new LinFuProxyFactory()).SetCache(persistentCache);

            cacheBuilder.For <PaintingsService>()
            .CacheMethod(c => c.GetGallery(""))
            .CacheMethod(c => c.GetPainting(""))
            .As <IPaintingsService>();
            var factory = cacheBuilder.BuildFactory();

            container.Register(Component.For <IPaintingsService>().UsingFactoryMethod(
                                   (kernel) => factory.Create <IPaintingsService>(kernel.Resolve <Flickr>())
                                   ));
        }
Esempio n. 41
0
        public override void OnClick()
        {
            //var bruTileAboutBox = new BruTileAboutBox();
            //bruTileAboutBox.ShowDialog(new ArcMapWindow(_application));

            var fileCache          = new FileCache(@"c:\aaa\tiles", "png");
            var osmTileSource      = new OsmTileSource();
            var mxdoc              = (IMxDocument)_application.Document;
            var map                = mxdoc.FocusMap;
            var brutileCustomLayer = new BruTileCustomLayer(_application, osmTileSource, fileCache)
            {
                Name = "testlayer"
            };

            map.AddLayer(brutileCustomLayer);
        }
Esempio n. 42
0
        public static FileCache GetFileCache(string baseCacheDir, IConfig config,EnumBruTileLayer enumBruTileLayer)
        {
            var schema = config.CreateTileSource().Schema;

            var cacheDirType = GetCacheDirectory(config, enumBruTileLayer, baseCacheDir);

            var format = schema.Format;

            if (format.Contains(@"image/"))
            {
                format = format.Substring(6, schema.Format.Length - 6);
            }
            if (format.Contains("png8"))
            {
                format = format.Replace("png8", "png");
            }
            var fileCache = new FileCache(cacheDirType, format);

            return fileCache;
        }
Esempio n. 43
0
        public void Configuration(IAppBuilder app)
        {
            var cachePath = RoleEnvironment.IsAvailable ?
                RoleEnvironment.GetLocalResource("fileCache").RootPath :
                Path.Combine(Path.GetTempPath(), "XML2JSON.Web.OWIN");

            Directory.CreateDirectory(cachePath);

            var cache = new FileCache(cachePath);

            cache.MaxCacheSize = RoleEnvironment.IsAvailable ?
                RoleEnvironment.GetLocalResource("fileCache").MaximumSizeInMegabytes * 1024 :
                2048 * 1024; //2GB

            //when the max size is reached, purge everything more than 24 hours old and hope for the best!
            cache.MaxCacheSizeReached += (s, e) => cache.Flush(DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)));

            var router = new RequestRouter { Cache = cache };

            app.Run(router.HandleRequest);
        }
Esempio n. 44
0
        public BruTileCustomLayer(IApplication application, TileSource tileSource, FileCache fileCache)
        {
            _tileSource = tileSource;
            _fileCache = fileCache;
            _simplefilefetcher = new SimpleFileFetcher(tileSource, fileCache);
            var spatialReferences = new SpatialReferences();
            _dataSpatialReference = spatialReferences.GetSpatialReference(_tileSource.Schema.Srs);

            if (SpatialReference.FactoryCode == 0)
            {
                // zet dan de spatial ref...
                m_spatialRef = _dataSpatialReference;
            }
            var mxdoc = (IMxDocument)application.Document;
            _map = mxdoc.FocusMap;
            var envelope = GetDefaultEnvelope();

            // If there is only one layer in the TOC zoom to this layer...
            if (_map.LayerCount == 0)
            {
                ((IActiveView)_map).Extent = envelope;
            }
        }
Esempio n. 45
0
        public void DoMainTask(DateTime time,string _extent,string basePath,string tileDir,string csv)
        {
            this.basePath = basePath;
            this.csv = csv;

            extent = _extent.Split(new[] { ',' }).Select(Convert.ToDouble).ToList();
            _config = ConfigHelper.GetConfig(EnumBruTileLayer.OSM);
            _tileSource = _config.CreateTileSource();
            _tileProvider = (WebTileProvider)_tileSource.Provider;

            _cacheDir = CacheSettings.GetCacheFolder(tileDir);

            while (true)
            {
                try
                {
                    DeleteDirectory(_cacheDir);
                    break;
                }
                catch (Exception ex)
                {
                    LogManager.LogPath = AppDomain.CurrentDomain.BaseDirectory + "\\log\\";
                    LogManager.WriteLog("error", ex.Message);
                }
            }

            _fileCache = CacheDirectory.GetFileCache(_cacheDir, _config, EnumBruTileLayer.OSM);
            Draw();
            var map = mosaicImage();
            DirectoryInfo directory =
                new DirectoryInfo(basePath + time.ToString("yyyy") + "\\" + time.ToString("yyyyMMdd") + "\\" +
                                  time.ToString("yyyyMMddHHmm"));
            if(!directory.Exists)
                directory.Create();
            map.Save(directory.FullName + "\\traffic.png");
            CreateTrafficCsv(directory);
        }
Esempio n. 46
0
        /// <summary>
        /// 水印图片
        /// 【如果图片需要缩略,请使用skeletonize.Resizepic()方法对图片进行缩略】
        /// 返回图片虚拟路径,和一个警告信息,可根据此信息获取图片合成信息
        /// </summary>
        /// <param name="picpath">需要水印的图片路径</param>
        /// <param name="waterspath">水印图片路径</param>
        /// <param name="watermodel">水印模式</param>
        /// <param name="spath">文件保存路径</param>
        /// <param name="imgtype">保存文件类型</param>
        /// <param name="filecache">原文件处理方式</param>
        /// <param name="warning">处理警告信息</param>
        /// <returns>错误,返回错误信息;成功,返回图片路径</returns>
        public static string makewatermark(string picpath, string waterspath, WaterType watermodel, string spath, ImageType imgtype, FileCache filecache, out string warning)
        {
            #region
            //反馈信息
            System.Text.StringBuilder checkmessage = new System.Text.StringBuilder();

            //检测源文件
            string _sourceimg_common_mappath = "";
            bool checkfile = false;

            //检测水印源文件
            string _sourceimg_water_mappath = "";
            bool checkfilewater = false;

            checkfile = FileExistMapPath(picpath, FileCheckModel.C, out _sourceimg_common_mappath);
            checkfilewater = FileExistMapPath(waterspath, FileCheckModel.C, out _sourceimg_water_mappath);

            System.Drawing.Image _sourceimg_common = null;
            System.Drawing.Image _sourceimg_water = null;

            if (checkfile == true)
            {
                //从指定源文件,创建image对象
                _sourceimg_common = System.Drawing.Image.FromFile(_sourceimg_common_mappath);
            }
            else
            {
                checkmessage.Append("error:找不到需要的水印图片!" + picpath + ";");
            }
            if (checkfilewater == true)
            {
                //从指定源文件,创建image对象
                _sourceimg_water = System.Drawing.Image.FromFile(_sourceimg_water_mappath);
            }
            else
            {
                checkmessage.Append("error:找不到需要水印图片!" + waterspath + ";");
            }
            #endregion

            #region
            if (string.IsNullOrEmpty(checkmessage.ToString()))
            {
                //源图宽、高
                int _sourceimg_common_width = _sourceimg_common.Width;
                int _sourceimg_common_height = _sourceimg_common.Height;

                //水印图片宽、高
                int _sourceimg_water_width = _sourceimg_water.Width;
                int _sourceimg_water_height = _sourceimg_water.Height;

                #region 水印坐标
                //水印坐标
                int _sourceimg_water_point_x = 0;
                int _sourceimg_water_point_y = 0;

                switch (watermodel)
                {
                    case WaterType.Center:
                        _sourceimg_water_point_x = (_sourceimg_common_width - _sourceimg_water_width) / 2;
                        _sourceimg_water_point_y = (_sourceimg_common_height - _sourceimg_water_height) / 2;
                        ; break;
                    case WaterType.CenterDown:
                        _sourceimg_water_point_x = (_sourceimg_common_width - _sourceimg_water_width) / 2;
                        _sourceimg_water_point_y = _sourceimg_common_height - _sourceimg_water_height;
                        ; break;
                    case WaterType.CenterUp:
                        _sourceimg_water_point_x = (_sourceimg_common_width - _sourceimg_water_width) / 2;
                        _sourceimg_water_point_y = 0;
                        ; break;
                    case WaterType.LeftDown:
                        _sourceimg_water_point_x = 0;
                        _sourceimg_water_point_y = _sourceimg_common_height - _sourceimg_water_height;
                        ; break;
                    case WaterType.LeftUp:
                        ; break;
                    case WaterType.Random:
                        Random r = new Random();
                        int x_random = r.Next(0, _sourceimg_common_width);
                        int y_random = r.Next(0, _sourceimg_common_height);

                        _sourceimg_water_point_x = x_random > (_sourceimg_common_width - _sourceimg_water_width)
                            ? _sourceimg_common_width - _sourceimg_water_width : x_random;

                        _sourceimg_water_point_y = y_random > (_sourceimg_common_height - _sourceimg_water_height)
                            ? _sourceimg_common_height - _sourceimg_water_height : y_random;

                        ; break;
                    case WaterType.RightDown:
                        _sourceimg_water_point_x = _sourceimg_common_width - _sourceimg_water_width;
                        _sourceimg_water_point_y = _sourceimg_common_height - _sourceimg_water_height;
                        ; break;
                    case WaterType.RightUp:
                        _sourceimg_water_point_x = _sourceimg_common_width - _sourceimg_water_width;
                        _sourceimg_water_point_y = 0;
                        ; break;
                }
                #endregion

                //从源图创建画板
                System.Drawing.Graphics _g_common = Graphics.FromImage(_sourceimg_common);

                //设置画笔
                _g_common.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
                _g_common.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                _g_common.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;

                //绘制水印图片
                _g_common.DrawImage(_sourceimg_water, new Rectangle(_sourceimg_water_point_x, _sourceimg_water_point_y, _sourceimg_water_width, _sourceimg_water_height), new Rectangle(0, 0, _sourceimg_water_width, _sourceimg_water_height), GraphicsUnit.Pixel);

                //保存图片
                string _spath_common_mappath = "";
                //全局文件名

                //获取图片类型的hashcode值,生成图片后缀名
                int extro = imgtype.GetHashCode();
                string extend = extro == 0 ? ".jpg" : (extro == 1 ? ".gif" : (extro == 2 ? ".png" : ".jpg"));

                spath = spath + Guid.NewGuid().ToString() + extend;

                FileExistMapPath(spath, FileCheckModel.M, out _spath_common_mappath);

                switch (imgtype)
                {
                    case ImageType.JPEG: _sourceimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Jpeg); break;
                    case ImageType.GIF: _sourceimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Gif); break;
                    case ImageType.PNG: _sourceimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Png); break;
                }

                //释放
                _sourceimg_common.Dispose();
                _sourceimg_water.Dispose();
                _g_common.Dispose();

                //处理原文件
                int filecachecode = filecache.GetHashCode();
                //删除原文件
                if (filecachecode == 1)
                {
                    System.IO.File.Delete(_sourceimg_common_mappath);
                }

                warning = "";
                return spath;

            }
            #endregion

            //释放
            if (_sourceimg_common != null)
            {
                _sourceimg_common.Dispose();
            }
            if (_sourceimg_water != null)
            {
                _sourceimg_water.Dispose();
            }

            warning = checkmessage.ToString().TrimEnd(';');
            return "";
        }
Esempio n. 47
0
 /// <summary>
 /// Creates an instance of this class
 /// </summary>
 /// <param name="tileSource">The tile source</param>
 /// <param name="layerName">The layers name</param>
 /// <param name="transparentColor">The color that should be treated as <see cref="Color.Transparent"/></param>
 /// <param name="showErrorInTile">Value indicating that an error tile should be generated for non-existent tiles</param>
 /// <param name="fileCache">If the layer should use a file-cache so store tiles, set this to a fileCacheProvider. Set to null to avoid filecache</param>
 /// <param name="imgFormat">Set the format of the tiles to be used</param>
 public TileAsyncLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, FileCache fileCache, ImageFormat imgFormat)
     : base(tileSource, layerName, transparentColor, showErrorInTile, fileCache,imgFormat)
 {
 }
Esempio n. 48
0
        public void DownloadImages( string rockUrl, FileCache.FileDownloaded onResult )
        {
            DownloadImage( LogoURL, LogoImageName, rockUrl, null );
            DownloadImage( BackgroundURL, BackgroundImageName, rockUrl, null );
            DownloadImage( AdultMaleNoPhoto, AdultMaleNoPhotoName, rockUrl, null );
            DownloadImage( AdultFemaleNoPhoto, AdultFemaleNoPhotoName, rockUrl, null );
            DownloadImage( ChildMaleNoPhoto, ChildMaleNoPhotoName, rockUrl, null );
            DownloadImage( ChildFemaleNoPhoto, ChildFemaleNoPhotoName, rockUrl, null );

            // dont make them wait.
            onResult( true );
        }
Esempio n. 49
0
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        /// <param name="tileSource">the source to get the tiles from</param>
        /// <param name="layerName">name of the layer</param>
        /// <param name="transparentColor">transparent color off</param>
        /// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
        /// <param name="fileCache">If the layer should use a file-cache so store tiles, set this to a fileCacheProvider. Set to null to avoid filecache</param>
        /// <param name="imgFormat">Set the format of the tiles to be used</param>
        public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, FileCache fileCache, ImageFormat imgFormat)
        {
            _source = tileSource;
            LayerName = layerName;
            _transparentColor = transparentColor;
            _showErrorInTile = showErrorInTile;

            _fileCache = fileCache;
            _ImageFormat = imgFormat;
        }
Esempio n. 50
0
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        /// <param name="tileSource">the source to get the tiles from</param>
        /// <param name="layerName">name of the layer</param>
        /// <param name="transparentColor">transparent color off</param>
        /// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
        /// <param name="fileCacheDir">If the layer should use a file-cache so store tiles, set this to that directory. Set to null to avoid filecache</param>
        /// <remarks>If <paramref name="showErrorInTile"/> is set to false, tile source keeps trying to get the tile in every request</remarks>
        public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, string fileCacheDir)
        {
            _source = tileSource;
            LayerName = layerName;
            _transparentColor = transparentColor;
            _showErrorInTile = showErrorInTile;

            if (!string.IsNullOrEmpty(fileCacheDir))
            {
                _fileCache = new FileCache(fileCacheDir, "png");
                _ImageFormat = ImageFormat.Png;
            }
        }
Esempio n. 51
0
        void DownloadImage( string imageUrl, string imageFileName, string rockUrl, FileCache.FileDownloaded onResult )
        {
            if ( string.IsNullOrWhiteSpace( imageUrl ) == false )
            {
                string qualifiedUrl;
                if ( imageUrl[ 0 ] == '~' )
                {
                    qualifiedUrl = imageUrl.Replace( "~", rockUrl );
                }
                else
                {
                    qualifiedUrl = imageUrl;
                }

                FileCache.Instance.DownloadFileToCache( qualifiedUrl, imageFileName, FileCache.CacheFileNoExpiration, onResult );
            }
        }
Esempio n. 52
0
 public IList<TileInfo> GetTilesMissing(IEnumerable<TileInfo> tilesWanted, FileCache fileCache)
 {
     return tilesWanted.Where(
         info => fileCache.Find(info.Index) == null).ToList();
 }
Esempio n. 53
0
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        /// <param name="tileSource">the source to get the tiles from</param>
        /// <param name="layerName">name of the layer</param>
        /// <param name="transparentColor">transparent color off</param>
        /// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
        /// <param name="fileCache">If the layer should use a file-cache so store tiles, set this to a fileCacheProvider. Set to null to avoid filecache</param>
        /// <param name="imgFormat">Set the format of the tiles to be used</param>
        public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, BruTile.Cache.FileCache fileCache, ImageFormat imgFormat)
        {
            _source = tileSource;
            LayerName = layerName;
            if (!transparentColor.IsEmpty)
                _imageAttributes.SetColorKey(transparentColor, transparentColor);
            _showErrorInTile = showErrorInTile;

#if !PocketPC
            _imageAttributes.SetWrapMode(WrapMode.TileFlipXY);
#endif
            _fileCache = fileCache;
            _ImageFormat = imgFormat;
        }
Esempio n. 54
0
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        /// <param name="tileSource">the source to get the tiles from</param>
        /// <param name="layerName">name of the layer</param>
        /// <param name="transparentColor">transparent color off</param>
        /// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
        /// <param name="fileCacheDir">If the layer should use a file-cache so store tiles, set this to that directory. Set to null to avoid filecache</param>
        /// <remarks>If <see cref="showErrorInTile"/> is set to false, tile source keeps trying to get the tile in every request</remarks>
        public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, string fileCacheDir)
        {
            _source = tileSource;
            LayerName = layerName;
            if (!transparentColor.IsEmpty)
                _imageAttributes.SetColorKey(transparentColor, transparentColor);
            _showErrorInTile = showErrorInTile;

#if !PocketPC
            _imageAttributes.SetWrapMode(WrapMode.TileFlipXY);
#endif
            if (!string.IsNullOrEmpty(fileCacheDir))
            {
                _fileCache = new BruTile.Cache.FileCache(fileCacheDir, "png");
                _ImageFormat = ImageFormat.Png;
            }
        }
Esempio n. 55
0
 public FileTileProvider(FileCache fileCache)
 {
     _fileCache = fileCache;
 }
Esempio n. 56
0
 public FileTileProvider(string directory, string format, TimeSpan cacheExpireTime)
 {
     _fileCache = new FileCache(directory, format, cacheExpireTime);
 }
Esempio n. 57
0
        /// <summary>
        /// 根据指定:缩略宽、高,缩略图片并保存
        /// 返回图片虚拟路径,和一个警告信息,可根据此信息获取图片合成信息
        /// </summary>
        /// <param name="picpath">原图路径</param>
        /// <param name="model">缩略模式[X,Y,XY](默认XY模式)</param>
        /// <param name="spath">文件保存路径(默认跟路径)</param>
        /// <param name="imgtype">图片保存类型</param>
        /// <param name="mwidth">缩略宽度(默认原图高度)</param>
        /// <param name="mheight">缩略高度(默认原图高度)</param>
        /// <param name="filecache">原文件处理方式</param>
        /// <param name="warning">处理警告信息</param>
        /// <returns>错误,返回错误信息;成功,返回图片路径</returns>
        public static string Resizepic(string picpath, ResizeType model, string spath, ImageType imgtype, double? mwidth, double? mheight, FileCache filecache, out string warning)
        {
            //反馈信息
            System.Text.StringBuilder checkmessage = new System.Text.StringBuilder();

            //文件保存路径
            spath = string.IsNullOrEmpty(spath) ? "/" : spath;

            //缩略宽度
            double swidth = mwidth.HasValue ? double.Parse(mwidth.ToString()) : 0;

            //缩略高度
            double sheight = mheight.HasValue ? double.Parse(mheight.ToString()) : 0;

            //从指定源图片,创建image对象
            string _sourceimg_common_mappath = "";

            //检测源文件
            bool checkfile = false;
            checkfile = FileExistMapPath(picpath, FileCheckModel.C, out _sourceimg_common_mappath);

            System.Drawing.Image _sourceimg_common = null;
            System.Drawing.Bitmap _currimg_common = null;
            System.Drawing.Graphics _g_common = null;

            if (checkfile == true)
            {
                //从源文件创建imgage
                _sourceimg_common = System.Drawing.Image.FromFile(_sourceimg_common_mappath);

                #region 缩略模式
                //缩略模式
                switch (model)
                {
                    case ResizeType.X:

                        #region X模式

                        //根据给定尺寸,获取绘制比例
                        double _width_scale = swidth / _sourceimg_common.Width;
                        //高着比例
                        sheight = _sourceimg_common.Height * _width_scale;

                        #endregion
                        ; break;
                    case ResizeType.Y:
                        #region Y模式

                        //根据给定尺寸,获取绘制比例
                        double _height_scale = sheight / _sourceimg_common.Height;
                        //宽着比例
                        swidth = _sourceimg_common.Width * _height_scale;

                        #endregion
                        ; break;
                    case ResizeType.XY:
                        #region XY模式

                        //当选择XY模式时,mwidth,mheight为必须值
                        if (swidth < 0 || sheight < 0)
                        {
                            checkmessage.Append("error:XY模式,mwidth,mheight为必须值;");
                        }

                        #endregion
                        ; break;
                    default:

                        #region 默认XY模式

                        //当默认XY模式时,mwidth,mheight为必须值
                        if (swidth < 0 || sheight < 0)
                        {
                            checkmessage.Append("error:你当前未选择缩略模式,系统默认XY模式,mwidth,mheight为必须值;");
                        }

                        ; break;
                        #endregion
                }
                #endregion
            }
            else
            {
                checkmessage.Append("error:未能找到缩略原图片," + picpath + ";");
            }

            if (string.IsNullOrEmpty(checkmessage.ToString()))
            {
                //创建bitmap对象
                _currimg_common = new System.Drawing.Bitmap((int)swidth, (int)sheight);

                _g_common = Graphics.FromImage(_currimg_common);

                //设置画笔
                _g_common.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
                _g_common.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                _g_common.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;

                //绘制图片
                _g_common.DrawImage(_sourceimg_common, new Rectangle(0, 0, (int)swidth, (int)sheight), new Rectangle(0, 0, _sourceimg_common.Width, _sourceimg_common.Height), GraphicsUnit.Pixel);

                //保存图片
                string _spath_common_mappath = "";

                //获取图片类型的hashcode值,生成图片后缀名
                int extro = imgtype.GetHashCode();

                string extend = extro == 0 ? ".jpg" : (extro == 1 ? ".gif" : (extro == 2 ? ".png" : ".jpg"));

                //全局文件名
                spath = spath + Guid.NewGuid().ToString() + extend;

                FileExistMapPath(spath, FileCheckModel.M, out _spath_common_mappath);

                switch (imgtype)
                {
                    case ImageType.JPEG: _currimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Jpeg); break;
                    case ImageType.GIF: _currimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Gif); break;
                    case ImageType.PNG: _currimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Png); break;
                }

                //释放
                _sourceimg_common.Dispose();
                _currimg_common.Dispose();
                _g_common.Dispose();

                //处理原文件
                int filecachecode = filecache.GetHashCode();

                //文件缓存方式:Delete,删除原文件
                if (filecachecode == 1)
                {
                    System.IO.File.Delete(_sourceimg_common_mappath);
                }

                //返回相对虚拟路径
                warning = "";
                return spath;
            }

            //释放
            if (_sourceimg_common != null)
            {
                _sourceimg_common.Dispose();
            }
            if (_currimg_common != null)
            {
                _currimg_common.Dispose();
            }
            if (_g_common != null)
            {
                _g_common.Dispose();
            }

            warning = checkmessage.ToString().TrimEnd(';');

            return "";
        }
Esempio n. 58
0
        private LuceneLoggerBackend()
        {
            indexDirectory = Path.Combine(TemporaryFilesManager.Instance.EmulatorTemporaryPath, "index");
            var directory = FSDirectory.Open(indexDirectory);
            analyzer = new StandardAnalyzer(LuceneNet.Util.Version.LUCENE_30);
            writer = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.LIMITED);

            writer.UseCompoundFile = false;

            logLevel = LogLevel.Noisy;
            searcher = new Searcher(directory, analyzer);

            cache = new FileCache();
        }
Esempio n. 59
0
        private void Receive(SendMode mode, LinccerContentCallback contentCallback, FileCacheGetCallback fileCallback)
        {
            var stringMode = SendModeString.ConvertSendModeToString(mode);
            // receive 1:1, in the Hoccer mobile App, you need to perform a drag out
            // gesture to send something to this client (one-to-many is throw/catch)
            this._linccer.Receive<Hoc>(stringMode, (hoc) =>
            {
                if (hoc == null)
                {
                    contentCallback(null);
                }
                else
                {
                    if(hoc.DataList.Any(x => x.Type == "text/plain"))
                    {
                        contentCallback(String.Join(",", hoc.DataList.Where(x => x.Type == "text/plain").Select(x => x.Content)));
                        return;
                    }

                    var data = hoc.DataList.FirstOrDefault(x => x.Uri != string.Empty);

                    //// inialize filecache for temporary up- and downloading large files
                    var cache = new FileCache();
                    cache.Config = this._config;
                    cache.Fetch(data.Uri, fileCallback);
                }
            });
        }
Esempio n. 60
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <param name="mode">one-to-many / one-to-one</param>
        /// <param name="callback"></param>
        private void SendData(byte[] data, SendMode mode, LinccerContentCallback callback)
        {
            // inialize filecache for temporary up- and downloading large files
            var cache = new FileCache();
            cache.Config = this._config;

            cache.Store(data, TIMEOUT, (uri) =>
            {
                Hoc hoc = new Hoc();
                hoc.DataList.Add(
                    new HocData { Uri = uri }
                );

                var stringMode = SendModeString.ConvertSendModeToString(mode);
                // share it 1:1, in the Hoccer mobile App, you need to perform a drag in
                // gesture to receive the message  (one-to-many is throw/catch)
                this._linccer.Share(stringMode, hoc, callback);
            });
        }