Exemplo n.º 1
0
            public void ReturnsRightValueForExistingKey()
            {
                var cache = new CacheStorage<string, int>();
                cache.Add("1", 1);
                cache.Add("2", 2);

                Assert.AreEqual(2, cache.Get("2"));
            }
Exemplo n.º 2
0
            public void ThrowsArgumentNullExceptionForNullKey()
            {
                var cache = new CacheStorage<string, int>();

                ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() =>
                {
                    var value = cache.Get(null);
                    Assert.IsNull(value);
                });
            }
Exemplo n.º 3
0
            public void ReturnsCachedItem()
            {
                var cache = new CacheStorage <string, int>();

                cache.Add("1", 1);
                var value = cache.GetFromCacheOrFetch("1", () => 2);

                Assert.IsTrue(cache.Contains("1"));
                Assert.AreEqual(1, cache["1"]);
                Assert.AreEqual(1, value);
            }
Exemplo n.º 4
0
            public void AddsItemToCacheWithOverrideAndReturnsIt()
            {
                var cache = new CacheStorage <string, int>();

                cache.Add("1", 1);
                var value = cache.GetFromCacheOrFetch("1", () => 2, true);

                Assert.IsTrue(cache.Contains("1"));
                Assert.AreEqual(2, cache["1"]);
                Assert.AreEqual(2, value);
            }
Exemplo n.º 5
0
 public static int LoadTexture(string filename, CacheStorage cache)
 {
     if (Listfile.TryGetFileDataID(filename, out var filedataid))
     {
         return(LoadTexture(filedataid, cache));
     }
     else
     {
         throw new Exception("Couldn't find filedataid for file " + filename + " in listfile!");
     }
 }
Exemplo n.º 6
0
            public void AutomaticallyRemovesExpiredItemsOfACacheStorageWithDefaultExpirationPolicyInitializationCode()
            {
                var cache = new CacheStorage <string, int>(() => ExpirationPolicy.Duration(TimeSpan.FromMilliseconds(500)));

                cache.Add("1", 1);

                Assert.IsTrue(cache.Contains("1"));

                ThreadHelper.Sleep(2000);

                Assert.IsFalse(cache.Contains("1"));
            }
Exemplo n.º 7
0
            public void AutomaticallyRemovesExpiredItems()
            {
                var cache = new CacheStorage <string, int>();

                cache.Add("1", 1, expiration: new TimeSpan(0, 0, 1));

                Assert.IsTrue(cache.Contains("1"));

                ThreadHelper.Sleep(2000);

                Assert.IsFalse(cache.Contains("1"));
            }
Exemplo n.º 8
0
            public void RemovesExistingValue()
            {
                var cache = new CacheStorage <string, int>();

                cache.Add("1", 1);

                Assert.IsTrue(cache.Contains("1"));

                cache.Remove("1");

                Assert.IsFalse(cache.Contains("1"));
            }
Exemplo n.º 9
0
 public static void Set <T>(string key, T value)
 {
     CacheStorage.Set(key + Postfix, DateTime.Now);
     if (SimpleSerialization.IsSupported <T>())
     {
         CacheStorage.Set(key, value);
     }
     else
     {
         CacheStorage.Storage.SetObject(key, value);
     }
 }
Exemplo n.º 10
0
        public static void SetShared(string filename, string url)
        {
            var name = Path.GetFileName(filename)?.ApartFromLast(ReplayObject.ReplayExtension, StringComparison.OrdinalIgnoreCase);
            var info = new FileInfo(filename);

            if (name == null || !info.Exists)
            {
            }
            else
            {
                CacheStorage.Set($@"sharedReplay:{name.ToLowerInvariant()}:{info.Length}", url);
            }
        }
Exemplo n.º 11
0
            public void AddsAndExpiresSeveralItems()
            {
                var cache = new CacheStorage <string, int>();

                for (int i = 0; i < 5; i++)
                {
                    var value = cache.GetFromCacheOrFetch("key", () => i, expiration: new TimeSpan(0, 0, 1));

                    Assert.AreEqual(i, value);

                    ThreadHelper.Sleep(2000);
                }
            }
Exemplo n.º 12
0
 public character(CacheStorage cacheStorage, CharacterDB db, ChatDB chatDB, ItemManager itemManager, TypeManager typeManager, Logger logger, Configuration.Character configuration, NodeContainer container)
 {
     this.Log              = logger.CreateLogChannel("character");
     this.mConfiguration   = configuration;
     this.DB               = db;
     this.ChatDB           = chatDB;
     this.ItemManager      = itemManager;
     this.TypeManager      = typeManager;
     this.CacheStorage     = cacheStorage;
     this.Container        = container;
     this.mBloodlineCache  = this.DB.GetBloodlineInformation();
     this.mAncestriesCache = this.DB.GetAncestryInformation(this.mBloodlineCache);
 }
