Пример #1
0
        public async void LoadImage()
        {
            string file = ImageFileName;

            if (string.IsNullOrWhiteSpace(file))
            {
                return;
            }
            string imagePath = $"{Global.AppDataPath}{Path.DirectorySeparatorChar}{Global.ImagesCacheDirectory}{Path.DirectorySeparatorChar}{file}";

            if (!Global.CachedImages.ContainsKey(file))
            {
                Global.CachedImages.Add(file, BitmapImageLoadingInfo.CreateDefault());
            }
            BitmapImageLoadingInfo info = Global.CachedImages[file];

            if (info.Loaded)
            {
                this.Image = info.Image;
            }
            if (info.Loading)
            {
                await Task.Run(async() =>
                {
                    // ugly hack to test wheter image is loaded,
                    // assigment of Image.Source before BitmapImage has been loaded causes NullReferenceException in BitmapImage.EndInit()
                    while (info.Loading)
                    {
                        await Task.Delay(100);
                    }
                });

                this.Image = info.Image;
            }
            if (info.Loaded || info.Loading)
            {
                return;
            }
            info.Loading = true;

            if (File.Exists(imagePath))
            {
                byte[]       imageData = File.ReadAllBytes(imagePath);
                MemoryStream stream    = new MemoryStream(imageData);
                info.Image.BeginInit();
                info.Image.CacheOption  = BitmapCacheOption.OnLoad;
                info.Image.StreamSource = stream;
                info.Image.EndInit();

                this.Image  = info.Image;
                info.Loaded = true;
            }
            else
            {
                MemoryStream memory  = new MemoryStream();
                bool         success = await Task.Run <bool>(() =>
                {
                    Stream stream = null;
                    if (IsContextValid && !m_context.OnlyContext)
                    {
                        stream = m_context.GetManufacturerImageStream();
                    }
                    else if (!Custom && !string.IsNullOrWhiteSpace(ManufacturerImageLink))
                    {
                        try
                        {
                            HttpWebRequest request   = Requests.CreateDefaultRequest(ManufacturerImageLink);
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            stream = response.GetResponseStream();
                        }
                        catch
                        {
                            stream = null;
                        }
                    }

                    if (stream != null)
                    {
                        FileStream fileStream = new FileStream(imagePath, FileMode.Create);
                        try
                        {
                            byte[] buffer = new byte[1024];
                            int len;
                            while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                memory.Write(buffer, 0, len);
                                fileStream.Write(buffer, 0, len);
                            }
                        }
                        finally
                        {
                            stream.Close();
                            fileStream.Close();
                        }

                        return(true);
                    }

                    return(false);
                });

                if (success)
                {
                    memory.Seek(0, SeekOrigin.Begin);
                    info.Image.BeginInit();
                    info.Image.CacheOption  = BitmapCacheOption.OnLoad;
                    info.Image.StreamSource = memory;
                    info.Image.EndInit();

                    this.Image  = info.Image;
                    info.Loaded = true;
                }
            }

            info.Loading = false;
        }
Пример #2
0
        private async void DoUpdate(string link)
        {
            string zipFilePath = $"{Global.AppDataPath}{Path.DirectorySeparatorChar}{Global.UpdateFile}";
            string extractPath = $"{Global.AppDataPath}{Path.DirectorySeparatorChar}{Global.UpdateExtractDirectory}";

            try
            {
                HttpWebRequest request = Requests.CreateDefaultRequest(link);
                using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        Text = Global.GetStringResource("StringDownloadingUpdate");
                        using (FileStream file = new FileStream(zipFilePath, FileMode.Create))
                        {
                            int    len;
                            byte[] buffer = new byte[4096];
                            while ((len = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                            {
                                await file.WriteAsync(buffer, 0, len);

                                Progress = (int)((decimal)(file.Position - 1) / (decimal)response.ContentLength * 50M);
                                Text     = $"{Global.GetStringResource("StringDownloadingUpdate")}{Environment.NewLine}{(file.Position - 1) / 1024}/{response.ContentLength / 1024} KB";
                            }
                        }
                    }
                }
            }
            catch
            {
                Global.Dialogs.Close(this);
                return;
            }

            m_downloadSuccessful = true;

            Text = Global.GetStringResource("StringExtractingUpdate");

            try
            {
                if (Directory.Exists(extractPath))
                {
                    Directory.Delete(extractPath, true);
                }

                await Task.Run(() =>
                {
                    long totalSize      = 0;
                    long transferred    = 0;
                    long oldTransferred = 0;
                    ZipEntry oldEntry   = null;
                    using (ZipFile zip = new ZipFile(zipFilePath))
                    {
                        foreach (ZipEntry item in zip.Entries)
                        {
                            totalSize += item.UncompressedSize;
                        }

                        zip.ExtractProgress += (s, e) =>
                        {
                            if (e.CurrentEntry != oldEntry)
                            {
                                oldEntry       = e.CurrentEntry;
                                oldTransferred = 0;
                            }
                            if (e.EventType == ZipProgressEventType.Extracting_EntryBytesWritten)
                            {
                                transferred   += e.BytesTransferred - oldTransferred;
                                oldTransferred = e.BytesTransferred;
                            }

                            InvokeWindow.Invoke(() =>
                            {
                                Text     = $"{Global.GetStringResource("StringExtractingUpdate")}{Environment.NewLine}{transferred / 1024}/{totalSize / 1024} KB";
                                Progress = 50 + (int)((decimal)transferred / (decimal)totalSize * 50M);
                            });
                        };
                        zip.ExtractAll(extractPath, ExtractExistingFileAction.OverwriteSilently);
                    }
                });
            }
            catch
            {
                Global.Dialogs.Close(this);
                return;
            }

            m_extractSuccessful = true;

            Global.Dialogs.Close(this);
        }