Example #1
0
        private static void RunInstaller(DownloadAndInstallProcess process)
        {
            var state = new OperationProgress
            {
                CurrentProgress = 0,
                MaxProgress     = 0,
                IsIndeterminate = true,
                ActionName      = "Installing MSysGit...",
            };

            if (process.Monitor != null)
            {
                process.Monitor.Report(state);
            }
            try
            {
                process.InstallerProcess = new Process()
                {
                    StartInfo = new ProcessStartInfo()
                    {
                        FileName  = process.InstallerFileName,
                        Arguments = @"/verysilent",
                    },
                    EnableRaisingEvents = true,
                };
                process.InstallerProcess.Exited += process.OnInstallerProcessExited;
                process.InstallerProcess.Start();
            }
            catch (Exception exc)
            {
                process.Exception = exc;
                process.Dispose();
            }
        }
        /// <summary>
        /// Handles progress notifications from a the local update metadata source
        /// Prints progress information to the console
        /// </summary>
        /// <param name="sender">The metadata source that is executing a long running operation</param>
        /// <param name="e">Progress information</param>
        private static void LocalSource_ExportOperationProgress(object sender, OperationProgress e)
        {
            switch (e.CurrentOperation)
            {
            case OperationType.ExportUpdateXmlBlobStart:
                Console.Write("Exporting update XML data: 000.00%");
                break;

            case OperationType.ExportUpdateXmlBlobProgress:
                Console.CursorLeft = 0;
                Console.Write("Exporting {0} update(s) and categories XML data: {1:000.00}%", e.Maximum, e.PercentDone);
                break;

            case OperationType.ExportMetadataStart:
                Console.Write("Packing metadata...");
                break;

            case OperationType.CompressExportFileStart:
                Console.WriteLine("Compressing output export file...\r\n");
                break;

            case OperationType.ExportMetadataEnd:
            case OperationType.ExportUpdateXmlBlobEnd:
            case OperationType.CompressExportFileEnd:
                ConsoleOutput.WriteGreen("Done!");
                break;
            }
        }
Example #3
0
        public void TestHashOrder()
        {
            string[] hashes = new string[]
            {
                "00000000000000000000000000000002",
                "00000000000000000000000000000004",
                "00000000000000000000000000000006",
                "00000000000000000000000000000008",
                "0000000000000000000000000000000A",
                "00000000000000000000000000000001",
                "00000000000000000000000000000003",
                "00000000000000000000000000000005",
                "00000000000000000000000000000007",
                "00000000000000000000000000000009",
            };

            HashSet <byte[]>  hashBytes = new HashSet <byte[]>(hashes.Select(t => t.HexStringToBytes()), new ByteArrayComparer());
            OperationProgress progress  = new OperationProgress();
            CancellationToken ct;

            this.Store.AddToStore(hashBytes, StoreType.Password, ct, progress);

            Assert.AreEqual(0, progress.HashesDiscarded);
            Assert.AreEqual(hashes.Length, progress.HashesAdded);

            CollectionAssert.AreEqual(hashes.OrderBy(t => t).ToList(), this.Store.GetHashes(this.GetPrefixFromHash("00000"), StoreType.Password).Select(t => t.ToHexString()).ToList());
        }