Exemplo n.º 13
0
            public void RunMultipleThreadsWithRandomAccessCalls()
            {
                var cacheStorage = new CacheStorage <Guid, int>(() => ExpirationPolicy.Duration(TimeSpan.FromMilliseconds(1)));

                var threads = new List <Thread>();

                for (int i = 0; i < 25; i++)
                {
                    var thread = new Thread(() =>
                    {
                        var random = new Random();

                        for (int j = 0; j < 10000; j++)
                        {
                            var randomGuid = _randomGuids[random.Next(0, 9)];
                            cacheStorage.GetFromCacheOrFetch(randomGuid, () =>
                            {
                                var threadId = Thread.CurrentThread.ManagedThreadId;
                                Log.Info("Key '{0}' is now controlled by thread '{1}'", randomGuid, threadId);
                                return(threadId);
                            });

                            ThreadHelper.Sleep(1);
                        }
                    });

                    threads.Add(thread);
                    thread.Start();
                }

                while (true)
                {
                    bool anyThreadAlive = false;

                    foreach (var thread in threads)
                    {
                        if (thread.IsAlive)
                        {
                            anyThreadAlive = true;
                            break;
                        }
                    }

                    if (!anyThreadAlive)
                    {
                        break;
                    }

                    ThreadHelper.Sleep(500);
                }
            }
Exemplo n.º 14
0
            public void RunMultipleThreadsWithRandomAccessCalls()
            {
                var cacheStorage = new CacheStorage<Guid, int>(() => ExpirationPolicy.Duration(TimeSpan.FromMilliseconds(1)));

                var threads = new List<Thread>();
                for (int i = 0; i < 25; i++)
                {
                    var thread = new Thread(() =>
                    {
                        var random = new Random();

                        for (int j = 0; j < 10000; j++)
                        {
                            var randomGuid = _randomGuids[random.Next(0, 9)];
                            cacheStorage.GetFromCacheOrFetch(randomGuid, () =>
                            {
                                var threadId = Thread.CurrentThread.ManagedThreadId;
                                Log.Info("Key '{0}' is now controlled by thread '{1}'", randomGuid, threadId);
                                return threadId;
                            });

                            ThreadHelper.Sleep(1);
                        }
                    });

                    threads.Add(thread);
                    thread.Start();
                }

                while (true)
                {
                    bool anyThreadAlive = false;

                    foreach (var thread in threads)
                    {
                        if (thread.IsAlive)
                        {
                            anyThreadAlive = true;
                            break;
                        }
                    }

                    if (!anyThreadAlive)
                    {
                        break;
                    }

                    ThreadHelper.Sleep(500);
                }
            }
Exemplo n.º 15
0
            public void AutomaticallyRemovesExpiredItems()
            {
                var cache = new CacheStorage <string, int>();

                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                cache.Add("1", 1, expiration: new TimeSpan(0, 0, 0, 0, 250));

                Assert.IsTrue(cache.Contains("1"));

                ThreadHelper.Sleep(750);

                Assert.IsFalse(cache.Contains("1"));
            }
Exemplo n.º 16
0
            public void AddsAndExpiresSeveralItems()
            {
                var cache = new CacheStorage <string, int>();

                for (int i = 0; i < 5; i++)
                {
                    ThreadHelper.Sleep(2000);

                    int innerI = i;
                    var value  = cache.GetFromCacheOrFetch("key", () => innerI, expiration: TimeSpan.FromMilliseconds(500));

                    Assert.AreEqual(i, value);
                }
            }
Exemplo n.º 17
0
            public void IsAutomaticallyEnabledWhenStartedDisabledButAddingItemWithCustomExpirationPolicy()
            {
                var cache = new CacheStorage <string, int>();

                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                cache.Add("1", 1, expiration: new TimeSpan(0, 0, 0, 0, 250));

                Assert.IsTrue(cache.Contains("1"));

                ThreadHelper.Sleep(750);

                Assert.IsFalse(cache.Contains("1"));
            }
Exemplo n.º 18
0
            public void DoesNotDisposeItemsOnClearWhenDisposingNotEnabled()
            {
                var disposable = new CustomDisposable();
                var cache      = new CacheStorage <string, CustomDisposable>();

                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                cache.Add("disposable", disposable, expiration: TimeSpan.FromMilliseconds(250));

                Assert.IsFalse(disposable.IsDiposed);

                cache.Clear();

                Assert.IsFalse(disposable.IsDiposed);
            }
Exemplo n.º 19
0
        public void CacheStorage_Count()
        {
            var cacheStorage = new CacheStorage <string>();

            Assert.AreEqual(0, cacheStorage.Count);

            var e1 = cacheStorage.GetEntry("foo");
            var e2 = cacheStorage.GetEntry("bar");

            Assert.AreEqual(2, cacheStorage.Count);

            cacheStorage.ReleaseEntry(e1);
            cacheStorage.ReleaseEntry(e2);
            Assert.AreEqual(0, cacheStorage.Count);
        }
Exemplo n.º 20
0
            public void DisposesItemOnRemoveWhenDisposingEnabled()
            {
                var disposable = new CustomDisposable();
                var cache      = new CacheStorage <string, CustomDisposable>();

                cache.DisposeValuesOnRemoval  = true;
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                cache.Add("disposable", disposable, expiration: TimeSpan.FromMilliseconds(250));

                Assert.IsFalse(disposable.IsDiposed);

                cache.Remove("disposable");

                Assert.IsTrue(disposable.IsDiposed);
            }
