public static void DownloadFile(LeafNodeProgress progress, String url, String path)
 {
     var tempFileInfo = new FileInfo(Path.Combine(FolderUtils.SystemTempFolder.FullName, Guid.NewGuid().ToString("N")));
     var targetFileInfo = new FileInfo(path);
     using (var client = new WebClient())
     {
         client.DownloadProgressChanged += (i, o) =>
         {
             progress.Percent = o.ProgressPercentage;
         };
         try
         {
             client.DownloadFileTaskAsync(url, tempFileInfo.FullName).Wait();
         }
         catch (AggregateException ex)
         {
             throw ex.GetBaseException();
         }
         if (targetFileInfo.Directory != null && !targetFileInfo.Directory.Exists)
         {
             targetFileInfo.Directory.Create();
         }
         File.Copy(tempFileInfo.FullName, targetFileInfo.FullName, true);
     }
 }
        public FileRepository(string configPath)
        {
            TerminologyLogger.GetLogger().Info("Initializing file repo...");
            this.Config = new Config(new FileInfo(configPath));
            this.RepoUrl = this.Config.GetConfigString("fileRepositoryUrl");
            this.OfficialProviRdeFilesRepo = new Dictionary<string, RepositoryItemEntity>();
            TerminologyLogger.GetLogger().Info("Initialized file repo!");
            this.CacheRootDirectoryInfo = new DirectoryInfo(Config.GetConfigString("repoCacheFolder"));
            if (!this.CacheRootDirectoryInfo.Exists)
            {
                this.CacheRootDirectoryInfo.Create();
            }
            TerminologyLogger.GetLogger().Info("Finished create repo repository folder.");
            //Different repo url will not share same cache folder.
            this.CacheDirectoryInfo = new DirectoryInfo(Path.Combine(this.CacheRootDirectoryInfo.FullName, EncodeUtils.CalculateStringMd5(this.Config.GetConfigString("fileRepositoryUrl"))));
            if (!this.CacheDirectoryInfo.Exists)
            {
                this.CacheDirectoryInfo.Create();
                TerminologyLogger.GetLogger().InfoFormat($"Created cache directory {this.CacheDirectoryInfo.Name}");
            }
            else
            {
                TerminologyLogger.GetLogger().InfoFormat($"Using cache directory {this.CacheDirectoryInfo.Name}");
            }

            TerminologyLogger.GetLogger().Info($"Start to fetch repo from url {RepoUrl}");
            try
            {
                var progress = new LeafNodeProgress("Fetch repo");
                DownloadUtils.DownloadFile(progress, this.RepoUrl, this.Config.GetConfigString("repoFilePath"));
                var repo =
                    JsonConverter.Parse<FileRepositoryEntity>(File.ReadAllText(this.Config.GetConfigString("repoFilePath")));
                foreach (var officialProvideFile in repo.Files)
                {
                    this.OfficialProviRdeFilesRepo.Add(officialProvideFile.ProvideId, officialProvideFile);
                }

            }
            catch (WebException)
            {
                TerminologyLogger.GetLogger().Error("Unable to receive repo right now. Trying to using local repo list.");
                if (!File.Exists(this.Config.GetConfigString("repoFilePath")))
                {
                    TerminologyLogger.GetLogger().Error("No local repo list available.");
                    return;
                }
                var repo =
                   JsonConverter.Parse<FileRepositoryEntity>(File.ReadAllText(this.Config.GetConfigString("repoFilePath")));
                foreach (var officialProvideFile in repo.Files)
                {
                    this.OfficialProviRdeFilesRepo.Add(officialProvideFile.ProvideId, officialProvideFile);
                }
                TerminologyLogger.GetLogger().Info("Used local repo list.");
            }
            catch (Exception)
            {
                throw;
            }
        }
 public LeafNodeProgress CreateNewLeafSubProgress(string taskName, double taskPercentage)
 {
     taskPercentage = this.CheckPercentage(taskPercentage);
     var progress = new LeafNodeProgress(taskName);
     this.SubProgressesAndPercentage.Add(progress, taskPercentage);
     progress.ProgressChanged += sender => { this.OnProgressChanged(); };
     return progress;
 }
 public void BottomLevelA(LeafNodeProgress progress)
 {
     Thread.Sleep(2000);
     progress.Percent = 20;
     Thread.Sleep(2000);
     progress.Percent = 40;
     Thread.Sleep(2000);
     progress.Percent = 60;
     Thread.Sleep(2000);
     progress.Percent = 80;
     Thread.Sleep(2000);
     progress.Percent = 100;
 }
        public void ProgressWindowTest()
        {
            var progress = new LeafNodeProgress("Common");
            var progressWindow = new GUI.ProgressWindow(progress);

            var t=new Task(() =>
            {
                progressWindow.ShowDialog();
            });
            t.Start();
            while (progress.Percent<100D)
            {
                Thread.Sleep(3000);
                progress.Percent += 1.5D;
            }
            t.Wait();
        }
        public static void DownloadFile(LeafNodeProgress progress, string url, string path)
        {
            var task = new Task(() =>
            {
                var tempFileInfo = new FileInfo(Path.Combine(FolderUtils.SystemTempFolder.FullName, Guid.NewGuid().ToString("N")));
                var targetFileInfo = new FileInfo(path);
                using (var client = new TerminologyWebClient())
                {
                    client.DownloadProgressChanged += (i, o) =>
                    {
                        progress.Percent = o.ProgressPercentage;
                    };
                    try
                    {
                        client.DownloadFileTaskAsync(url, tempFileInfo.FullName).Wait();
                    }
                    catch (AggregateException ex)
                    {
                        throw ex.GetBaseException();
                    }
                    catch (ArgumentException ex)
                    {
                        throw new ArgumentException(ex.Message + $"Url:{url}", ex);
                    }

                    if (targetFileInfo.Directory != null && !targetFileInfo.Directory.Exists)
                    {
                        targetFileInfo.Directory.Create();
                    }
                    File.Copy(tempFileInfo.FullName, targetFileInfo.FullName, true);
                }
            });
            task.Start();
            try
            {
                task.Wait();
            }
            catch (AggregateException ae)
            {

                throw ae.InnerException;
            }
        }
        public static void MainTest()
        {
            var progress = new LeafNodeProgress("Common");
            ProgressWindow progressWindow = new ProgressWindow(progress);

            var t = Task.Run(() =>
            {
                do
                {
                    Thread.Sleep(1000);
                    progress.Percent += 5.5D;
                    Console.WriteLine("Progress update to {0}!", progress.Percent);
                } while (true);
            });

            progressWindow.ShowDialog();

            //var t = Task.Run(() =>
            //{
            //    progressWindow = new ProgressWindow(progress);
            //    progressWindow.Show();
            //    Console.WriteLine("Show progress!");
            //});
        }
        private void ReceiveOfficialFile(LeafNodeProgress progress, String instanceName, OfficialFileEntity officialFile, FileRepository usingRepo)
        {
            //Try to find file at file repo
            var repositoryFile = usingRepo.GetOfficialFile(officialFile.ProvideId);

            var downloadLink = repositoryFile.DownloadPath;
            var downloadTargetPositon = Path.Combine(this.GetInstanceRootFolder(instanceName).FullName, officialFile.LocalPath);
            Logger.GetLogger().Info(String.Format("Downloading file:{0} from remote url:{1}.", downloadTargetPositon, downloadLink));
            DownloadUtils.DownloadFile(progress, downloadLink, downloadTargetPositon, officialFile.Md5);
            Logger.GetLogger().Info(String.Format("Successfully downloaded file:{0} from remote url:{1}.", downloadTargetPositon, downloadLink));
        }
 private void ReceiveCustomFile(LeafNodeProgress progress, String instanceName, CustomFileEntity customFile)
 {
     var downloadLink = customFile.DownloadLink;
     var downloadTargetPositon = Path.Combine(this.GetInstanceRootFolder(instanceName).FullName, customFile.LocalPath);
     Logger.GetLogger().Info(String.Format("Downloading file:{0} from remote url:{1}.", downloadTargetPositon, downloadLink));
     DownloadUtils.DownloadFile(progress, downloadLink, downloadTargetPositon, customFile.Md5);
     Logger.GetLogger().Info(String.Format("Successfully downloaded file:{0} from remote url:{1}.", downloadTargetPositon, downloadLink));
 }
 public static void DownloadFile(LeafNodeProgress progress, String url, String path, String md5)
 {
     DownloadFile(progress, url, path);
     if (!EncodeUtils.CheckFileMd5(path, md5))
     {
         throw new Exception(String.Format("Md5 check for {0} refused!", path));
     }
 }
        public static string GetFileContent(LeafNodeProgress progress, string url)
        {
            using (var client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                client.DownloadProgressChanged += (i, o) =>
                {
                    progress.Percent = o.ProgressPercentage;
                };

                return client.DownloadStringTaskAsync(url).Result;

            }
        }
 public static string GetWebContent(LeafNodeProgress progress, string url)
 {
     var task = new Task<string>(() =>
     {
         using (var client = new TerminologyWebClient())
         {
             client.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
             client.Encoding = EncodeUtils.NoneBomUTF8;
             client.DownloadProgressChanged += (i, o) =>
             {
                 progress.Percent = o.ProgressPercentage;
             };
             try
             {
                 return client.DownloadStringTaskAsync(url).Result;
             }
             catch (ArgumentException ex)
             {
                 throw new ArgumentException(ex.Message + $"Url:{url}", ex);
             }
         }
     });
     task.Start();
     task.Wait();
     return task.Result;
 }
 public static void DownloadFile(LeafNodeProgress progress, string url, string path, string md5)
 {
     DownloadFile(progress, url, path);
     if (!EncodeUtils.CheckFileMd5(path, md5))
     {
         throw new Exception($"Md5 check for {path} refused!");
     }
 }
        private void ReceiveOfficialFile(LeafNodeProgress progress, string instanceName, OfficialFileEntity officialFile, FileRepository usingRepo)
        {
            //Try to find file at file repo
            var repositoryFile = usingRepo.GetOfficialFile(progress, officialFile.ProvideId);

            var targetPositon = Path.Combine(this.GetInstanceRootFolder(instanceName).FullName, officialFile.LocalPath);
            repositoryFile.CopyTo(targetPositon, true);
            TerminologyLogger.GetLogger().Info($"Successfully put file:{targetPositon}.");
        }
        public FileInfo GetOfficialFile(LeafNodeProgress progress, string id)
        {
            if (!this.OfficialProviRdeFilesRepo.ContainsKey(id))
            {
                throw new Exception(
                    $"Cannot find official file with id:{id} at current repo. Try to change repo or contact instance author to correct provide info.");
            }
            var repositoryFile = this.OfficialProviRdeFilesRepo[id];
            var cacheFile = new FileInfo(Path.Combine(this.CacheDirectoryInfo.FullName, repositoryFile.ProvideId));
            if (cacheFile.Exists && (EncodeUtils.CalculateFileMd5(cacheFile.FullName).Equals(repositoryFile.Md5)))
            {
                progress.Percent = 100D;
                TerminologyLogger.GetLogger()
                    .InfoFormat($"File {repositoryFile.Name} exists and md5 check successful. Using cache file.");
            }
            else
            {
                TerminologyLogger.GetLogger()
                    .InfoFormat($"File {repositoryFile.Name} not exists or md5 check fault. Download new file.");

                cacheFile.Delete();
                DownloadUtils.DownloadFile(progress, repositoryFile.DownloadPath, cacheFile.FullName);
                TerminologyLogger.GetLogger()
                    .InfoFormat($"Successful download file {repositoryFile.Name} from url {repositoryFile.DownloadPath}");
            }
            return cacheFile;
        }