Example #1
0
        public static void DownloadSelfAvatar(GetAvatarResult resultHandler, ErrorHandler errorHandler, bool ignoreCache = false, [CallerMemberName] string caller = null)
        {
            try
            {
                String address = ChatConnection.Instance.WebHost;
                int    port    = ChatConnection.Instance.WebPort;
                String url     = String.Format(GetSelfAvatarURL, address, port);

                if (avatarCache.Contains("Self") && !ignoreCache)
                {
                    resultHandler(avatarCache.Get("Self"));
                }
                else
                {
                    new Task(() =>
                    {
                        using (WebClient client = new WebClient())
                        {
                            Console.WriteLine(caller + " downloading self avatar");
                            client.Headers.Add(ClientSession.HeaderToken, ChatConnection.Instance.Session.SessionID);
                            byte[] data = client.DownloadData(url);

                            BitmapImage bitmap = new BitmapImage();
                            bitmap.BeginInit();
                            bitmap.StreamSource = new MemoryStream(data);
                            bitmap.EndInit();

                            if (resultHandler != null)
                            {
                                bitmap.Freeze();
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    avatarCache.AddReplace("Self", bitmap);
                                    resultHandler(bitmap);
                                });
                            }
                        }
                    }).Start();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                if (errorHandler != null)
                {
                    errorHandler(e);
                }
            }
        }
Example #2
0
        public async Task <Size> GetImageSizeCached(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(new Size(0, 0));
            }
            using (var key = await KeyedSemaphore.LockAsync(path + "size"))
            {
                Size size;
                if (imagesSizeCache.TryGet(path, out size))
                {
                    return(size);
                }
                else
                {
                    var image = await GetImageCached(path);

                    if (image == null)
                    {
                        return(Size.Empty);
                    }
                    size = await ImageProcessing.GetImageSize(image);

                    imagesSizeCache.AddReplace(path, size);
                    return(size);
                }
            }
        }
Example #3
0
        public async Task <byte[]?> GetImageCached(string path, bool forced = false)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(null);
            }
            using (var key = await KeyedSemaphore.LockAsync(path))
            {
                byte[]? image;
                if (imagesCache.TryGet(path, out image) && !forced)
                {
                    return(image);
                }
                else
                {
                    image = await ArchivesProvider.GetImage(path);

                    if (image == null)
                    {
                        return(null);
                    }
                    imagesCache.AddReplace(path, image);
                    return(image);
                }
            }
        }
Example #4
0
        /// <summary>
        /// Start the server to receive datagrams.  Before calling this method, set the 'DatagramReceived' event.
        /// </summary>
        public void StartServer()
        {
            State state = new State(_MaxDatagramSize);

            _Socket.BeginReceiveFrom(state.Buffer, 0, _MaxDatagramSize, SocketFlags.None, ref _Endpoint, _ReceiveCallback = (ar) =>
            {
                State so = (State)ar.AsyncState;
                _Socket.BeginReceiveFrom(so.Buffer, 0, _MaxDatagramSize, SocketFlags.None, ref _Endpoint, _ReceiveCallback, so);
                int bytes = _Socket.EndReceiveFrom(ar, ref _Endpoint);

                string ipPort = _Endpoint.ToString();
                string ip     = null;
                int port      = 0;
                Common.ParseIpPort(ipPort, out ip, out port);

                if (!_RemoteSockets.Contains(ipPort))
                {
                    _RemoteSockets.AddReplace(ipPort, _Socket);
                    EndpointDetected?.Invoke(this, new EndpointMetadata(ip, port));
                }

                if (bytes == so.Buffer.Length)
                {
                    DatagramReceived?.Invoke(this, new Datagram(ip, port, so.Buffer));
                }
                else
                {
                    byte[] buffer = new byte[bytes];
                    Buffer.BlockCopy(so.Buffer, 0, buffer, 0, bytes);
                    DatagramReceived?.Invoke(this, new Datagram(ip, port, buffer));
                }
            }, state);
        }