Exemplo n.º 21
0
            private void RunMultipleThreadsWithRandomAccessCalls(Func <ICacheStorage <Guid, int>, Guid, int> retrievalFunc)
            {
                var cacheStorage = new CacheStorage <Guid, int>(() => ExpirationPolicy.Duration(TimeSpan.FromMilliseconds(250)));

                var threads = new List <Thread>();

                for (var i = 0; i < 50; i++)
                {
                    var thread = new Thread(() =>
                    {
                        var random = new Random();

                        for (var j = 0; j < 1000; j++)
                        {
                            var randomGuid = _randomGuids[random.Next(0, 9)];

                            retrievalFunc(cacheStorage, randomGuid);

                            ThreadHelper.Sleep(10);
                        }
                    });

                    threads.Add(thread);
                    thread.Start();
                }

                while (true)
                {
                    var anyThreadAlive = false;

                    foreach (var thread in threads)
                    {
                        if (thread.IsAlive)
                        {
                            anyThreadAlive = true;
                            break;
                        }
                    }

                    if (!anyThreadAlive)
                    {
                        break;
                    }

                    ThreadHelper.Sleep(500);
                }
            }
Exemplo n.º 22
0
        public static async Task <string> PostOnlineDataAsync(ServerInformationExtra data, CancellationToken cancellation = default(CancellationToken))
        {
            try {
                var json     = JsonConvert.SerializeObject(data);
                var key      = ".PostedOnlineData:" + json.GetChecksum();
                var uploaded = CacheStorage.Get <string>(key);
                if (uploaded != null)
                {
                    return(uploaded);
                }

                var id = await InternalUtils.PostOnlineDataAsync(json, UserAgent, cancellation);

                if (id != null)
                {
                    CacheStorage.Set(key, id);
                    LazierCached.Set(@".OnlineData:" + id, data);
                }

                return(id);
            } catch (Exception e) when(e.IsCancelled())
            {
            } catch (WebException e) when(e.Response is HttpWebResponse h)
            {
                try {
                    var s = h.GetResponseStream()?.ReadAsStringAndDispose();
                    if (s != null)
                    {
                        var o = JObject.Parse(s);
                        if (o["error"] != null)
                        {
                            NonfatalError.NotifyBackground($"Can’t share online data: {o["error"].ToString().ToSentenceMember()}",
                                                           o["details"]?.ToString().ToSentence());
                            return(null);
                        }
                    }
                    NonfatalError.NotifyBackground($"Can’t share online data: {h.StatusDescription.ToLower()}", e);
                } catch (Exception ex) {
                    Logging.Warning(ex);
                    NonfatalError.NotifyBackground("Can’t share online data", e);
                }
            } catch (Exception e) {
                NonfatalError.NotifyBackground("Can’t share online data", e);
            }
            return(null);
        }
Exemplo n.º 23
0
            private void RunMultipleThreadsWithRandomAccessCalls(Func<ICacheStorage<Guid, int>, Guid, int> retrievalFunc)
            {
                var cacheStorage = new CacheStorage<Guid, int>(() => ExpirationPolicy.Duration(TimeSpan.FromMilliseconds(250)));

                var threads = new List<Thread>();
                for (var i = 0; i < 50; i++)
                {
                    var thread = new Thread(() =>
                    {
                        var random = new Random();

                        for (var j = 0; j < 1000; j++)
                        {
                            var randomGuid = _randomGuids[random.Next(0, 9)];

                            retrievalFunc(cacheStorage, randomGuid);

                            ThreadHelper.Sleep(10);
                        }
                    });

                    threads.Add(thread);
                    thread.Start();
                }

                while (true)
                {
                    var anyThreadAlive = false;

                    foreach (var thread in threads)
                    {
                        if (thread.IsAlive)
                        {
                            anyThreadAlive = true;
                            break;
                        }
                    }

                    if (!anyThreadAlive)
                    {
                        break;
                    }

                    ThreadHelper.Sleep(500);
                }
            }
Exemplo n.º 24
0
            public void DisposesExpiredItemWhenDisposingNotEnabledButForcedByEventArgs()
            {
                var disposable = new CustomDisposable();
                var cache      = new CacheStorage <string, CustomDisposable>();

                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);
                cache.Expired += (sender, e) =>
                {
                    e.Dispose = true;
                };

                cache.Add("disposable", disposable, expiration: TimeSpan.FromMilliseconds(250));

                ThreadHelper.Sleep(750);

                Assert.IsTrue(disposable.IsDiposed);
            }
Exemplo n.º 25
0
            public ViewModel([NotNull] ReplayObject acObject) : base(acObject)
            {
                UpdateAlreadyShared();

                _timeKey = @".ReplayTime:" + acObject.Id;
                Time     = acObject.AllowToOverrideTime
                        ? CacheStorage.Get(_timeKey, acObject.TimeFrom ?? FlexibleParser.ParseTime(@"09:00"))
                        : acObject.TimeFrom ?? FlexibleParser.ParseTime(@"09:00");

                if (acObject.AllowToOverrideTime)
                {
                    TimeSliderMapper = new DiapasonMapper(WeatherManager.Instance.GetById(acObject.WeatherId)?.GetTimeDiapason()
                                                          ?? Diapason.CreateTime(@"0:00-23:59"))
                    {
                        ActualValue = Time
                    };
                }
            }