Example #4
0
        public void TestAddHashesToStore()
        {
            string[] hashes = new string[]
            {
                "00000000000000000000000000000001",
                "00000000000000000000000000000002",
                "00000000000000000000000000000003",
                "00000000000000000000000000000004",
                "00000000000000000000000000000005",
                "00000000000000000000000000000006",
                "00000000000000000000000000000007",
                "00000000000000000000000000000008",
                "00000000000000000000000000000009",
                "0000000000000000000000000000000A",
            };

            List <byte[]>     hashBytes = hashes.Select(t => t.HexStringToBytes()).ToList();
            CancellationToken ct        = new CancellationToken();

            OperationProgress progress = new OperationProgress();

            this.Store.AddToStore(new HashSet <byte[]>(hashBytes, new ByteArrayComparer()), StoreType.Password, ct, progress);

            Assert.AreEqual(0, progress.HashesDiscarded);
            Assert.AreEqual(hashes.Length, progress.HashesAdded);

            string rawFile = Path.Combine(this.Store.StorePathPasswordStore, this.GetFileNameFromHash(hashes[0]));

            TestHelpers.AssertFileIsExpectedSize(rawFile, this.StoredHashSize * hashes.Length);

            this.Store.AddToStore(new HashSet <byte[]>(hashBytes, new ByteArrayComparer()), StoreType.Password, ct, new OperationProgress());
            TestHelpers.AssertFileIsExpectedSize(rawFile, this.StoredHashSize * hashes.Length);
        }
Example #5
0
        private static void OnGotResponse(IAsyncResult ar)
        {
            var process = (DownloadAndInstallProcess)ar.AsyncState;
            var state   = new OperationProgress
            {
                CurrentProgress = 0,
                MaxProgress     = 0,
                IsIndeterminate = true,
                ActionName      = "Downloading MSysGit...",
            };

            if (process.Monitor != null)
            {
                process.Monitor.Report(state);
            }
            process.WebResponse    = process.WebRequest.EndGetResponse(ar);
            process.ResponseStream = process.WebResponse.GetResponseStream();
            if (process.WebResponse.ContentLength > 0)
            {
                state.IsIndeterminate = false;
                state.MaxProgress     = (int)process.WebResponse.ContentLength;
                if (process.Monitor != null)
                {
                    process.Monitor.Report(state);
                }
            }
            process.Buffer = new byte[1024 * 4];
            process.ResponseStream.BeginRead(
                process.Buffer,
                0,
                process.Buffer.Length,
                OnResponseStreamRead,
                process);
        }
Example #6
0
        private static void LocalSource_OperationProgress(object sender, OperationProgress e)
        {
            switch (e.CurrentOperation)
            {
            case OperationType.DownloadFileStart:
                Console.Write("Downloading {0,60} [000.00%]", (e as ContentOperationProgress).File.FileName);
                break;

            case OperationType.HashFileStart:
                Console.Write("Hashing     {0,60} [000.00%]", (e as ContentOperationProgress).File.FileName);
                break;

            case OperationType.DownloadFileEnd:
                Console.CursorLeft = 0;
                Console.Write("Downloading {0,60} [100.00%] ", (e as ContentOperationProgress).File.FileName);
                ConsoleOutput.WriteGreen("Done!");
                break;

            case OperationType.HashFileEnd:
                Console.CursorLeft = 0;
                Console.Write("Hashing     {0,60} [100.00%] ", (e as ContentOperationProgress).File.FileName);
                ConsoleOutput.WriteGreen("Done!");
                break;

            case OperationType.DownloadFileProgress:
                Console.CursorLeft = 0;
                Console.Write("Downloading {0,60} [{1:000.00}%]", (e as ContentOperationProgress).File.FileName, e.PercentDone);
                break;

            case OperationType.HashFileProgress:
                Console.CursorLeft = 0;
                Console.Write("Hashing     {0,60} [{1:000.00}%]", (e as ContentOperationProgress).File.FileName, e.PercentDone);
                break;
            }
        }
