public void LaunchInstance()
        {
            if (InstanceManager.Config != null)
                InstanceManager.Config.SetConfigString("javaBinPath", "C:\\jdk1.7.0_51\\bin\\");

            var progress = new InternalNodeProgress("");
            progress.ProgressChanged += (i) =>
            {
                Console.WriteLine(progress.Percent);
            };
            InstanceManager.LaunchInstance(progress.CreateNewInternalSubProgress("", 100D), InstanceManager.Instances[0].InstanceName, new PlayerEntity() { PlayerName = "DeckerCHAN" });
        }
        public string FetchLatestVersionAndStartUpdate(InternalNodeProgress progress)
        {
            progress.Percent = 0D;

            if (!this.GetupdateInfo().UpdateType.Equals(UpdateType.Higher))
            {
                return TranslationManager.GetManager.Localize("NoUpdateAvailable", "No update available.");
            }

            var update = JsonConverter.Parse<UpdateEntity>(DownloadUtils.GetWebContent(this.Config.GetConfigString("updateCheckingUrl")));

            var updateTempFolder = Path.Combine(FolderUtils.SystemTempFolder.FullName,
                $"TerminologyLauncher-{update.LatestVersion.CoreVersion}-{update.LatestVersion.BuildNumber}");
            var updateBinaryFolder = Path.Combine(updateTempFolder, "Binary");
            var updaterExecutorFile = Path.Combine(
                Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Updater.exe");
            var updaterRealExecutorFile = Path.Combine(updateTempFolder, "Updater.exe");

            if (Directory.Exists(updateTempFolder))
            {
                FolderUtils.DeleteDirectory(updateTempFolder);
            }

            progress.Percent = 10D;
            DownloadUtils.DownloadZippedFile(
                progress.CreateNewInternalSubProgress("Fetching update pack", 80D), update.LatestVersion.DownloadLink,
                updateBinaryFolder,
                update.LatestVersion.Md5);
            if (!File.Exists(updaterExecutorFile))
            {
                throw new FileNotFoundException("Cannot find updater.exe. You may have to re-install to resolve!");
            }
            File.Copy("Updater.exe", updaterRealExecutorFile, true);
            var updateProcessInfo = new ProcessStartInfo(updaterRealExecutorFile)
            {
                Arguments =
                    $"{updateBinaryFolder} {Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)} {Assembly.GetEntryAssembly().Location}",
                CreateNoWindow = false,
                UseShellExecute = true
            };
            var updateProcess = new Process { StartInfo = updateProcessInfo };
            updateProcess.Start();

            progress.Percent = 100D;
            return string.Format(TranslationManager.GetManager.Localize("FetchedNewUpdateToVersion", "Updating from {0} to {1}! Close launcher to continue.", 2),
                $"{this.Version.CoreVersion}-{this.Version.BuildNumber}",
                $"{this.Version.CoreVersion}-{this.Version.BuildNumber}");
        }
        public String FetchLatestVersionAndStartUpdate(InternalNodeProgress progress)
        {
            progress.Percent = 0D;

            if (!this.CheckUpdateAvailable())
            {
                return "No newer update available.";
            }

            var update = JsonConverter.Parse<UpdateEntity>(DownloadUtils.GetFileContent(this.Config.GetConfig("updateCheckingUrl")));

            var updateTempFolder = Path.Combine(FolderUtils.SystemTempFolder.FullName,
                String.Format("TerminologyLauncher-{0}", update.LatestVersion.VersionNumber));
            var updateBinaryFolder = Path.Combine(updateTempFolder, "Binary");
            var updaterExecutorFile = Path.Combine(
                Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Updater.exe");
            var updaterRealExecutorFile = Path.Combine(updateTempFolder, "Updater.exe");

            if (Directory.Exists(updateTempFolder))
            {
                FolderUtils.DeleteDirectory(updateTempFolder);
            }

            progress.Percent = 10D;
            DownloadUtils.DownloadZippedFile(
                progress.CreateNewInternalSubProgress(80D, "Fetching update pack"), update.LatestVersion.DownloadLink,
                updateBinaryFolder,
                update.LatestVersion.Md5);
            if (!File.Exists(updaterExecutorFile))
            {
                throw new FileNotFoundException("Can not find updater.exe. You may have to re-install to resolve!");
            }
            File.Copy("Updater.exe", updaterRealExecutorFile, true);
            var updateProcessInfo = new ProcessStartInfo(updaterRealExecutorFile)
            {
                Arguments =
                    String.Format("{0} {1} {2}", updateBinaryFolder,
                        Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), Assembly.GetEntryAssembly().Location),
                CreateNoWindow = false,
                UseShellExecute = true
            };
            var updateProcess = new Process { StartInfo = updateProcessInfo };
            updateProcess.Start();

            progress.Percent = 100D;
            return String.Format("Updating from {0} to {1}! Close launcher to continue.", this.Version,
            update.LatestVersion.VersionNumber);
        }
        public static void LaunchInstance()
        {
            if (InstanceManager.Config != null)
                InstanceManager.Config.SetConfig("javaBinPath", "C:\\jdk1.7.0_51\\bin\\");
            var fileRepo = new FileRepository("Configs/FileRepositoryConfig.json");

            var progress = new InternalNodeProgress("");
            var t = Task.Run(() =>
            {
                while (progress.Percent <= 100D)
                {
                    Console.WriteLine(progress.Percent);
                    Thread.Sleep(1000);
                }

            });
            var process = InstanceManager.LaunchInstance(progress.CreateNewInternalSubProgress(100D, ""), InstanceManager.Instances[0].InstanceName, new PlayerEntity() { PlayerName = "DeckerCHAN" });
            process.WaitForExit();
        }
        public Process LaunchInstance(InternalNodeProgress progress, String instanceName, PlayerEntity player)
        {
            Logger.GetLogger().Info(String.Format("Start to launch {0} by player {1}...", instanceName, player.PlayerName));
            var instanceInfo = this.InstanceBank.InstancesInfoList.First(x => (x.Name.Equals(instanceName)));
            var instance =
                JsonConverter.Parse<InstanceEntity>(
                    File.ReadAllText(instanceInfo.FilePath));

            if (!(instanceInfo.InstanceState == InstanceState.Ok || instanceInfo.InstanceState == InstanceState.PerInitialized))
            {
                throw new WrongStateException("Wrong instance state! Just instance which in OK or PerInitialized state could launch.");
            }

            this.CriticalInstanceFieldCheck(instance);

            var instanceRootFolder = this.GetInstanceRootFolder(instance.InstanceName);

            #region Buding environment

            if (instanceInfo.InstanceState == InstanceState.PerInitialized)
            {
                #region entire file.
                if (instance.FileSystem.EntirePackageFiles != null && instance.FileSystem.EntirePackageFiles.Count != 0)
                {
                    var singlePackageDownloadNodeProgress = 30D / instance.FileSystem.EntirePackageFiles.Count;
                    foreach (var entirePackageFile in instance.FileSystem.EntirePackageFiles)
                    {
                        this.ReceiveEntirePackage(progress.CreateNewInternalSubProgress(singlePackageDownloadNodeProgress, String.Format("Receiving entire package {0}", entirePackageFile.Name)),
                        instance.InstanceName, entirePackageFile);
                    }
                }
                #endregion
                progress.Percent = 30D;
                #region official files.
                if (instance.FileSystem.OfficialFiles != null && instance.FileSystem.OfficialFiles.Count != 0)
                {
                    var singleOfficialDownloadNodeProgress = 30D / instance.FileSystem.OfficialFiles.Count;
                    foreach (var officialFileEntity in instance.FileSystem.OfficialFiles)
                    {
                        this.ReceiveOfficialFile(
                            progress.CreateNewLeafSubProgress(singleOfficialDownloadNodeProgress,
                                String.Format("Downloading official file: {0}", officialFileEntity.Name)),
                            instance.InstanceName, officialFileEntity, this.UsingFileRepository);
                    }
                }
                #endregion
                progress.Percent = 60D;
                #region custom files

                if (instance.FileSystem.CustomFiles != null && instance.FileSystem.CustomFiles.Count != 0)
                {
                    var singleCustomDownloadNodeProgress = 30D / instance.FileSystem.CustomFiles.Count;
                    foreach (var customFileEntity in instance.FileSystem.CustomFiles)
                    {
                        this.ReceiveCustomFile(
                           progress.CreateNewLeafSubProgress(singleCustomDownloadNodeProgress,
                               String.Format("Downloading custom file: {0}", customFileEntity.Name)),
                           instance.InstanceName, customFileEntity);
                    }
                }
                #endregion
            }

            #endregion
            progress.Percent = 90D;

            instanceInfo.InstanceState = InstanceState.Ok;
            instanceInfo.UpdateDate = DateTime.Now.ToString("O");
            this.SaveInstancesBankToFile();

            //DONE:Build start argument.
            var startArgument = new StringBuilder();// placer.ReplaceArgument(instance.StartupArguments);
            foreach (var jvmArgument in instance.StartupArguments.JvmArguments)
            {
                startArgument.Append(jvmArgument + " ");
            }

            startArgument.Append(this.Config.GetConfig("extraJvmArguments") ?? String.Empty).Append(" ");

            startArgument.AppendFormat("-Xmx{0}M -Xms{1}M" + " ", Convert.ToInt64(this.Config.GetConfig("maxMemorySizeMega")), instance.StartupArguments.MiniumMemoryMegaSize);

            var nativeFolder = new DirectoryInfo(Path.Combine(instanceRootFolder.FullName, instance.StartupArguments.Nativespath));
            if (nativeFolder.Exists)
            {
                startArgument.AppendFormat("-Djava.library.path=\"{0}\"" + " ", nativeFolder.FullName);

            }
            else
            {
                throw new DirectoryNotFoundException(String.Format("Native folder is not valid!"));
            }

            startArgument.Append("-cp" + " ");

            foreach (var libraryPath in instance.StartupArguments.LibraryPaths)
            {
                var libFile = new FileInfo(Path.Combine(instanceRootFolder.FullName, libraryPath));
                if (libFile.Exists)
                {
                    startArgument.Append("\"" + libFile.FullName + "\"" + ";");
                }
                else
                {
                    throw new FileNotFoundException(String.Format("Instance {0} is missing lib file {1}", instance.InstanceName, libraryPath));
                }
            }

            var mainJarFile =
                new FileInfo(Path.Combine(instanceRootFolder.FullName, instance.StartupArguments.MainJarPath));

            if (mainJarFile.Exists)
            {
                startArgument.Append("\"" + mainJarFile.FullName + "\"" + " ");
            }
            else
            {
                throw new FileNotFoundException(String.Format("Instance {0} is missing main jar file {1}", instance.InstanceName, mainJarFile.Name));
            }

            startArgument.Append(instance.StartupArguments.MainClass + " ");

            startArgument.AppendFormat("--username {0} ", player.PlayerName);
            startArgument.AppendFormat("--version {0} ", instance.StartupArguments.Version);
            startArgument.AppendFormat("--gameDir \"{0}\" ", instanceRootFolder.FullName);

            var assetsDir =
                new DirectoryInfo(Path.Combine(instanceRootFolder.FullName, instance.StartupArguments.AssetsDir));
            if (assetsDir.Exists)
            {
                startArgument.AppendFormat("--assetsDir \"{0}\" ", assetsDir.FullName);
            }
            else
            {
                throw new DirectoryNotFoundException("Assets folder not found!");
            }

            startArgument.AppendFormat("--assetIndex {0} ", instance.StartupArguments.AssetIndex);
            startArgument.AppendFormat("--uuid {0} ", player.PlayerId);
            startArgument.AppendFormat("--accessToken {0} ", player.AccessToken);
            startArgument.AppendFormat("--userProperties {{{0}}} ", instance.StartupArguments.UserProperties);
            startArgument.AppendFormat("--userType {0} ", instance.StartupArguments.UserType);

            foreach (var tweakClass in instance.StartupArguments.TweakClasses)
            {
                startArgument.AppendFormat("--tweakClass {0} ", tweakClass);
            }

            //Launch minecraft
            var instanceStartInfo = new ProcessStartInfo
            {
                FileName = this.JavaRuntime.JavaWPath,
                Arguments = startArgument.ToString(),
                WorkingDirectory = instanceRootFolder.FullName,
                WindowStyle = ProcessWindowStyle.Normal,
                UseShellExecute = false,
                RedirectStandardOutput = true
            };
            var instanceProcess = new Process { StartInfo = instanceStartInfo, EnableRaisingEvents = true };
            instanceProcess.Start();
            progress.Percent = 100D;

            this.CurrentInstanceProcess = instanceProcess;
            Logger.GetLogger().Info(String.Format("Instance {0} launched!", instanceName));

            return this.CurrentInstanceProcess;
        }
 public void TopLevel()
 {
     var progress = new InternalNodeProgress("Main task");
     progress.ProgressChanged += sender =>
     {
         Console.WriteLine("Woring on {0}:{1}", progress.TaskName, progress.Percent);
     };
     Console.WriteLine(progress.Percent);
     this.MidLevel(progress.CreateNewInternalSubProgress(100D,"MidLevel"));
     Console.WriteLine("All tasks finished!");
 }