Exemplo n.º 26
0
            public void DoesNotDisposeExpiredItemWhenDisposingEnabledButCanceledByEventArgs()
            {
                var disposable = new CustomDisposable();
                var cache      = new CacheStorage <string, CustomDisposable>();

                cache.DisposeValuesOnRemoval  = true;
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);
                cache.Expired += (sender, e) =>
                {
                    e.Dispose = false;
                };

                cache.Add("disposable", disposable, expiration: TimeSpan.FromMilliseconds(250));

                ThreadHelper.Sleep(750);

                Assert.IsFalse(disposable.IsDiposed);
            }
Exemplo n.º 27
0
        public static int LoadTexture(string filename, CacheStorage cache)
        {
            GL.ActiveTexture(TextureUnit.Texture0);

            filename = filename.ToLower();

            if (cache.materials.ContainsKey(filename))
            {
                // Console.WriteLine("[CACHE HIT] " + filename);
                return(cache.materials[filename]);
            }

            //Console.WriteLine("[CACHE MISS] " + filename);

            int textureId = GL.GenTexture();

            var blp = new BLPReader();

            blp.LoadBLP(filename);

            if (blp.bmp == null)
            {
                throw new Exception("BMP is null!");
            }
            else
            {
                GL.BindTexture(TextureTarget.Texture2D, textureId);
                cache.materials.Add(filename, textureId);
                System.Drawing.Imaging.BitmapData bmp_data = blp.bmp.LockBits(new System.Drawing.Rectangle(0, 0, blp.bmp.Width, blp.bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
                GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);

                blp.bmp.UnlockBits(bmp_data);
            }

            // Console.WriteLine("[CACHE ADD] " + filename);

            return(textureId);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Reclaim unused space (Copy the table in a temporary file, defragment and replace the original table)
        /// </summary>
        /// <returns>The number of bytes saved</returns>
        public async ValueTask <int> Defragment(CancellationToken cancellationToken = default)
        {
            ClearTrie();
            await ClearFileStream();

            // We copy the current table on a temporary file, then defragment that
            // once defragmentation is complete, we copy the temp file to the current table
            // this prevent corruption if anything happen on the middle of the defragmentation
            var fileName = await tx.Schema.GetFileNameOrCreate(tableName);

            var tmpFile = $"{fileName}_tmp";

            if (!await tx._Engine.Storages.Exists(fileName.ToString()))
            {
                return(0);
            }
            await tx._Engine.Storages.Copy(fileName.ToString(), tmpFile);

            int saved = 0;

            try
            {
                await using var fs = await tx._Engine.Storages.OpenStorage(tmpFile);

                await using var cache = new CacheStorage(fs, false, PagePool, true);
                var trie = await LTrie.OpenFromStorage(cache);

                saved = await trie.Defragment(cancellationToken);

                await cache.Flush();

                await fs.Flush();
            }
            catch
            {
                await tx._Engine.Storages.Delete(tmpFile);

                throw;
            }
            await tx._Engine.Storages.Move(tmpFile, fileName.ToString());

            return(saved);
        }
Exemplo n.º 29
0
            public void ItemStaysInCacheWhenExpiringEventIsCanceled()
            {
                var key   = "1";
                var value = 1;

                var cache = new CacheStorage <string, int>();

                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);
                cache.Expiring += (sender, e) =>
                {
                    e.Cancel = true;
                };

                cache.Add(key, value, expiration: new TimeSpan(0, 0, 0, 0, 250));

                ThreadHelper.Sleep(750);

                Assert.IsTrue(cache.Contains(key));
            }
Exemplo n.º 30
0
        /// <summary>
        /// Returns either a list of close contacts or a the value, if the node's storage contains the value for the key.
        /// </summary>
        public (List <Contact> contacts, string val) FindValue(Contact sender, ID key)
        {
            Validate.IsFalse <SendingQueryToSelfException>(sender.ID == ourContact.ID, "Sender should not be ourself!");
            SendKeyValuesIfNewContact(sender);
            bucketList.AddContact(sender);

            if (storage.Contains(key))
            {
                return(null, storage.Get(key));
            }
            else if (CacheStorage.Contains(key))
            {
                return(null, CacheStorage.Get(key));
            }
            else
            {
                // Exclude sender.
                return(bucketList.GetCloseContacts(key, sender.ID), null);
            }
        }
Exemplo n.º 31
0
        public static int LoadTexture(string filename, CacheStorage cache)
        {
            GL.ActiveTexture(TextureUnit.Texture0);

            filename = filename.ToLower();
            
            if (cache.materials.ContainsKey(filename))
            {
               // Console.WriteLine("[CACHE HIT] " + filename);
                return cache.materials[filename];
            }

            //Console.WriteLine("[CACHE MISS] " + filename);

            int textureId = GL.GenTexture();

            var blp = new BLPReader();

            blp.LoadBLP(filename);

            if (blp.bmp == null)
            {
                throw new Exception("BMP is null!");
            }
            else
            {
                GL.BindTexture(TextureTarget.Texture2D, textureId);
                cache.materials.Add(filename, textureId);
                System.Drawing.Imaging.BitmapData bmp_data = blp.bmp.LockBits(new System.Drawing.Rectangle(0, 0, blp.bmp.Width, blp.bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
                blp.bmp.UnlockBits(bmp_data);
            }

            // Console.WriteLine("[CACHE ADD] " + filename);

            return textureId;
        }
Exemplo n.º 32
0
        public override Task SaveAsync()
        {
            FullDetailsRequired();

            var json = new JObject();

            SaveData(json);
            CacheStorage.Set(_nameCacheKey, Name);

            Changed = false;
            using (CarsManager.Instance.IgnoreChanges()) {
                File.WriteAllText(JsonFilename, JsonConvert.SerializeObject(json, Formatting.Indented, new JsonSerializerSettings {
                    Formatting           = Formatting.Indented,
                    NullValueHandling    = NullValueHandling.Include,
                    DefaultValueHandling = DefaultValueHandling.Include,
                    Culture = CultureInfo.InvariantCulture
                }));
            }

            return(Task.Delay(0));
        }
Exemplo n.º 33
0
        private async Task <string> TryToFindAppIconAsync()
        {
            const string iconMissing = "_";

            var iconKey = $".AppIcon:{Id}";
            var result  = CacheStorage.Get <string>(iconKey);

            if (result != null)
            {
                return(result == iconMissing ? null : result);
            }

            var windows = await Windows.GetValueAsync();

            var icon = windows?.FirstOrDefault(x => string.Equals(x.DisplayName, Name, StringComparison.Ordinal))
                       ?? windows?.FirstOrDefault(x => string.Equals(x.DisplayName, Id, StringComparison.Ordinal))
                       ?? windows?.OrderBy(x => x.DisplayName.Length).FirstOrDefault();

            CacheStorage.Set(iconKey, icon?.IconOff ?? iconMissing);
            return(icon?.IconOff);
        }
Exemplo n.º 34
0
        private List <TItem> LoadFromCache()
        {
            if (_cacheKey == null)
            {
                return(null);
            }

            var list   = CacheStorage.GetStringList(_cacheKey);
            var result = new List <TItem>((list as IReadOnlyList <string>)?.Count ?? 50);

            foreach (var obj in list)
            {
                var item = LoadFromCache(obj);
                if (item != null)
                {
                    result.AddSorted(item, this);
                }
            }

            result.Capacity = result.Count;
            return(result);
        }
Exemplo n.º 35
0
        public static int Main(string[] args)
        {
            CultureInfo.DefaultThreadCurrentCulture   = CultureInfo.InvariantCulture;
            CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-US");

            try {
                var options = new Options();
                if (!Parser.Default.ParseArguments(args, options))
                {
                    return(1);
                }

                FilesStorage.Initialize(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AcTools Console Wrapper"));
                ValuesStorage.Initialize(null, null);
                CacheStorage.Initialize(null);
                LimitedSpace.Initialize();
                LimitedStorage.Initialize();
                DataProvider.Initialize();

                AcRootDirectory.Initialize(options.AcRoot);
                if (!AcRootDirectory.Instance.IsReady)
                {
                    Console.Error.WriteLine("Invalid AC root directory");
                    return(3);
                }

                Superintendent.Initialize();

                AsyncContext.Run(() => MainAsync(options));
                return(0);
            } catch (InformativeException e) {
                Console.Error.WriteLine(e.Message);
                return(2);
            } catch (Exception e) {
                Console.Error.WriteLine(e.ToString());
                return(2);
            }
        }
Exemplo n.º 36
0
            public void ThrowsArgumentNullExceptionForNullValueIfNotAllowNullValues()
            {
                var cache = new CacheStorage<string, object>();

                ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => cache.Add(null, null));
            }
Exemplo n.º 37
0
            public void AddsNonExistingValue()
            {
                var cache = new CacheStorage<string, int>();
                cache.Add("1", 1);

                Assert.AreEqual(1, cache["1"]);
            }
Exemplo n.º 38
0
            public void AddsNonExistingValueForTrueOverride()
            {
                var cache = new CacheStorage<string, int>();
                cache.Add("1", 1);
                cache.Add("1", 2, true);

                Assert.AreEqual(2, cache["1"]);
            }
Exemplo n.º 39
0
            public void ItemStaysInCacheWhenExpiringEventIsCanceled()
            {
                var key = "1";
                var value = 1;

                var cache = new CacheStorage<string, int>();
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);
                cache.Expiring += (sender, e) =>
                {
                    e.Cancel = true;
                };

                cache.Add(key, value, expiration: new TimeSpan(0, 0, 0, 0, 250));

                ThreadHelper.Sleep(750);

                Assert.IsTrue(cache.Contains(key));
            }
Exemplo n.º 40
0
        public static void LoadM2(string filename, CacheStorage cache)
        {
            filename = filename.ToLower().Replace(".mdx", ".m2");

            if (cache.doodadBatches.ContainsKey(filename))
            {
                return;
            }

            WoWFormatLib.Structs.M2.M2Model model = new WoWFormatLib.Structs.M2.M2Model();

            if (cache.models.ContainsKey(filename))
            {
                model = cache.models[filename];
            }
            else
            {
                //Load model from file
                if (WoWFormatLib.Utils.CASC.FileExists(filename))
                {
                    var modelreader = new M2Reader();
                    modelreader.LoadM2(filename);
                    cache.models.Add(filename, modelreader.model);
                    model = modelreader.model;
                }
                else
                {
                    throw new Exception("Model " + filename + " does not exist!");
                }
            }

            var ddBatch = new TerrainWindow.DoodadBatch();

            // Textures
            ddBatch.mats = new TerrainWindow.Material[model.textures.Count()];

            for (int i = 0; i < model.textures.Count(); i++)
            {
                string texturefilename = model.textures[i].filename;
                ddBatch.mats[i].flags = model.textures[i].flags;

                switch (model.textures[i].type)
                {
                    case 0:
                        // Console.WriteLine("      Texture given in file!");
                        texturefilename = model.textures[i].filename;
                        break;
                    case 1:
                        string[] csfilenames = WoWFormatLib.DBC.DBCHelper.getTexturesByModelFilename(filename, (int)model.textures[i].type, i);
                        if (csfilenames.Count() > 0)
                        {
                            texturefilename = csfilenames[0];
                        }
                        else
                        {
                            //Console.WriteLine("      No type 1 texture found, falling back to placeholder texture");
                        }
                        break;
                    case 2:
                        if (WoWFormatLib.Utils.CASC.FileExists(System.IO.Path.ChangeExtension(filename, ".blp")))
                        {
                            // Console.WriteLine("      BLP exists!");
                            texturefilename = System.IO.Path.ChangeExtension(filename, ".blp");
                        }
                        else
                        {
                            //Console.WriteLine("      Type 2 does not exist!");
                            //needs lookup?
                        }
                        break;
                    case 11:
                        string[] cdifilenames = WoWFormatLib.DBC.DBCHelper.getTexturesByModelFilename(filename, (int)model.textures[i].type);
                        for (int ti = 0; ti < cdifilenames.Count(); ti++)
                        {
                            if (WoWFormatLib.Utils.CASC.FileExists(filename.Replace(model.name + ".M2", cdifilenames[ti] + ".blp")))
                            {
                                texturefilename = filename.Replace(model.name + ".M2", cdifilenames[ti] + ".blp");
                            }
                        }
                        break;
                    default:
                        //Console.WriteLine("      Falling back to placeholder texture");
                        texturefilename = "Dungeons\\Textures\\testing\\COLOR_13.blp";
                        break;
                }
                ddBatch.mats[i].textureID = BLPLoader.LoadTexture(texturefilename, cache);
                ddBatch.mats[i].filename = texturefilename;
            }

            // Submeshes
            ddBatch.submeshes = new TerrainWindow.Submesh[model.skins[0].submeshes.Count()];
            for (int i = 0; i < model.skins[0].submeshes.Count(); i++)
            {
                if (filename.StartsWith("character"))
                {
                    if (model.skins[0].submeshes[i].submeshID != 0)
                    {
                        if (!model.skins[0].submeshes[i].submeshID.ToString().EndsWith("01"))
                        {
                            continue;
                        }
                    }
                }

                ddBatch.submeshes[i].firstFace = model.skins[0].submeshes[i].startTriangle;
                ddBatch.submeshes[i].numFaces = model.skins[0].submeshes[i].nTriangles;
                for (int tu = 0; tu < model.skins[0].textureunit.Count(); tu++)
                {
                    if (model.skins[0].textureunit[tu].submeshIndex == i)
                    {
                        ddBatch.submeshes[i].blendType = model.renderflags[model.skins[0].textureunit[tu].renderFlags].blendingMode;
                        if (!cache.materials.ContainsKey(model.textures[model.texlookup[model.skins[0].textureunit[tu].texture].textureID].filename.ToLower()))
                        {
                            throw new Exception("MaterialCache does not have texture " + model.textures[model.texlookup[model.skins[0].textureunit[tu].texture].textureID].filename.ToLower());
                        }

                        ddBatch.submeshes[i].material = (uint)cache.materials[model.textures[model.texlookup[model.skins[0].textureunit[tu].texture].textureID].filename.ToLower()];
                    }
                }
            }

            // Vertices & indices
            ddBatch.vertexBuffer = GL.GenBuffer();
            ddBatch.indiceBuffer = GL.GenBuffer();

            GL.BindBuffer(BufferTarget.ArrayBuffer, ddBatch.vertexBuffer);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, ddBatch.indiceBuffer);

            List<uint> modelindicelist = new List<uint>();
            for (int i = 0; i < model.skins[0].triangles.Count(); i++)
            {
                modelindicelist.Add(model.skins[0].triangles[i].pt1);
                modelindicelist.Add(model.skins[0].triangles[i].pt2);
                modelindicelist.Add(model.skins[0].triangles[i].pt3);
            }

            uint[] modelindices = modelindicelist.ToArray();

            //Console.WriteLine(modelindicelist.Count() + " indices!");
            ddBatch.indices = modelindices;

            GL.BindBuffer(BufferTarget.ElementArrayBuffer, ddBatch.indiceBuffer);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(ddBatch.indices.Length * sizeof(uint)), ddBatch.indices, BufferUsageHint.StaticDraw);

            TerrainWindow.M2Vertex[] modelvertices = new TerrainWindow.M2Vertex[model.vertices.Count()];

            for (int i = 0; i < model.vertices.Count(); i++)
            {
                modelvertices[i].Position = new Vector3(model.vertices[i].position.X, model.vertices[i].position.Y, model.vertices[i].position.Z);
                modelvertices[i].Normal = new Vector3(model.vertices[i].normal.X, model.vertices[i].normal.Y, model.vertices[i].normal.Z);
                modelvertices[i].TexCoord = new Vector2(model.vertices[i].textureCoordX, model.vertices[i].textureCoordY);
            }
            GL.BindBuffer(BufferTarget.ArrayBuffer, ddBatch.vertexBuffer);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(modelvertices.Length * 8 * sizeof(float)), modelvertices, BufferUsageHint.StaticDraw);

            cache.doodadBatches.Add(filename, ddBatch);
        }