Example #5
0
        public void ShowImage(String imageURL)
        {
            try
            {
                LoadingAhihi.Visibility = Visibility.Visible;
                VideoFull.Close();

                VideoFull.Visibility = Visibility.Hidden;
                ImgFull.Visibility   = Visibility.Hidden;

                if (ImgCache.Contains(imageURL))
                {
                    ImgFull.Source = ImgCache.Get(imageURL);

                    ImgFull.MaxHeight = ImgFull.Source.Height;
                    ImgFull.MaxWidth  = ImgFull.Source.Width;

                    ImgFull.Visibility      = Visibility.Visible;
                    LoadingAhihi.Visibility = Visibility.Hidden;
                }
                else
                {
                    if (imgThread != null && imgThread.IsAlive)
                    {
                        imgThread.Abort();
                    }
                    imgThread = new Thread(() =>
                    {
                        try
                        {
                            WebClient wc       = new WebClient();
                            BitmapFrame bitmap = BitmapFrame.Create(new MemoryStream(wc.DownloadData(imageURL)));
                            wc.Dispose();
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                ImgCache.AddReplace(imageURL, bitmap);
                                ImgFull.Source = bitmap;

                                ImgFull.MaxHeight  = bitmap.PixelHeight;
                                ImgFull.MaxWidth   = bitmap.PixelWidth;
                                ImgFull.Visibility = Visibility.Visible;

                                LoadingAhihi.Visibility = Visibility.Hidden;
                            });
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    });
                    imgThread.IsBackground = true;
                    imgThread.Start();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public static AbstractConversation GetConversation(Guid id)
        {
            CachedConversation.TryGet(id, out var result);

            if (result == null)
            {
                result = new ConversationStore().Load(id);
                CachedConversation.AddReplace(id, result);
            }

            return(result);
        }
Example #7
0
    static ulong fibonacci(ulong x)
    {
        ulong resp;

        try{
            resp = cache.Get(x);
        } catch {
            if (x == 0)
            {
                return(START_0);
            }
            else if (x == 1)
            {
                return(START_1);
            }
            resp = fibonacci(x - 2) + fibonacci(x - 1);
            cache.AddReplace(x, resp);
        }
        return(resp);
    }
Example #8
0
        public async Task <byte[]?> GetThumbnailCached(string id, int page = 0, bool forced = false, bool ignoreCache = false)
        {
            if (string.IsNullOrEmpty(id))
            {
                return(null);
            }
            var thumbKey = $"{id}.{page}";

            if (ignoreCache)
            {
                return(await GetThumbnailRaw(id, page));
            }
            using (var key = await KeyedSemaphore.LockAsync(thumbKey))
            {
                byte[]? data;
                if (thumbnailsCache.TryGet(thumbKey, out data) && !forced)
                {
                    return(data);
                }
                else
                {
                    var path = $"{thumbnailCacheDirectory.FullName}/{id.Substring(0, 2)}/{id}/{page}.cache";
                    if (File.Exists(path) && !forced)
                    {
                        data = await Files.GetFileBytes(path);

                        if (data.Length == 55876)
                        {
                            using (var md5 = System.Security.Cryptography.MD5.Create())
                                if (NoThumbHash.Equals(string.Concat(md5.ComputeHash(data).Select(x => x.ToString("X2")))))
                                {
                                    File.Delete(path);
                                    data = await GetThumbnailRaw(id, page);

                                    if (data == null)
                                    {
                                        return(null);
                                    }
                                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                                    await Files.StoreFile(path, data);
                                }
                        }
                    }
                    else
                    {
                        data = await GetThumbnailRaw(id, page);

                        if (data == null)
                        {
                            return(null);
                        }
                        if (data.Length == 55876)
                        {
                            using (var md5 = System.Security.Cryptography.MD5.Create())
                                if (NoThumbHash.Equals(string.Concat(md5.ComputeHash(data).Select(x => x.ToString("X2")))))
                                {
                                    return(null);
                                }
                        }
                        Directory.CreateDirectory(Path.GetDirectoryName(path));
                        await Files.StoreFile(path, data);
                    }
                    thumbnailsCache.AddReplace(thumbKey, data);
                    return(data);
                }
            }
        }
        static void LRUCacheTest()
        {
            try
            {
                bool   runForever = true;
                int    capacity   = 2048;
                int    evictCount = 512;
                int    loadCount  = 256;
                bool   cacheDebug = true;
                int    dataLen    = 4096;
                byte[] data       = InitByteArray(dataLen, 0x00);
                byte[] keyData;

                LRUCache <string, byte[]> cache = new LRUCache <string, byte[]>(capacity, evictCount, cacheDebug);
                Thread.Sleep(250);

                while (runForever)
                {
                    Console.WriteLine("-------------------------------------------------------------------------------");
                    Console.WriteLine("Available commands (LRU Cache Test):");
                    Console.WriteLine("  get              Get entry by key");
                    Console.WriteLine("  load             Load " + loadCount + " new records");
                    Console.WriteLine("  last_used        Get the last used entry");
                    Console.WriteLine("  first_used       Get the first used entry");
                    Console.WriteLine("  oldest           Get the oldest entry");
                    Console.WriteLine("  newest           Get the newest entry");
                    Console.WriteLine("  count            Get the count of cached entries");
                    Console.WriteLine("  clear            Clear the cache");
                    Console.WriteLine("  quit             Exit the application");
                    Console.WriteLine("  debug            Flip the cache debug flag (currently " + cache.Debug + ")");

                    Console.WriteLine("");
                    Console.Write("Command > ");
                    string userInput = Console.ReadLine();
                    if (String.IsNullOrEmpty(userInput))
                    {
                        continue;
                    }

                    switch (userInput.ToLower())
                    {
                    case "get":
                        Console.Write("Key > ");
                        string getKey = Console.ReadLine();
                        if (String.IsNullOrEmpty(getKey))
                        {
                            break;
                        }
                        if (cache.TryGet(getKey, out keyData))
                        {
                            Console.WriteLine("Cache hit");
                        }
                        else
                        {
                            Console.WriteLine("Cache miss");
                        }
                        break;

                    case "load":
                        DateTime startTime = DateTime.Now;

                        for (int i = 0; i < loadCount; i++)
                        {
                            string loadKey = Guid.NewGuid().ToString();
                            Console.Write("Adding entry " + i + " of " + loadCount + "                      \r");
                            cache.AddReplace(loadKey, data);
                        }

                        Console.WriteLine(
                            "Loaded " + loadCount +
                            " records in " + TotalTimeFrom(startTime) + ": " +
                            DecimalToString(TotalMsFrom(startTime) / loadCount) + "ms per entry");
                        break;

                    case "last_used":
                        Console.WriteLine("Last used key: " + cache.LastUsed());
                        break;

                    case "first_used":
                        Console.WriteLine("First used key: " + cache.FirstUsed());
                        break;

                    case "oldest":
                        Console.WriteLine("Oldest key: " + cache.Oldest());
                        break;

                    case "newest":
                        Console.WriteLine("Newest key: " + cache.Newest());
                        break;

                    case "count":
                        Console.WriteLine("Cache count: " + cache.Count());
                        break;

                    case "clear":
                        cache.Clear();
                        Console.WriteLine("Cache cleared");
                        break;

                    case "q":
                    case "quit":
                        runForever = false;
                        break;

                    case "debug":
                        cache.Debug = !cache.Debug;
                        break;

                    default:
                        continue;
                    }
                }

                Console.WriteLine("Goodbye!");
                return;
            }
            catch (Exception e)
            {
                PrintException(e);
            }
            finally
            {
                Console.WriteLine("");
                Console.Write("Press ENTER to exit.");
                Console.ReadLine();
            }
        }
Example #10
0
        static void LRUCacheTest()
        {
            try
            {
                bool   runForever = true;
                byte[] data       = InitByteArray(_DataLength, 0x00);
                byte[] keyData;

                LRUCache <string, byte[]> cache = new LRUCache <string, byte[]>(_Capacity, _EvictCount);
                Thread.Sleep(250);

                while (runForever)
                {
                    Console.Write("Command [LRU] > ");
                    string userInput = Console.ReadLine();
                    if (String.IsNullOrEmpty(userInput))
                    {
                        continue;
                    }

                    switch (userInput.ToLower())
                    {
                    case "?":
                        MenuLRU();
                        break;

                    case "get":
                        Console.Write("Key > ");
                        string getKey = Console.ReadLine();
                        if (String.IsNullOrEmpty(getKey))
                        {
                            break;
                        }
                        if (cache.TryGet(getKey, out keyData))
                        {
                            Console.WriteLine("Cache hit");
                        }
                        else
                        {
                            Console.WriteLine("Cache miss");
                        }
                        break;

                    case "all":
                        Dictionary <string, byte[]> dump = cache.All();
                        if (dump != null && dump.Count > 0)
                        {
                            foreach (KeyValuePair <string, byte[]> entry in dump)
                            {
                                Console.WriteLine(entry.Key);
                            }
                            Console.WriteLine("Count: " + dump.Count + " entries");
                        }
                        else
                        {
                            Console.WriteLine("Empty");
                        }
                        break;

                    case "load":
                        DateTime startTime = DateTime.Now;

                        for (int i = 0; i < _LoadCount; i++)
                        {
                            string loadKey = Guid.NewGuid().ToString();
                            Console.Write("Adding entry " + i + " of " + _LoadCount + "                      \r");
                            cache.AddReplace(loadKey, data);
                        }

                        Console.WriteLine(
                            "Loaded " + _LoadCount +
                            " records in " + TotalTimeFrom(startTime) + ": " +
                            DecimalToString(TotalMsFrom(startTime) / _LoadCount) + "ms per entry");
                        break;

                    case "last_used":
                        Console.WriteLine("Last used key: " + cache.LastUsed());
                        break;

                    case "first_used":
                        Console.WriteLine("First used key: " + cache.FirstUsed());
                        break;

                    case "oldest":
                        Console.WriteLine("Oldest key: " + cache.Oldest());
                        break;

                    case "newest":
                        Console.WriteLine("Newest key: " + cache.Newest());
                        break;

                    case "count":
                        Console.WriteLine("Cache count: " + cache.Count());
                        break;

                    case "clear":
                        cache.Clear();
                        Console.WriteLine("Cache cleared");
                        break;

                    case "q":
                    case "quit":
                        runForever = false;
                        break;

                    default:
                        continue;
                    }
                }

                Console.WriteLine("Goodbye!");
                return;
            }
            catch (Exception e)
            {
                PrintException(e);
            }
            finally
            {
                Console.WriteLine("");
                Console.Write("Press ENTER to exit.");
                Console.ReadLine();
            }
        }