Example #7
0
        private void CopyButton_Click(object sender, EventArgs e)
        {
            try
            {
                progressBar.Minimum = 0;
                progressBar.Maximum = 100;

                var progress = new OperationProgress();
                progressBar.Value = (int)progress.Progress;

                progress.PropertyChanged += (prog, evt) =>
                {
                    if (evt.PropertyName.ToLower().Equals("progress"))
                    {
                        Method funcToRun = RunFunction;
                        progressBar.Invoke(funcToRun, progress);
                    }
                };

                var copyEngine = new CopyDirectoryEngine.DirectoryCopyEngine();

                Task.Run(() =>
                         copyEngine.StartCopy(SourceFolderPath.Text, DestinationFolderPath.Text, progress)).ConfigureAwait(true).GetAwaiter().OnCompleted(
                    () => {
                    MessageBox.Show("Completed Successfully!");
                });
                MessageBox.Show("Task running");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #8
0
            public void SetProgress(OperationProgress p)
            {
                var data = new byte[1 + InedoLib.UTF8Encoding.GetByteCount(p.Message ?? string.Empty)];

                data[0] = (byte)(p.Percent ?? 255);
                InedoLib.UTF8Encoding.GetBytes(p.Message ?? string.Empty, 0, p.Message.Length, data, 1);
                this.Post(data);
            }
Example #9
0
 private static void SetProgress(IProgress <OperationProgress> progress, int val, string action)
 {
     if (progress != null)
     {
         var status = new OperationProgress
         {
             ActionName      = action,
             MaxProgress     = 8,
             CurrentProgress = val,
         };
         progress.Report(status);
     }
 }
Example #10
0
        public override async Task ExecuteAsync(IOperationExecutionContext context)
        {
            this.serverName = context.ServerName;

            var execOps = await context.Agent.GetServiceAsync <IRemoteProcessExecuter>();

            var makeStartInfo = new RemoteProcessStartInfo
            {
                FileName         = "dfhack-make",
                Arguments        = this.Target.EscapeLinuxArg(),
                WorkingDirectory = context.WorkingDirectory
            };

            if (this.UseNinja)
            {
                makeStartInfo.EnvironmentVariables["DFHACK_USE_NINJA"] = "1";
            }

            var cidfile = await this.LogAndWrapCommandAsync(context, makeStartInfo);

            using (var make = execOps.CreateProcess(makeStartInfo))
            {
                this.progress = new OperationProgress(0);

                make.OutputDataReceived += this.OutputDataReceived;
                make.ErrorDataReceived  += this.ErrorDataReceived;

                make.Start();
                using (ManageContainerIDFile(context, cidfile))
                {
                    await make.WaitAsync(context.CancellationToken);
                }

                var processName = this.UseNinja ? "ninja" : "make";

                if (make.ExitCode == 0)
                {
                    this.LogDebug($"{processName} exited with code 0 (success)");
                }
                else if (make.ExitCode.HasValue)
                {
                    this.LogError($"{processName} exited with code {make.ExitCode} (failure)");
                }
                else
                {
                    this.LogError($"{processName} exited with unknown code");
                }
            }
        }
Example #11
0
 private static void UpdateDownloadProgress(DownloadAndInstallProcess process, int downloadedBytes)
 {
     process.DownloadedBytes += downloadedBytes;
     if (process.Monitor != null && process.WebResponse.ContentLength > 0 && process.DownloadedBytes <= process.WebResponse.ContentLength)
     {
         var state = new OperationProgress
         {
             CurrentProgress = (int)process.DownloadedBytes,
             MaxProgress     = (int)process.WebResponse.ContentLength,
             IsIndeterminate = false,
             ActionName      = "Downloading MSysGit...",
         };
         process.Monitor.Report(state);
     }
 }
Example #12
0
        private void NinjaOutputDataReceived(object source, ProcessDataReceivedEventArgs args)
        {
            int?percentage = null;

            var line = this.RemoveLogRubbish(args);

            if (line == null)
            {
                return;
            }

            var slash = line.IndexOf('/');
            var close = line.IndexOf(']');

            if (slash != -1 && slash < close && line[0] == '[')
            {
                var num = AH.ParseInt(line.Substring(1, slash - 1));
                var den = AH.ParseInt(line.Substring(slash + 1, close - slash - 1));

                if (num.HasValue && den.HasValue)
                {
                    percentage    = 100 * num.Value / den.Value;
                    this.progress = new OperationProgress(percentage, $"{this.serverName} {line.Substring(0, close + 1)}");
                }
            }

            if (this.ImageTag == "msvc" && !percentage.HasValue && args.Data != line && new[] { ".c", ".cc", ".cpp" }.Any(ext => line.EndsWith(ext)))
            {
                return;
            }

            if (percentage.HasValue)
            {
                this.LogInformation(line);
            }
            else if (line.Contains(this.ImageTag == "msvc" ? " error C" : ": error: "))
            {
                this.LogError(line);
            }
            else if (line.Contains(this.ImageTag == "msvc" ? " warning C" : ": warning: "))
            {
                this.LogWarning(line);
            }
            else
            {
                this.LogDebug(line);
            }
        }
Example #13
0
        public async override Task ExecuteAsync(IOperationExecutionContext context)
        {
            if (!this.ProxyRequest)
            {
                await this.QueueBuildAsync(progress => this.progress = progress, context.CancellationToken).ConfigureAwait(false);

                return;
            }

            var jobExec = await context.Agent.GetServiceAsync <IRemoteJobExecuter>().ConfigureAwait(false);

            using (var job = new QueueBuildRemoteJob(this))
            {
                job.MessageLogged += (s, e) => this.OnMessageLogged(e);
                await jobExec.ExecuteJobAsync(job, context.CancellationToken).ConfigureAwait(false);
            }
        }
        public static void MetadataSourceOperationProgressHandler(object sender, OperationProgress e)
        {
            if (!OperationsMessages.TryGetValue(e.CurrentOperation, out string operationMessage))
            {
                return;
            }

            switch (e.CurrentOperation)
            {
            case OperationType.IndexingFilesStart:
            case OperationType.IndexingBundlesStart:
            case OperationType.IndexingCategoriesStart:
            case OperationType.HashMetadataStart:
            case OperationType.PrerequisiteGraphUpdateStart:
            case OperationType.ProcessSupersedeDataStart:
            case OperationType.IndexingTitlesStart:
            case OperationType.IndexingPrerequisitesStart:
            case OperationType.IndexingDriversStart:
                Console.CursorLeft = 0;
                Console.Write($"{operationMessage} [000.0%]");
                break;

            case OperationType.IndexingFilesEnd:
            case OperationType.IndexingBundlesEnd:
            case OperationType.IndexingCategoriesEnd:
            case OperationType.PrerequisiteGraphUpdateEnd:
            case OperationType.ProcessSupersedeDataEnd:
            case OperationType.HashMetadataEnd:
            case OperationType.IndexingTitlesEnd:
            case OperationType.IndexingPrerequisitesEnd:
            case OperationType.IndexingDriversEnd:
                Console.CursorLeft = 0;
                Console.Write($"{operationMessage}  [100.00%] ");
                ConsoleOutput.WriteGreen(" Done!");
                break;

            case OperationType.IndexingCategoriesProgress:
            case OperationType.PrerequisiteGraphUpdateProgress:
                Console.CursorLeft = 0;
                Console.Write("{1} [{0:000.00}%]", e.PercentDone, operationMessage);
                break;
            }
        }
Example #15
0
        public static async Task Main(string[] args)
        {
            ConfigureLogger();

            var progress = new OperationProgress();

            using (new ConsoleDisplayUpdater(progress))
            {
                try
                {
                    await Execute(args, progress);

                    Log.Information("Execution finished");
                }
                catch (Exception e)
                {
                    Log.Fatal(e, "Operation failed");
                    throw;
                }
            }
        }
        /// <inheritdoc/>
        public async Task <OperationStatus> GetStatusAsync(Guid operationId, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // TODO: Pass token when supported
            DurableOrchestrationStatus status = await _durableClient.GetStatusAsync(OperationId.ToString(operationId), showInput : true);

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

            _logger.LogInformation(
                "Successfully found the status of orchestration instance '{InstanceId}' with name '{Name}'.",
                status.InstanceId,
                status.Name);

            OperationType type = status.GetOperationType();

            if (type == OperationType.Unknown)
            {
                _logger.LogWarning("Orchestration instance with '{Name}' did not resolve to a public operation type.", status.Name);
                return(null);
            }

            OperationRuntimeStatus runtimeStatus = status.GetOperationRuntimeStatus();
            OperationProgress      progress      = GetOperationProgress(type, status);

            return(new OperationStatus
            {
                CreatedTime = status.CreatedTime,
                LastUpdatedTime = status.LastUpdatedTime,
                OperationId = operationId,
                PercentComplete = runtimeStatus == OperationRuntimeStatus.Completed ? 100 : progress.PercentComplete,
                Resources = await GetResourceUrlsAsync(type, progress.ResourceIds, cancellationToken),
                Status = runtimeStatus,
                Type = type,
            });
        }
        public override async Task ExecuteAsync(IOperationExecutionContext context)
        {
            this.progress = null;

            var sourceDirectory = context.ResolvePath(this.SourceDirectory);

            var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>().ConfigureAwait(false);

            var files = await fileOps.GetFileSystemInfosAsync(sourceDirectory, new MaskingContext(this.Includes, this.Excludes)).ConfigureAwait(false);

            if (files.Count == 0)
            {
                this.LogWarning("No files matched.");
                return;
            }

            var github = new GitHubClient(this.ApiUrl, this.UserName, this.Password, this.OrganizationName);

            var ownerName = AH.CoalesceString(this.OrganizationName, this.UserName);

            foreach (var info in files)
            {
                var file = info as SlimFileInfo;
                if (file == null)
                {
                    this.LogWarning($"Not a file: {info.FullName}");
                    continue;
                }

                using (var stream = await fileOps.OpenFileAsync(file.FullName, FileMode.Open, FileAccess.Read).ConfigureAwait(false))
                {
                    this.LogDebug($"Uploading {file.Name} ({AH.FormatSize(file.Size)})");
                    await github.UploadReleaseAssetAsync(ownerName, this.RepositoryName, this.Tag, file.Name, this.ContentType, new PositionStream(stream, file.Size), pos => this.progress = new OperationProgress((int)(100 * pos / file.Size), $"Uploading {file.Name} ({AH.FormatSize(pos)} / {AH.FormatSize(file.Size)})"), context.CancellationToken).ConfigureAwait(false);

                    this.progress = null;
                }
            }
        }
Example #18
0
        private void MakeOutputDataReceived(object source, ProcessDataReceivedEventArgs args)
        {
            int? percentage     = null;
            bool targetsChanged = false;

            var line = this.RemoveLogRubbish(args);

            if (line == null)
            {
                return;
            }

            if (line.Length > "[100%] ".Length && line[0] == '[' && line[4] == '%' && line[5] == ']' && line[6] == ' ')
            {
                percentage = AH.ParseInt(line.Substring(1, 3).TrimStart());
                if (line.Substring("[100%] ".Length).StartsWith("Built target "))
                {
                    if (activeTargets.Remove(line.Substring("[100%] Built target ".Length).Trim()))
                    {
                        targetsChanged = true;
                    }
                }
            }
            else if (line.StartsWith("Scanning dependencies of target "))
            {
                if (activeTargets.Add(line.Substring("Scanning dependencies of target ".Length).Trim()))
                {
                    targetsChanged = true;
                }
            }
            else if (line.StartsWith("CPack: "))
            {
                this.LogInformation(line);
                if (!line.StartsWith("CPack: - "))
                {
                    this.progress = new OperationProgress(100, line);
                }
                return;
            }

            if (targetsChanged || (percentage.HasValue && percentage != this.progress.Percent))
            {
                this.progress = new OperationProgress(percentage ?? this.progress.Percent, string.Join(", ", activeTargets));
            }

            if (this.ImageTag == "msvc" && (!targetsChanged || !percentage.HasValue) && args.Data != line && new[] { ".c", ".cc", ".cpp" }.Any(ext => line.EndsWith(ext)))
            {
                return;
            }

            if (targetsChanged && percentage.HasValue)
            {
                this.LogInformation(line);
            }
            else if (line.Contains(this.ImageTag == "msvc" ? " error C" : ": error: "))
            {
                this.LogError(line);
            }
            else if (line.Contains(this.ImageTag == "msvc" ? " warning C" : ": warning: "))
            {
                this.LogWarning(line);
            }
            else
            {
                this.LogDebug(line);
            }
        }
 protected void InitializeProgressUpdate(string header)
 {
     this.Progress      = new OperationProgress();
     this.overallRecord = new ProgressRecord(1, header, "Starting...");
 }
 public override Task ConfigureAsync(IOperationExecutionContext context) => PackageDeployer.DeployAsync(context, this.Template, this, "Ensure-Package", true, p => this.progress = p);
 public DataContext(OperationProgress progress)
 {
     Progress = progress;
 }
Example #22
0
 public override Task ExecuteAsync(IOperationExecutionContext context) => PackageDeployer.DeployAsync(context, this, this, "Get-Package", this.RecordDeployment, p => this.progress = p);
 public ConsoleDisplayUpdater(OperationProgress progress)
 {
     progressUpdater = progress.Percentage.Subscribe(DisplayProgress);
 }
Example #24
0
        public static async Task <int> Main(params string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
            OperationProgress progress = new OperationProgress();
            Stopwatch         sw       = new Stopwatch();
            uint count       = 0;
            var  rootCommand = new RootCommand("MSLA/DLP, file analysis, repair, conversion and manipulation")
            {
                new Option(new [] { "-f", "--file" }, "Input file to read")
                {
                    IsRequired = true,
                    Argument   = new Argument <FileSystemInfo>("filepath").ExistingOnly()
                },
                new Option(new [] { "-o", "--output" }, "Output file to save the modifications, if aware, it saves to the same input file")
                {
                    Argument = new Argument <FileSystemInfo>("filepath")
                },
                new Option(new [] { "-e", "--extract" }, "Extract file content to a folder")
                {
                    Argument = new Argument <DirectoryInfo>("folder")
                },
                new Option(new [] { "-c", "--convert" }, "Converts input into a output file format by it extension")
                {
                    Argument = new Argument <FileSystemInfo>("filepath"),
                },

                new Option(new [] { "-p", "--properties" }, "Print a list of all properties/settings"),
                new Option(new [] { "-gcode" }, "Print the GCode if available"),
                new Option(new [] { "-i", "--issues" }, "Compute and print a list of all issues"),
                new Option(new [] { "-r", "--repair" }, "Attempt to repair all issues")
                {
                    Argument = new Argument <int[]>("[start layer index] [end layer index] [islands 0/1] [remove empty layers 0/1] [resin traps 0/1]"),
                },

                new Option(new [] { "-mr", "--mut-resize" }, "Resizes layer images in a X and/or Y factor, starting from 100% value")
                {
                    Argument = new Argument <decimal[]>("[x%] [y%] [start layer index] [end layer index] [fade 0/1]")
                },
                new Option(new [] { "-ms", "--mut-solidify" }, "Closes all inner holes")
                {
                    Argument = new Argument <uint[]>("[start layer index] [end layer index]")
                },
                new Option(new [] { "-me", "--mut-erode" }, "Erodes away the boundaries of foreground object")
                {
                    Argument = new Argument <uint[]>("[start iterations] [end iterations] [start layer index] [end layer index] [fade 0/1]")
                },
                new Option(new [] { "-md", "--mut-dilate" }, "It is just opposite of erosion")
                {
                    Argument = new Argument <uint[]>("[start iterations] [end iterations] [start layer index] [end layer index] [fade 0/1]")
                },
                new Option(new [] { "-mc", "--mut-close" }, "Dilation followed by Erosion")
                {
                    Argument = new Argument <uint[]>("[start iterations] [end iterations] [start layer index] [end layer index] [fade 0/1]")
                },
                new Option(new [] { "-mo", "--mut-open" }, "Erosion followed by Dilation")
                {
                    Argument = new Argument <uint[]>("[start iterations] [end iterations] [start layer index] [end layer index] [fade 0/1]")
                },
                new Option(new [] { "-mg", "--mut-gradient" }, "The difference between dilation and erosion of an image")
                {
                    Argument = new Argument <uint[]>("[kernel size] [start layer index] [end layer index] [fade 0/1]")
                },

                new Option(new [] { "-mpy", "--mut-py" }, "Performs down-sampling step of Gaussian pyramid decomposition")
                {
                    Argument = new Argument <uint[]>("[start layer index] [end layer index]")
                },
                new Option(new [] { "-mgb", "--mut-gaussian-blur" }, "Each pixel is a sum of fractions of each pixel in its neighborhood")
                {
                    Argument = new Argument <ushort[]>("[aperture] [sigmaX] [sigmaY]")
                },
                new Option(new [] { "-mmb", "--mut-median-blur" }, "Each pixel becomes the median of its surrounding pixels")
                {
                    Argument = new Argument <ushort>("[aperture]")
                },
            };

            rootCommand.Handler = CommandHandler.Create(
                (
                    FileSystemInfo file,
                    FileSystemInfo convert,
                    DirectoryInfo extract,
                    bool properties,
                    bool gcode,
                    bool issues,
                    int[] repair
                    //decimal[] mutResize
                ) =>
            {
                var fileFormat = FileFormat.FindByExtension(file.FullName, true, true);
                if (ReferenceEquals(fileFormat, null))
                {
                    Console.WriteLine($"Error: {file.FullName} is not a known nor valid format.");
                }
                else
                {
                    Console.Write($"Reading: {file}");
                    sw.Restart();
                    fileFormat.Decode(file.FullName, progress);
                    sw.Stop();
                    Console.WriteLine($", in {sw.ElapsedMilliseconds}ms");
                    Console.WriteLine("----------------------");
                    Console.WriteLine($"Layers: {fileFormat.LayerCount} x {fileFormat.LayerHeight}mm = {fileFormat.PrintHeight}mm");
                    Console.WriteLine($"Resolution: {new Size((int) fileFormat.ResolutionX, (int) fileFormat.ResolutionY)}");
                    Console.WriteLine($"AntiAlias: {fileFormat.ValidateAntiAliasingLevel()}");

                    Console.WriteLine($"Bottom Layer Count: {fileFormat.BottomLayerCount}");
                    Console.WriteLine($"Bottom Exposure Time: {fileFormat.BottomExposureTime}s");
                    Console.WriteLine($"Layer Exposure Time: {fileFormat.ExposureTime}s");
                    Console.WriteLine($"Print Time: {fileFormat.PrintTime}s");
                    Console.WriteLine($"Cost: {fileFormat.MaterialCost}$");
                    Console.WriteLine($"Resin Name: {fileFormat.MaterialName}");
                    Console.WriteLine($"Machine Name: {fileFormat.MachineName}");

                    Console.WriteLine($"Thumbnails: {fileFormat.CreatedThumbnailsCount}");
                    Console.WriteLine("----------------------");
                }

                if (!ReferenceEquals(extract, null))
                {
                    Console.Write($"Extracting to {extract.FullName}");
                    sw.Restart();
                    fileFormat.Extract(extract.FullName, true, true, progress);
                    sw.Stop();
                    Console.WriteLine($", finished in {sw.ElapsedMilliseconds}ms");
                }

                if (properties)
                {
                    count = 0;
                    Console.WriteLine("Listing all properties:");
                    Console.WriteLine("----------------------");
                    foreach (var config in fileFormat.Configs)
                    {
                        Console.WriteLine("******************************");
                        Console.WriteLine($"\t{config.GetType().Name}");
                        Console.WriteLine("******************************");
                        foreach (PropertyInfo propertyInfo in config.GetType()
                                 .GetProperties(BindingFlags.Public | BindingFlags.Instance))
                        {
                            count++;
                            if (propertyInfo.Name.Equals("Item"))
                            {
                                continue;
                            }
                            Console.WriteLine($"{propertyInfo.Name}: {propertyInfo.GetValue(config)}");
                        }
                    }

                    Console.WriteLine("----------------------");
                    Console.WriteLine($"Total properties: {count}");
                }

                if (gcode)
                {
                    if (ReferenceEquals(fileFormat.GCode, null))
                    {
                        Console.WriteLine("No GCode available");
                    }
                    else
                    {
                        Console.WriteLine("----------------------");
                        Console.WriteLine(fileFormat.GCode);
                        Console.WriteLine("----------------------");
                        Console.WriteLine($"Total lines: {fileFormat.GCode.Length}");
                    }
                }

                if (issues)
                {
                    Console.WriteLine("Computing Issues, please wait.");
                    sw.Restart();
                    var issueList = fileFormat.LayerManager.GetAllIssues(null, null, null, null, true, null, progress);
                    sw.Stop();

                    Console.WriteLine("Issues:");
                    Console.WriteLine("----------------------");
                    count = 0;
                    foreach (var issue in issueList)
                    {
                        Console.WriteLine(issue);
                        count++;
                    }

                    /*for (uint layerIndex = 0; layerIndex < fileFormat.LayerCount; layerIndex++)
                     * {
                     *  if(!issuesDict.TryGetValue(layerIndex, out var list)) continue;
                     *  foreach (var issue in list)
                     *  {
                     *      Console.WriteLine(issue);
                     *      count++;
                     *  }
                     * }*/

                    Console.WriteLine("----------------------");
                    Console.WriteLine($"Total Issues: {count} in {sw.ElapsedMilliseconds}ms");
                }

                if (!ReferenceEquals(convert, null))
                {
                    var fileConvert = FileFormat.FindByExtension(convert.FullName, true, true);
                    if (ReferenceEquals(fileFormat, null))
                    {
                        Console.WriteLine($"Error: {convert.FullName} is not a known nor valid format.");
                    }
                    else
                    {
                        Console.WriteLine($"Converting {fileFormat.GetType().Name} to {fileConvert.GetType().Name}: {convert.Name}");

                        try
                        {
                            sw.Restart();
                            fileFormat.Convert(fileConvert, convert.FullName, progress);
                            sw.Stop();
                            Console.WriteLine($"Convertion done in {sw.ElapsedMilliseconds}ms");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                }

                if (!ReferenceEquals(repair, null))
                {
                    uint layerStartIndex   = (uint)(repair.Length >= 1 ? Math.Max(0, repair[0]) : 0);
                    uint layerEndIndex     = repair.Length >= 2 ? (uint)repair[1].Clamp(0, (int)(fileFormat.LayerCount - 1)) : fileFormat.LayerCount - 1;
                    bool repairIslands     = repair.Length < 3 || repair[2] > 0 || repair[2] < 0;
                    bool removeEmptyLayers = repair.Length < 4 || repair[3] > 0 || repair[3] < 0;
                    bool repairResinTraps  = repair.Length < 5 || repair[4] > 0 || repair[4] < 0;

                    //fileFormat.LayerManager.RepairLayers(layerStartIndex, layerEndIndex, 2, 1, 4, repairIslands, removeEmptyLayers, repairResinTraps, null, progress);
                }
            });


            //await rootCommand.InvokeAsync(args);
            await rootCommand.InvokeAsync("-f body_Tough0.1mm_SL1_5h16m_HOLLOW_DRAIN.sl1 -r -1");

            return(1);
        }
Example #25
0
 public void SetProgress(OperationProgress progress) => this.progress = progress;