Exemplo n.º 41
0
            public void AddsAndExpiresSeveralItems()
            {
                var cache = new CacheStorage<string, int>();

                for (int i = 0; i < 5; i++)
                {
                    var value = cache.GetFromCacheOrFetch("key", () => i, expiration: new TimeSpan(0, 0, 1));

                    Assert.AreEqual(i, value);

                    ThreadHelper.Sleep(2000);
                }
            }
Exemplo n.º 42
0
            public void ThrowsArgumentNullExceptionForNullFunction()
            {
                var cache = new CacheStorage<string, int>();

                ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => cache.GetFromCacheOrFetch("1", null));
            }
Exemplo n.º 43
0
 public void RemovesNonExistingValue()
 {
     var cache = new CacheStorage<string, int>();
     cache.Remove("1");
 }
Exemplo n.º 44
0
            public void DisposesExpiredItemWhenDisposingNotEnabledButForcedByEventArgs()
            {
                var disposable = new CustomDisposable();
                var cache = new CacheStorage<string, CustomDisposable>();
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);
                cache.Expired += (sender, e) =>
                {
                    e.Dispose = true;
                };

                cache.Add("disposable", disposable, expiration: TimeSpan.FromMilliseconds(250));

                ThreadHelper.Sleep(750);

                Assert.IsTrue(disposable.IsDiposed);
            }
