private string GetJobSampleData()
        {
            var metric = _usageMetricFactory.CreateMetric <PdfCreatorUsageStatisticsMetric>();

            metric.OperatingSystem      = OsHelper.GetWindowsVersion();
            metric.Duration             = TimeSpan.Zero.Milliseconds;
            metric.OutputFormat         = OutputFormat.Pdf.ToString();
            metric.Mode                 = Mode.Interactive;
            metric.QuickActions         = true;
            metric.OpenViewer           = true;
            metric.OpenWithPdfArchitect = true;
            metric.Status               = "Success";
            metric.Attachment           = true;
            metric.Background           = true;
            metric.Dropbox              = true;
            metric.Cover                = true;
            metric.NumberOfCopies       = 1;
            metric.Script               = true;
            metric.CustomScript         = true;
            metric.TotalPages           = 1;
            metric.Mailclient           = true;
            metric.Print                = true;
            metric.Signature            = true;
            metric.Encryption           = true;
            metric.UserToken            = true;
            metric.Ftp   = true;
            metric.Http  = true;
            metric.Smtp  = true;
            metric.Stamp = true;

            return(ConvertToJson(metric));
        }
Beispiel #2
0
 private void InitForm_Load(object sender, EventArgs e)
 {
     if (!OsHelper.IsAdministrator())
     {
         MessageBox.Show(this, "请以管理员身份运行!", "EasyWss", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Environment.Exit(0);
     }
 }
Beispiel #3
0
        private void FindAssemblyDirectory()
        {
            var libPath = _assemblyHelper.GetAssemblyDirectory() + "\\lib\\";

            _osHelper = new OsHelper();
            libPath  += _osHelper.Is64BitProcess ? "x64" : "x86";
            _osHelper.AddDllDirectorySearchPath(libPath);
        }
Beispiel #4
0
 public long GetDownloadedSize(string hash)
 {
     OsHelper.ExecuteCommand("transmission-remote", $"{TrAuth} -t {hash} -i", out var output, out var _);
     if (string.IsNullOrEmpty(output))
     {
         return(0);
     }
     return(new TransmissionItem(output, null).DownloadedSize);
 }
 /// <summary>
 /// ctor.
 /// </summary>
 public ClientService()
 {
     ServiceName = Constants.ClientServiceDisplayName;
     Directory.SetCurrentDirectory(Application.StartupPath);
     OsHelper.RenameCurrentThread(Constants.ThreadClient);
     XmlConfigurator.Configure(new FileInfo(Path.Combine(Application.StartupPath, "LoggerConfig.xml")));
     logMain    = LogManager.GetLogger(Constants.LogService);
     logSpooler = LogManager.GetLogger(Constants.LogSpooler);
 }
Beispiel #6
0
        public static void LogUserEnvironment(HttpRequestBase request, string userName)
        {
            var    dojoLogger  = LogManager.GetCurrentClassLogger();
            string browserInfo = OsHelper.GetUserBrowser(request);
            string osInfo      = OsHelper.GetUserPlatform(request).ToString();
            string message     = string.Format("User:{0} OS:{1} {2}", (userName != null ? userName : string.Empty), osInfo, browserInfo);

            dojoLogger.Info(message, typeof(OsHelper));
        }
Beispiel #7
0
        public bool AddTorrent(string torrentPath, string downloadDirPath)
        {
            var args = $"{TrAuth} -a " + torrentPath.Quoted() + " -w " + downloadDirPath.Quoted() + " --torrent-done-script " + settings.TorrentDoneScript.Quoted();

            logger.LogInformation("transmission-remote " + args);
            var result = OsHelper.ExecuteCommand("transmission-remote", args, out var output, out var error);

            logger.LogInformation($"output: {output} error: {error}");
            return(result == 0);
        }
Beispiel #8
0
        public PdfToolsTestLicensing() : base(ParameterHelper.GetPassword("pdftoolbox_key"), ParameterHelper.GetPassword("pdfa_converter_key"), ParameterHelper.GetPassword("pdfsecure_key"), ParameterHelper.GetPassword("pdfa_validator_key"))
        {
            var assemblyHelper = new AssemblyHelper(Assembly.GetExecutingAssembly());
            var libPath        = assemblyHelper.GetAssemblyDirectory() + "\\lib\\";

            var osHelper = new OsHelper();

            libPath += osHelper.Is64BitProcess ? "x64" : "x86";
            osHelper.AddDllDirectorySearchPath(libPath);
        }
Beispiel #9
0
 private void button_Register_Click(object sender, EventArgs e)
 {
     if (OsHelper.AddFileContextMenuItem("EasyWss", "发送到文叔叔", Process.GetCurrentProcess().MainModule.FileName))
     {
         MessageBox.Show(this, "注册成功!\r\n使用:右键单击需要上传的文件,点击“发送到文叔叔”即可。", "EasyWss", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     else
     {
         MessageBox.Show(this, "注册失败!", "EasyWss", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        /// <summary>
        /// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running.
        /// </summary>
        protected override void OnStop()
        {
            base.OnStop();

            // остановка чтения очереди принтера
            spoolerWatchdog.Abort();

            // запись в журнал
            OsHelper.RenameCurrentThread(Constants.ThreadClient);
            LogHelper.Write(logMain, MessageType.Stop, "Остановка службы...");
        }
        private string GetServiceSampleData()
        {
            var metric = _usageMetricFactory.CreateMetric <ServiceUsageStatisticsMetric>();

            metric.ServiceUptime   = TimeSpan.TicksPerMillisecond;
            metric.TotalUsers      = 1;
            metric.TotalDocuments  = 1;
            metric.OperatingSystem = OsHelper.GetWindowsVersion();

            return(ConvertToJson(metric));
        }
Beispiel #12
0
 private void button_UnRegister_Click(object sender, EventArgs e)
 {
     if (OsHelper.DelFileContextMenuItem("EasyWss"))
     {
         MessageBox.Show(this, "卸载成功!", "EasyWss", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     else
     {
         MessageBox.Show(this, "卸载失败!", "EasyWss", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Beispiel #13
0
 public bool TryGetDuration(string path, out TimeSpan duration)
 {
     duration = TimeSpan.FromMilliseconds(0);
     if (OsHelper.ExecuteCommand("mediainfo", $"--Inform=\"General;%Duration%\" \"{path}\"", out var outputDuration, out var stderr) != 0)
     {
         return(false);
     }
     if (!double.TryParse(outputDuration, out var value))
     {
         return(false);
     }
     duration = TimeSpan.FromMilliseconds(value);
     return(true);
 }
Beispiel #14
0
        /// <summary>
        /// Get the media location for the file
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public RenameResult Rename(RenameRequest request)
        {
            var result     = new RenameResult();
            var destFormat = request.BaseDestPath + Path.DirectorySeparatorChar + "{plex}";
            var args       = "-rename " + request.Path.Quoted() + " --format " + destFormat.Quoted() + " -non-strict --action " + request.Action.Quoted();

            if (request.Db != null)
            {
                args += " --db " + request.Db.Quoted();
            }

            logger.LogInformation("filebot " + args);
            result.RawExecutedCommand = $"filebot {args}";
            result.ExitCode           = OsHelper.ExecuteCommand("filebot", args, out var stdout, out var stderr);
            result.StandardOutput     = stdout;
            result.StandardError      = stderr;

            logger.LogInformation($"code: {result.ExitCode}, output: {result.StandardOutput}, error: {result.StandardError}");

            if (result.ExitCode != 0)
            {
                var match = FileAlreadyExistsPattern.Match(result.StandardOutput);
                if (match.Success && match.Groups["dest"].Success)
                {
                    result.DestPath = match.Groups["dest"].Value;
                    logger.LogInformation($"Filebot.TryRename [SUCCESS] [FileAlreadyExists] [{result.DestPath}]");
                    result.Reason    = "File already exists at dest location";
                    result.Succeeded = true;
                    return(result);
                }
            }

            var p = new Regex(@"\[" + request.Action.ToUpper() + @"\].*\[.*\] to \[(?<dest>.*)\]").Match(result.StandardOutput);

            if (p.Success && p.Groups["dest"].Success)
            {
                result.DestPath  = p.Groups["dest"].Value;
                result.Succeeded = true;
                result.Reason    = "Found";
                logger.LogWarning($"Filebot.TryRename [SUCCESS] [{result.DestPath}]");
                return(result);
            }

            result.Succeeded = false;
            result.Reason    = "Failed to capture destPath in stdout";
            logger.LogWarning("Filebot.TryRename [FAILED] to capture destPath in output: ", result.StandardOutput);
            return(result);
        }
Beispiel #15
0
        public void AddTestPage()
        {
            var osHelper = new OsHelper();

            var rm = new ResourceManager(typeof(Resources));
            var sb = new StringBuilder(rm.GetString("TestPage"));

            // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion -> ProductName

            sb.Replace("[INFOTITLE]", "PDFCreator " + UpdateAssistant.CurrentVersion);
            sb.Replace("[INFODATE]", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString());
            sb.Replace("[INFOAUTHORS]", "pdfforge");
            sb.Replace("[INFOHOMEPAGE]", Urls.PdfforgeWebsiteUrl);
            sb.Replace("[INFOPDFCREATOR]", "PDFCreator " + UpdateAssistant.CurrentVersion);

            sb.Replace("[INFOCOMPUTER]", Environment.MachineName);
            sb.Replace("[INFOWINDOWS]", osHelper.GetWindowsVersion());
            sb.Replace("[INFO64BIT]", osHelper.Is64BitOperatingSystem.ToString());

            string tempPath = Path.Combine(SpoolFolder, Guid.NewGuid().ToString());

            Directory.CreateDirectory(tempPath);
            File.WriteAllText(Path.Combine(tempPath, "testpage.ps"), sb.ToString());

            sb = new StringBuilder();

            sb.AppendLine("[0]");
            sb.AppendLine("SessionId=" + Process.GetCurrentProcess().SessionId);
            sb.AppendLine("WinStation=Console");
            sb.AppendLine("UserName="******"ClientComputer=" + Environment.MachineName);
            sb.AppendLine("SpoolFileName=testpage.ps");
            sb.AppendLine("PrinterName=PDFCreator");
            sb.AppendLine("JobId=1");
            sb.AppendLine("TotalPages=1");
            sb.AppendLine("Copies=1");
            sb.AppendLine("DocumentTitle=PDFCreator Testpage");
            sb.AppendLine("");

            string infFile = Path.Combine(tempPath, "testpage.inf");

            File.WriteAllText(infFile, sb.ToString(), Encoding.Unicode);

            var jobInfo = new JobInfo(infFile, SettingsHelper.Settings.ApplicationSettings.TitleReplacement);

            Add(jobInfo);
        }
Beispiel #16
0
        // опрос очереди печати по таймеру
        private void spoolerDelegate()
        {
            try
            {
                OsHelper.RenameCurrentThread(Constants.ThreadSpooler);
                while (true)
                {
                    // запрос новых записей
                    var printJobs = PrintInfo.Request();
                    foreach (var pringJob in printJobs)
                    {
                        // поиск старой записи
                        var old = oldPrintJobs.Find(job => job.Id == pringJob.Id);

                        // если такой нету - заносим в список
                        if (old == null)
                        {
                            oldPrintJobs.Add(pringJob);
                        }
                        // если есть - объединяем со старой
                        else
                        {
                            old.TimeStamp     = DateTime.Now;
                            old.Size          = Math.Max(old.Size, pringJob.Size);
                            old.NumberOfPages = Math.Max(old.NumberOfPages, pringJob.NumberOfPages);
                        }
                    }

                    // сохранение старых
                    var toSave = oldPrintJobs.Where(job =>
                                                    !job.Stored &&
                                                    (DateTime.Now - job.TimeStamp).TotalSeconds > Config.SpoolerDelay);
                    foreach (var info in toSave)
                    {
                        var xml = XmlHelper.SerializeElement(info);
                        logSpooler.Info(xml.OuterXml);
                        info.Stored = true;
                    }

                    // усыпление потока
                    Thread.Sleep(Config.Instance.SpoolerTimer);
                }
            }
            catch (ThreadAbortException)
            { }
        }
Beispiel #17
0
        /// <summary>
        ///     Call the SetupHelper.exe to add, rename or delete printers
        /// </summary>
        /// <param name="arguments">Command line arguments that will be passed to SetupHelper.exe</param>
        /// <returns>true, if the action was successful</returns>
        private bool CallPrinterHelper(string arguments)
        {
            var assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            if (assemblyPath == null)
            {
                return(false);
            }

            var printerHelperPath = Path.Combine(assemblyPath, "SetupHelper.exe");

            if (!File.Exists(printerHelperPath))
            {
                var message = TranslationHelper.Instance.TranslatorInstance.GetFormattedTranslation("Application",
                                                                                                    "SetupFileMissing",
                                                                                                    "An important clawPDF file is missing ('{0}'). Please reinstall clawPDF!",
                                                                                                    Path.GetFileName(printerHelperPath));
                var caption =
                    TranslationHelper.Instance.TranslatorInstance.GetTranslation("ApplicationSettingsWindow", "Error",
                                                                                 "Error");
                MessageWindow.ShowTopMost(message, caption, MessageWindowButtons.OK, MessageWindowIcon.Error);
                return(false);
            }

            if (Environment.OSVersion.Version.Major <= 5)
            {
                var osHelper = new OsHelper();
                if (!osHelper.UserIsAdministrator())
                {
                    var message = TranslationHelper.Instance.TranslatorInstance.GetFormattedTranslation(
                        "ApplicationSettingsWindow", "OperationRequiresAdminPrivileges",
                        "This operation requires admin privileges and it looks like you are not an admin. Do you want to continue anyway?\r\nNote: It is safe to continue even if you are unsure if you have appropriate rights, but the operation will not be completed.",
                        Path.GetFileName(printerHelperPath));
                    var caption = TranslationHelper.Instance.TranslatorInstance.GetTranslation(
                        "ApplicationSettingsWindow", "AdminPrivilegesRequired", "Admin privileges required");
                    if (MessageWindow.ShowTopMost(message, caption, MessageWindowButtons.YesNo,
                                                  MessageWindowIcon.Info) ==
                        MessageWindowResponse.No)
                    {
                        return(false);
                    }
                }
            }

            return(CallProgramAsAdmin(printerHelperPath, arguments));
        }
        /// <summary>
        /// Основной код службы.
        /// </summary>
        protected override void AgentMain()
        {
            try
            {
                // инициализация
                OsHelper.RenameCurrentThread(Constants.ThreadClient);
                LogHelper.Write(logMain, MessageType.Start, "Запуск службы...");
                Config.LoadOrCreate();
                LogHelper.Write(logMain, MessageType.Information, "Прочитаны настройки...");

                // ожидание запросов информации
                serviceHost = new ServiceHost(
                    typeof(SalePointService),
                    new Uri(string.Format(CultureInfo.InvariantCulture, Protocol.ServiceAddressFormat, "0.0.0.0", Protocol.ConnectionPort, Protocol.ServiceName)));
                serviceHost.Open();
                if (ConsoleRunInvoked)
                {
                    LogHelper.Write(logMain, MessageType.Debug, "Запущено ожидание запросов от сервера...");
                }

                // запуск проверки очереди печати
                spoolerWatchdog = new Thread(spoolerDelegate);
                spoolerWatchdog.Start();
                if (ConsoleRunInvoked)
                {
                    LogHelper.Write(logMain, MessageType.Debug, "Запущен поток слежения за принтером...");
                }

                // отслеживание смены времени
                SystemEvents.TimeChanged += timeChanged;
                if (ConsoleRunInvoked)
                {
                    LogHelper.Write(logMain, MessageType.Debug, "Включено слежение за изменением времени...");
                }
            }
            catch (Exception ex)
            {
                if (ConsoleRunInvoked)
                {
                    LogHelper.Write(logMain, MessageType.Fatal, "Произошла ошибка!", ex);
                    Thread.Sleep(50);
                }
                throw;
            }
        }
Beispiel #19
0
        public string BuildDownloadCompletedMailBody(DownloadItem item)
        {
            var downloadedIn = item.DownloadedAt.Subtract(item.StartedAt);
            var avgSpeed     = new ByteSize(item.TotalSize).Per(downloadedIn);
            var processedIn  = item.CompletedAt.Subtract(item.DownloadedAt);
            var html         = OsHelper.GetRessourceContent("download-completed-email.tmpl.html");

            html = html
                   .Replace("{downloadedIn}", downloadedIn.Humanize())
                   .Replace("{avgSpeed}", avgSpeed.Humanize("#"))
                   .Replace("{processedIn}", processedIn.Humanize())
                   .Replace("{movedFiles}", string.Join("",
                                                        item.MovedFiles.Where(pmi => pmi.Size.HasValue).OrderBy(x => x.Path).Select(pmi =>
                                                                                                                                    "<tr>" +
                                                                                                                                    "   <td>" + pmi.Path.Split('/').Last() + "</td>" +
                                                                                                                                    "   <td>" + new ByteSize((double)pmi.Size).Humanize("#") + "</td>" +
                                                                                                                                    "</tr>")
                                                        ));
            return(html);
        }
Beispiel #20
0
        public bool GetSubtitles(string path, out string srtPath, string lang = "eng", bool nonStrict = false)
        {
            // todo: wrap in requst/result object
            srtPath = "";
            var args = "-get-subtitles " + path.Quoted() + " --lang " + lang.Quoted();

            if (nonStrict)
            {
                args += " -non-strict ";
            }

            var expectedSrtPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path)) +
                                  $".{lang}.srt";

            logger.LogInformation("filebot " + args);
            Console.WriteLine("filebot " + args);

            var code = OsHelper.ExecuteCommand("filebot", args, out var output, out var error);
            var msg  = $"code: {code}, output: {output}, error: {error}";

            Console.WriteLine(msg);
            logger.LogInformation(msg);
            if (!File.Exists(expectedSrtPath))
            {
                Console.WriteLine(expectedSrtPath + " does not exists");
                return(false);
            }

            /* -get-subtitles option always returns 0 regardless of failure */
            logger.LogInformation("Renaming to 2 letter iso code");
            var twoLetterSrtPath = FilesystemHelper.ConvertToTwoLetterIsoLanguageNameSubtitle(expectedSrtPath);

            if (twoLetterSrtPath != null)
            {
                FilesystemHelper.MoveOrReplace(expectedSrtPath, twoLetterSrtPath);
                srtPath = twoLetterSrtPath;
            }

            return(true);
        }
        /// <summary>
        ///     Call the SetupHelper.exe to add or remove explorer context menu integration
        /// </summary>
        /// <param name="arguments">Command line arguments that will be passed to SetupHelper.exe</param>
        /// <returns>true, if the action was successful</returns>
        private void CallSetupHelper(string arguments)
        {
            var assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            if (assemblyPath == null)
            {
                return;
            }

            var setupHelperPath = Path.Combine(assemblyPath, "SetupHelper.exe");

            if (!File.Exists(setupHelperPath))
            {
                var message = _translator.GetFormattedTranslation("Application", "SetupFileMissing",
                                                                  Path.GetFileName(setupHelperPath));
                var caption = _translator.GetTranslation("ApplicationSettingsWindow", "Error");
                ShowMessage(message, caption, MessageOptions.OK, MessageIcon.Error);
                return;
            }

            if (Environment.OSVersion.Version.Major <= 5)
            {
                var osHelper = new OsHelper();
                if (!osHelper.UserIsAdministrator())
                {
                    var message = _translator.GetTranslation("ApplicationSettingsWindow", "OperationRequiresAdminPrivileges");
                    var caption = _translator.GetTranslation("ApplicationSettingsWindow", "AdminPrivilegesRequired");

                    var response = ShowMessage(message, caption, MessageOptions.YesNo, MessageIcon.Info);
                    if (response == MessageResponse.No)
                    {
                        return;
                    }
                }
            }

            CallProgramAsAdmin(setupHelperPath, arguments);
        }
Beispiel #22
0
        public void AddTestPage()
        {
            var osHelper  = new OsHelper();
            var verHelper = new VersionHelper();

            var rm = new ResourceManager(typeof(Resources));
            var sb = new StringBuilder(rm.GetString("TestPage"));
            // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion -> ProductName

            var tempPath = Path.Combine(SpoolFolder, Guid.NewGuid().ToString());

            Directory.CreateDirectory(tempPath);
            File.WriteAllText(Path.Combine(tempPath, "testpage.ps"), sb.ToString());

            sb = new StringBuilder();

            sb.AppendLine("[0]");
            sb.AppendLine("SessionId=" + Process.GetCurrentProcess().SessionId);
            sb.AppendLine("WinStation=Console");
            sb.AppendLine("Username="******"ClientComputer=" + Environment.MachineName);
            sb.AppendLine("SpoolFileName=testpage.ps");
            sb.AppendLine("PrinterName=clawPDF");
            sb.AppendLine("JobId=1");
            sb.AppendLine("TotalPages=1");
            sb.AppendLine("Copies=1");
            sb.AppendLine("DocumentTitle=CUPS Testpage");
            sb.AppendLine("");

            var infFile = Path.Combine(tempPath, "testpage.inf");

            File.WriteAllText(infFile, sb.ToString(), Encoding.Unicode);

            var jobInfo = new JobInfo(infFile, SettingsHelper.Settings.ApplicationSettings.TitleReplacement);

            Add(jobInfo);
        }
Beispiel #23
0
        private string GetApplicationPath(string applicationName)
        {
            var assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            if (assemblyPath == null)
            {
                return(null);
            }

            var applicationPath = Path.Combine(assemblyPath, applicationName);

            if (!File.Exists(applicationPath))
            {
                var message = _translation.GetFormattedSetupFileMissing(Path.GetFileName(applicationPath));
                var caption = _translation.Error;
                ShowMessage(message, caption, MessageOptions.OK, MessageIcon.Error);
                return(null);
            }

            if (Environment.OSVersion.Version.Major <= 5)
            {
                var osHelper = new OsHelper();
                if (!osHelper.UserIsAdministrator())
                {
                    var message = _translation.OperationRequiresAdminPrivileges;
                    var caption = _translation.AdminPrivilegesRequired;

                    var response = ShowMessage(message, caption, MessageOptions.YesNo, MessageIcon.Info);
                    if (response == MessageResponse.No)
                    {
                        return(null);
                    }
                }
            }

            return(applicationPath);
        }
Beispiel #24
0
        public ShellRunner([NotNull] ShellRunnerSettings settings, [CanBeNull] ILog log)
        {
            log = log ?? LogProvider.Get();

            this.settings = settings;
            this.log      = log;

            startInfo = new ProcessStartInfo
            {
                FileName               = settings.Command,
                CreateNoWindow         = true,
                RedirectStandardError  = true,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                StandardOutputEncoding = Encoding.Default,
                StandardErrorEncoding  = Encoding.Default,
                WindowStyle            = ProcessWindowStyle.Hidden,
                UseShellExecute        = false,
                Arguments              = settings.Arguments ?? string.Empty,
                WorkingDirectory       = settings.WorkingDirectory
            };

            processKillJob = OsHelper.TryCreateWindowsProcessKillJob();
        }
Beispiel #25
0
 public int DownloadTorrentFile(string magnetLink, string downloadFolder, TimeSpan?timeout = null)
 {
     return(OsHelper.ExecuteCommand("aria2c",
                                    "--bt-metadata-only=true --bt-save-metadata=true -q " + magnetLink.Quoted() + " -d " +
                                    downloadFolder.Quoted(), out _, out _, timeout));
 }
Beispiel #26
0
 public bool RemoveTorrent(string hash)
 {
     return(OsHelper.ExecuteCommand("transmission-remote", $"{TrAuth} -t {hash} -r", out _, out _) == 0);
 }
Beispiel #27
0
        public static void Execute()
        {
            String    filepath  = "sorted.dat";
            Stopwatch stopWatch = new Stopwatch();
            TimeSpan  ts;

            int[]  nums      = new int[100000];
            int[]  dummyList = new int[nums.Length];
            Random rand      = new Random();

            for (int i = 0; i < nums.Length; i++)
            {
                nums[i] = rand.Next(1000000);
            }
            Console.WriteLine("----Random: ");
            Console.WriteLine("Selection: ");
            stopWatch.Start();
            SelectionSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);
            int[] sorted = new int[dummyList.Length];
            sorted = ShellSort(dummyList);
            String[] lines = new String[sorted.Length];
            for (int i = 0; i < sorted.Length; i++)
            {
                lines[i] = sorted[i].ToString();
            }
            Console.WriteLine(OsHelper.CompatiblePath(filepath, true));
            if (!File.Exists(OsHelper.CompatiblePath(filepath, true)))
            {
                File.Create(OsHelper.CompatiblePath(filepath, true));
            }
            System.IO.File.WriteAllLines(OsHelper.CompatiblePath(filepath, true), lines);
            Console.WriteLine("Insertion: ");
            stopWatch.Restart();
            dummyList = nums;
            InsertionSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Bubble: ");
            stopWatch.Restart();
            dummyList = nums;
            BubbleSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Ripple: ");
            stopWatch.Restart();
            dummyList = nums;
            RippleSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Shell: ");
            stopWatch.Restart();
            dummyList = nums;
            ShellSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);
            //sorted
            Console.WriteLine("----Sorted: ");
            dummyList = ShellSort(dummyList);
            Console.WriteLine("Selection: ");
            stopWatch.Start();
            SelectionSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Insertion: ");
            stopWatch.Restart();
            dummyList = nums;
            InsertionSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Bubble: ");
            stopWatch.Restart();
            dummyList = nums;
            BubbleSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Ripple: ");
            stopWatch.Restart();
            dummyList = nums;
            RippleSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Shell: ");
            stopWatch.Restart();
            dummyList = nums;
            ShellSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);
            //sorted backwards
            Array.Reverse(dummyList);
            Console.WriteLine("----Reverse: ");
            Console.WriteLine("Selection: ");
            stopWatch.Start();
            SelectionSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Insertion: ");
            stopWatch.Restart();
            dummyList = nums;
            InsertionSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Bubble: ");
            stopWatch.Restart();
            dummyList = nums;
            BubbleSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Ripple: ");
            stopWatch.Restart();
            dummyList = nums;
            RippleSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);

            Console.WriteLine("Shell: ");
            stopWatch.Restart();
            dummyList = nums;
            ShellSort(dummyList);
            stopWatch.Stop();
            ts = stopWatch.Elapsed;
            Console.WriteLine("Time: " + ts.Seconds + ":" + ts.Milliseconds);
        }