Exemplo n.º 45
0
            public void DoesNotDisposeItemsOnClearWhenDisposingNotEnabled()
            {
                var disposable = new CustomDisposable();
                var cache = new CacheStorage<string, CustomDisposable>();
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                cache.Add("disposable", disposable, expiration: TimeSpan.FromMilliseconds(250));

                Assert.IsFalse(disposable.IsDiposed);

                cache.Clear();

                Assert.IsFalse(disposable.IsDiposed);
            }
Exemplo n.º 46
0
            public void DoesNotRaiseExpiredEventOnClearStorage()
            {
                var counter = 0;
                var cache = new CacheStorage<string, int>();
                cache.Add("1", 1);
                cache.Expired += (sender, e) => counter++;

                Assert.AreEqual(0, counter);
            }
Exemplo n.º 47
0
            public void DoesNotDisposeExpiredItemWhenDisposingEnabledButCanceledByEventArgs()
            {
                var disposable = new CustomDisposable();
                var cache = new CacheStorage<string, CustomDisposable>();
                cache.DisposeValuesOnRemoval = true;
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);
                cache.Expired += (sender, e) =>
                {
                    e.Dispose = false;
                };

                cache.Add("disposable", disposable, expiration: TimeSpan.FromMilliseconds(250));

                ThreadHelper.Sleep(750);

                Assert.IsFalse(disposable.IsDiposed);
            }
Exemplo n.º 48
0
            public void DisposesItemOnRemoveWhenDisposingEnabled()
            {
                var disposable = new CustomDisposable();
                var cache = new CacheStorage<string, CustomDisposable>();
                cache.DisposeValuesOnRemoval = true;
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                cache.Add("disposable", disposable, expiration: TimeSpan.FromMilliseconds(250));

                Assert.IsFalse(disposable.IsDiposed);

                cache.Remove("disposable");

                Assert.IsTrue(disposable.IsDiposed);
            }
Exemplo n.º 49
0
            public void RaisesExpiredEventWithCorrectEventArgsWhenItemExpires()
            {
                var dispose = true;
                var key = "1";
                var value = 1;
                var evDispose = false;
                var evKey = (string)null;
                var evValue = 0;

                var cache = new CacheStorage<string, int>();
                cache.DisposeValuesOnRemoval = dispose;
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);
                cache.Expired += (sender, e) =>
                {
                    evDispose = e.Dispose;
                    evKey = e.Key;
                    evValue = e.Value;
                };

                cache.Add(key, value, expiration: new TimeSpan(0, 0, 0, 0, 250));

                ThreadHelper.Sleep(750);

                Assert.AreEqual(dispose, evDispose);
                Assert.AreEqual(key, evKey);
                Assert.AreEqual(value, evValue);
            }
Exemplo n.º 50
0
            public void AddsItemToCacheWithOverrideAndReturnsIt()
            {
                var cache = new CacheStorage<string, int>();

                cache.Add("1", 1);
                var value = cache.GetFromCacheOrFetch("1", () => 2, true);

                Assert.IsTrue(cache.Contains("1"));
                Assert.AreEqual(2, cache["1"]);
                Assert.AreEqual(2, value);
            }
Exemplo n.º 51
0
            public void ReturnsCachedItem()
            {
                var cache = new CacheStorage<string, int>();

                cache.Add("1", 1);
                var value = cache.GetFromCacheOrFetch("1", () => 2);

                Assert.IsTrue(cache.Contains("1"));
                Assert.AreEqual(1, cache["1"]);
                Assert.AreEqual(1, value);
            }
Exemplo n.º 52
0
            public void RemovesExistingValue()
            {
                var cache = new CacheStorage<string, int>();
                cache.Add("1", 1);

                Assert.IsTrue(cache.Contains("1"));

                cache.Remove("1");

                Assert.IsFalse(cache.Contains("1"));
            }
Exemplo n.º 53
0
            public void ReturnsTrueForExistingKey()
            {
                var cache = new CacheStorage<string, int>();
                cache.Add("1", 1);
                cache.Add("2", 2);

                Assert.IsTrue(cache.Contains("2"));
            }
Exemplo n.º 54
0
            public void AddsAndExpiresSeveralItems()
            {
                var cache = new CacheStorage<string, int>();
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                for (int i = 0; i < 5; i++)
                {
                    ThreadHelper.Sleep(1000);

                    int innerI = i;
                    var value = cache.GetFromCacheOrFetch("key", () => innerI, expiration: TimeSpan.FromMilliseconds(250));

                    Assert.AreEqual(i, value);
                }
            }
Exemplo n.º 55
0
            public void AutomaticallyRemovesExpiredItemsOfACacheStorageWithDefaultExpirationPolicyInitializationCode()
            {
                var cache = new CacheStorage<string, int>(() => ExpirationPolicy.Duration(TimeSpan.FromMilliseconds(250)));
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                cache.Add("1", 1);

                Assert.IsTrue(cache.Contains("1"));

                ThreadHelper.Sleep(750);

                Assert.IsFalse(cache.Contains("1"));
            }
Exemplo n.º 56
0
            public void DoesNotAddExistingValueForFalseOverride()
            {
                var cache = new CacheStorage<string, int>();
                cache.Add("1", 1);
                cache.Add("1", 2, false);

                Assert.AreEqual(1, cache["1"]);
            }
Exemplo n.º 57
0
            public void ThrowsArgumentNullExceptionForNullKey()
            {
                var cache = new CacheStorage<string, int>();

                ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => cache.Remove(null));
            }
Exemplo n.º 58
0
            public void RaisesExpiringEventWithCorrectEventArgsWhenItemExpires()
            {
                var key = "1";
                var expirationPolicy = new SlidingExpirationPolicy(TimeSpan.FromMilliseconds(250));
                var value = 1;
                var evKey = (string)null;
                var evExpirationPolicy = default(ExpirationPolicy);
                var evValue = 0;

                var cache = new CacheStorage<string, int>();
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);
                cache.Expiring += (sender, e) =>
                {
                    evKey = e.Key;
                    evExpirationPolicy = e.ExpirationPolicy;
                    evValue = e.Value;
                };

                cache.Add(key, value, expirationPolicy);

                ThreadHelper.Sleep(750);

                Assert.AreEqual(key, evKey);
                Assert.AreEqual(expirationPolicy, evExpirationPolicy);
                Assert.AreEqual(value, evValue);
            }
Exemplo n.º 59
0
            public void IsAutomaticallyEnabledWhenStartedDisabledButAddingItemWithCustomExpirationPolicy()
            {
                var cache = new CacheStorage<string, int>();
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                cache.Add("1", 1, expiration: new TimeSpan(0, 0, 0, 0, 250));

                Assert.IsTrue(cache.Contains("1"));

                ThreadHelper.Sleep(750);

                Assert.IsFalse(cache.Contains("1"));
            }
Exemplo n.º 60
0
            public void AutomaticallyRemovesExpiredItems()
            {
                var cache = new CacheStorage<string, int>();
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                cache.Add("1", 1, expiration: new TimeSpan(0, 0, 0, 0, 250));

                Assert.IsTrue(cache.Contains("1"));

                ThreadHelper.Sleep(750);

                Assert.IsFalse(cache.Contains("1"));
            }