Example #1
0
 public override void SetProcessOptions(ProcessOptions processOptions)
 {
     processOptions.Add(Command);
     processOptions.Add("-g", Global);
     AddOtherArguments(processOptions);
     AddStandardInput(processOptions);
 }
        public byte[] processImage(byte[] byteArray, CutSetting cutSetting, SizeSetting sizeSetting, ProcessOptions processOption)
        {
            byte[] result = null;

            using (MemoryStream ms = new MemoryStream(byteArray))
            {
                Image image = Image.FromStream(ms);

                if (processOption == ProcessOptions.ResizeFirst)
                {
                    if (sizeSetting != null && sizeSetting.FrameSize.Width > 0 && sizeSetting.FrameSize.Height > 0)
                    {
                        image = ImageProcessor.ResizeImage(image, sizeSetting.FrameSize, sizeSetting.Option);
                    }
                }

                if (cutSetting != null && cutSetting.RegionSize.Width > 0 && cutSetting.RegionSize.Height > 0)
                {
                    if (cutSetting.Position == PositionOptions.Custom)
                    {
                        Point point = cutSetting.LeftTopPosition;
                        double rate = 1.0;
                        if (point == null) point = new Point(0, 0);
                        if (cutSetting.PreviewRate != null) rate = cutSetting.PreviewRate.Value;
                        image = ImageProcessor.CutImage(image, new Rectangle(point, cutSetting.RegionSize), rate);
                    }
                    else
                    {
                        string positionOption = cutSetting.Position.ToString();
                        HorizonOptions horizonOption = HorizonOptions.Left;
                        VerticalOptions verticalOption = VerticalOptions.Top;

                        if (positionOption.Contains("Left")) horizonOption = HorizonOptions.Left;
                        else if (positionOption.Contains("Center")) horizonOption = HorizonOptions.Center;
                        else if (positionOption.Contains("Right")) horizonOption = HorizonOptions.Right;

                        if (positionOption.Contains("Top")) verticalOption = VerticalOptions.Top;
                        else if (positionOption.Contains("Middle")) verticalOption = VerticalOptions.Middle;
                        else if (positionOption.Contains("Bottom")) verticalOption = VerticalOptions.Bottom;

                        image = ImageProcessor.CutImage(image, cutSetting.RegionSize, horizonOption, verticalOption);
                    }
                }

                if (processOption == ProcessOptions.CutFirst)
                {
                    if (sizeSetting != null && sizeSetting.FrameSize.Width > 0 && sizeSetting.FrameSize.Height > 0)
                    {
                        image = ImageProcessor.ResizeImage(image, sizeSetting.FrameSize, sizeSetting.Option);
                    }
                }

                ImageConverter converter = new ImageConverter();
                result = (byte[])converter.ConvertTo(image, typeof(byte[]));
            }

            return result;
        }
Example #3
0
 protected override void AddOptions(ProcessOptions options)
 {
     options.Add("--name", Settings.Name);
     options.Add("--karma", PathUtils.GetRelativePath(WorkingDirectory, Settings.KarmaConfigFile));
     if (Settings.HasSettingsFile && File.Exists(Settings.SettingsFile))
     {
         options.Add("--settings", PathUtils.GetRelativePath(WorkingDirectory, Settings.SettingsFile));
     }
 }
 public string UploadImageByUrl(string url, CutSetting cutSetting, SizeSetting sizeSetting, ProcessOptions processOption)
 {
     byte[] image;
     using (WebClient client = new WebClient())
     {
         image = client.DownloadData(Server.UrlDecode(url));
     }
     return saveImage(processImage(image, cutSetting, sizeSetting, processOption)).ToString();
 }
Example #5
0
        /// <summary>
        ///     Initializes a new instance of this ProcessWatchdog with the specified options.
        ///     The given host process will only be started once <see cref="Start()" /> is called.
        /// </summary>
        /// <param name="executable"></param>
        /// <param name="options"></param>
        /// <param name="processReadyTimeout">The amount of time the host process has to report being ready before it is assumed to be dead</param>
        /// <exception cref="ArgumentNullException">
        ///     When <paramref name="executable" /> is null
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     When <paramref name="executable" /> is contains only whitespace
        /// </exception>
        public ProcessWatchdog(
            string executable            = SharpRemoteHost,
            ProcessOptions options       = ProcessOptions.HideConsole,
            TimeSpan?processReadyTimeout = null
            )
        {
            if (executable == null)
            {
                throw new ArgumentNullException(nameof(executable));
            }
            if (string.IsNullOrWhiteSpace(executable))
            {
                throw new ArgumentException("executable");
            }

            _processReadyTimeout = processReadyTimeout ?? new FailureSettings().ProcessReadyTimeout;
            _waitHandle          = new ManualResetEvent(false);
            _hostedProcessState  = HostState.BootPending;
            _syncRoot            = new object();

            _parentPid = Process.GetCurrentProcess().Id;
            _startInfo = new ProcessStartInfo(executable)
            {
                Arguments = FormatArguments(_parentPid),
                RedirectStandardOutput = true,
                UseShellExecute        = false
            };
            switch (options)
            {
            case ProcessOptions.HideConsole:
                _startInfo.CreateNoWindow = true;
                break;

            case ProcessOptions.ShowConsole:
                _startInfo.CreateNoWindow = false;
                break;
            }


            _hasProcessExited = true;
        }
        public void SwappingOptions()
        {
            ProcessOptions options = ResponsiveWindowedProcessOptions;

            using (ProcessRunner runner = new ProcessRunner(options))
            {
                runner.Stop();
                Assert.IsNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Stopped);

                runner.Start();
                Assert.IsNotNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Running);

                runner.ProcessOptions = options;
                Assert.IsNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Stopped);

                Assert.IsFalse(ReferenceEquals(runner.ProcessOptions, options));
            }
        }
        public void StateRestore()
        {
            ProcessOptions options = ResponsiveWindowedProcessOptions;

            using (ProcessRunner runner = new ProcessRunner(options))
            {
                runner.RestoreState();
                Assert.AreEqual(runner.State, ProcessRunner.Status.Stopped);

                runner.State = ProcessRunner.Status.Disabled;
                runner.RestoreState();
                Assert.AreEqual(runner.State, ProcessRunner.Status.Stopped);

                runner.State = ProcessRunner.Status.Disabled;

                // this should be a no-op
                runner.State = ProcessRunner.Status.Disabled;
                runner.RestoreState();
                Assert.AreEqual(runner.State, ProcessRunner.Status.Stopped);
            }
        }
Example #8
0
        /// <summary>
        /// Creates a new process and assigns the process to the job object.
        /// </summary>
        /// <param name="createProcessInfo">The <see cref="CreateProcessInfo"/> that contains information this is
        /// used to start the process, including the file name and any command-line arguments.</param>
        /// <param name="processOptions">A set of <see cref="ProcessOptions"/> that controls how the new process
        /// is created.</param>
        /// <returns>A <see cref="Process"/> instance that represents the newly created process.</returns>
        public Process CreateProcess(CreateProcessInfo createProcessInfo, ProcessOptions processOptions)
        {
            if (createProcessInfo == null)
            {
                throw new ArgumentNullException(nameof(createProcessInfo));
            }

            CheckDisposed();

            Process newProcess = null;

            try
            {
                // create the process, forcing it to be suspened..
                newProcess = new Process(createProcessInfo, processOptions | ProcessOptions.Suspended);

                // assign the process to this job object..
                if (!Interop.Kernel32.AssignProcessToJobObject(Handle, newProcess.Handle))
                {
                    throw Errors.Win32Error();
                }

                // if the process wasn't requested to be started in a suspended state then
                // resume the process now..

                if ((processOptions & ProcessOptions.Suspended) == 0)
                {
                    newProcess.Resume();
                }
            }
            catch
            {
                // if assignment fails, kill the process and dispose of it..
                newProcess?.Kill();
                newProcess?.Dispose();
                throw;
            }

            return(newProcess);
        }
Example #9
0
        private async Task ProcessTask(BatchModel model, CancellationToken token)
        {
            var tempPath = Path.Combine(Path.GetTempPath(), "PSXPackager");


            while (await _channel.Reader.WaitToReadAsync())
            {
                var job = await _channel.Reader.ReadAsync();

                var notifier = new ProcessNotifier(_dispatcher);
                notifier.Entry = job.Entry;

                var processing = new Popstation.Processing(notifier, _eventHandler, _gameDb);


                var processOptions = new ProcessOptions()
                {
                    ////Files = files,
                    OutputPath = model.Settings.OutputPath,
                    TempPath   = tempPath,
                    Discs      = Enumerable.Range(1, 5).ToList(),
                    //CheckIfFileExists = !o.OverwriteIfExists,
                    //SkipIfFileExists = o.SkipIfExists,
                    FileNameFormat   = _settings.FileNameFormat,
                    CompressionLevel = _settings.CompressionLevel,
                    ////Verbosity = o.Verbosity,
                    ////Log = o.Log,
                    ExtractResources        = model.ExtractResources,
                    ImportResources         = _settings.UseCustomResources,
                    GenerateResourceFolders = model.GenerateResourceFolders,
                    CustomResourceFormat    = _settings.CustomResourcesFormat,
                    ResourceFoldersPath     = _settings.CustomResourcesPath,
                };

                await Task.Run(() =>
                {
                    processing.ProcessFile(Path.Combine(model.Settings.InputPath, job.Entry.RelativePath), processOptions, token);
                });
            }
        }
Example #10
0
        /// <summary>
        /// Gets the absolute path to the IP command.
        /// </summary>
        /// <returns></returns>
        private string GetIPCommandPath()
        {
            // Build layout of what we want to do.
            var ipProcessOptions = new ProcessOptions()
            {
                InvokeAsSuperuser = true,
                Monitor           = false,
                DisposeOnExit     = true,
                Executable        = "which",
                Arguments         = new[] { "ip" },
                ThrowOnError      = true
            };

            // Execute the options
            var commandHolder = _processRunner.Run(ipProcessOptions);

            // Wait for exit.
            commandHolder.Command.Wait();

            // Return the data wae need.
            return(commandHolder.Command.StandardOutput.ReadToEnd().Trim());
        }
        /// <summary>
        /// This pipeline command creates a Persistence Message Initiator.
        /// </summary>
        /// <typeparam name="C">The incoming channel type.</typeparam>
        /// <typeparam name="K">The key type.</typeparam>
        /// <typeparam name="E">The entity type.</typeparam>
        /// <param name="cpipe">The incoming channel.</param>
        /// <param name="command">The output command.</param>
        /// <param name="responseChannel">The channel to send the response message on. If this is not set, a default response channel will be created.</param>
        /// <param name="startupPriority"></param>
        /// <param name="cacheManager">The cache manager to attach to the persistence agent</param>
        /// <param name="defaultRequestTimespan">The default time out time. If not set, this defaults to 30s as set in the command initiator policy.</param>
        /// <param name="routing">The route map will attempt to first route the message internally and then try an external channel.</param>
        /// <returns>The passthrough for the channel.</returns>
        public static C AttachPersistenceClient <C, K, E>(this C cpipe
                                                          , out PersistenceClient <K, E> command
                                                          , string responseChannel            = null
                                                          , int startupPriority               = 90
                                                          , ICacheManager <K, E> cacheManager = null
                                                          , TimeSpan?defaultRequestTimespan   = null
                                                          , ProcessOptions routing            = ProcessOptions.RouteExternal | ProcessOptions.RouteInternal
                                                          )
            where C : IPipelineChannelIncoming <IPipeline>
            where K : IEquatable <K>
        {
            var ms = cpipe.ToMicroservice();

            command = new PersistenceClient <K, E>(cacheManager, defaultRequestTimespan);

            if (responseChannel == null || !cpipe.ToMicroservice().Communication.HasChannel(responseChannel, ChannelDirection.Incoming))
            {
                var outPipe = cpipe.ToPipeline().AddChannelIncoming($"PersistenceClient{command.ComponentId.ToString("N").ToUpperInvariant()}");
                command.ResponseChannelId = outPipe.Channel.Id;
            }
            else
            {
                //If the response channel is not set, dynamically create a response channel.
                command.ResponseChannelId = responseChannel;
            }

            //Check that the response channel exists
            if (!cpipe.ToMicroservice().Communication.HasChannel(command.ResponseChannelId, ChannelDirection.Incoming))
            {
                throw new ChannelDoesNotExistException(command.ResponseChannelId, ChannelDirection.Incoming, ms.Id.Name);
            }

            command.ChannelId      = cpipe.Channel.Id;
            command.RoutingDefault = routing;

            cpipe.Pipeline.AddCommand(command, startupPriority);

            return(cpipe);
        }
Example #12
0
        public BatchClassification(ref Klu klu, ref TrainingDataSet dataSet, ProcessOptions processOptions)
        {
            InitializeComponent();

            _DataSet        = dataSet;
            _SelectedFiles  = new ArrayList();
            _ProcessOptions = processOptions;
            // We want the images to be as less distorded as possible, so we disable all the overlays.

            _ProcessOptions.DrawAnthropometricPoints = 0;
            _ProcessOptions.DrawDetectionTime        = 0;
            _ProcessOptions.DrawFaceRectangle        = 0;
            _ProcessOptions.DrawSearchRectangles     = 0;
            _ProcessOptions.DrawFeaturePoints        = 0;

            _KLU        = klu;
            _FFP        = new FaceFeaturePoints();
            _TempBitmap = new System.Drawing.Bitmap(10, 10);

            ExpressionsComboBox.ItemsSource = _DataSet.Expression;
            ClassifyButton.Content          = "Classify";
        }
Example #13
0
        public void TestProcessCommand_IsVerbosePropagation()
        {
            // Preconditions
            Debug.Assert(managerMock != null);
            Debug.Assert(outputMock != null);

            /* GIVEN */
            outputMock.SetupSet(output => output.IsVerbose = true);

            var command = new ProcessCommand(managerMock.Object, outputMock.Object);
            var options = new ProcessOptions
            {
                IsVerbose  = true,
                ConfigPath = "C:/",
                InputFile  = "C:/"
            };

            /* WHEN */
            command.Execute(options);

            /* THEN */
            outputMock.VerifySet(output => output.IsVerbose = true);
        }
Example #14
0
        private void chuanHoaDuLieu(ProcessOptions options)
        {
            if (options == ProcessOptions.AutoUpperFirstCharGiaDinh || options == ProcessOptions.AutoUpperFirstCharGiaoDan)
            {
                frmProcess frmUpdate = new frmProcess();

                if (options == ProcessOptions.AutoUpperFirstCharGiaoDan)
                {
                    if (MessageBox.Show("Bạn có chắc muốn thực hiện việc chuẩn hóa dữ liệu (tất cả các dữ liệu được nhập cho giáo dân sẽ được chuyển hóa theo quy tắc viết hoa chữ cái đầu tiên mỗi từ, các ký tự khác trong từ chuyển thành chữ thường, trừ các ghi chú)?",
                                        "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        return;
                    }
                    frmUpdate.LabelStart    = "Đang chuẩn hóa dữ liệu giáo dân...";
                    frmUpdate.LableFinished = "Đã thực hiện xong!";
                    frmUpdate.Text          = "Đang chuẩn hóa dữ liệu giáo dân. Có thể mất vài phút. Xin vui lòng đợi...";
                }
                else
                {
                    if (MessageBox.Show("Bạn có chắc muốn thực hiện việc chuẩn hóa dữ liệu (tất cả các dữ liệu được nhập cho gia đình sẽ được chuyển hóa theo quy tắc viết hoa chữ cái đầu tiên mỗi từ, các ký tự khác trong từ viết thường, trừ các ghi chú)?",
                                        "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        return;
                    }
                    frmUpdate.LabelStart    = "Đang chuẩn hóa dữ liệu gia đình...";
                    frmUpdate.LableFinished = "Đã thực hiện xong!";
                    frmUpdate.Text          = "Đang chuẩn hóa dữ liệu gia đình. Có thể mất vài phút. Xin vui lòng đợi...";
                }

                frmUpdate.ProcessClass = new UpdateProcess();
                frmUpdate.ProcessClass.ProcessOptions = options;
                frmUpdate.StartFunction    = new EventHandler(frmUpdate_OnUpdating);
                frmUpdate.ErrorFunction    = new CancelEventHandler(frmUpdate_OnError);
                frmUpdate.FinishedFunction = new EventHandler(frmUpdate_OnFinished);
                frmUpdate.ShowDialog();
            }
        }
Example #15
0
        public CommonProcess(ProcessOptions options)
        {
            _options = options;

            var startInfo = new ProcessStartInfo
            {
                Arguments              = options.Arguments,
                FileName               = options.FileName,
                WorkingDirectory       = options.WorkingDirectory,
                UseShellExecute        = options.UseShellExecute,
                CreateNoWindow         = options.CreateNoWindow,
                RedirectStandardError  = options.RedirectStandardError,
                RedirectStandardInput  = options.RedirectStandardInput,
                RedirectStandardOutput = options.RedirectStandardOutput
            };

#if NET46
            startInfo.ErrorDialog = options.ErrorDialog;

            if (options.IsHidden)
            {
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            }
#endif

            _process = new Process
            {
                StartInfo = startInfo
            };

            if (options.EnableRaisingEvents)
            {
                _process.EnableRaisingEvents = true;
                _process.Exited += _process_Exited;
            }
        }
Example #16
0
        public void TestProcessCommand_Successful()
        {
            // Preconditions
            Debug.Assert(managerMock != null);
            Debug.Assert(outputMock != null);

            /* GIVEN */
            var command = new ProcessCommand(managerMock.Object, outputMock.Object);
            var options = new ProcessOptions
            {
                IsVerbose  = false,
                ConfigPath = Assembly.GetExecutingAssembly().Location,
                InputFile  = "C:/"
            };

            /* WHEN */
            var returnCode = command.Execute(options);

            /* THEN */

            // We test if the command was successful and returned code 0.
            Assert.AreEqual(successCode, returnCode);
            managerMock.Verify(manager => manager.Process(It.IsAny <IEnumerable <DirectoryPath> >()), Times.Once);
        }
Example #17
0
        private void OnProcessListViewDragDrop(object sender, DragEventArgs e)
        {
            string[] dragged_files = e.Data.GetData(DataFormats.FileDrop, false) as string[];

            if (dragged_files == null)
            {
                return;
            }

            foreach (string dragged_file in dragged_files)
            {
                if (!ProcessManager.Contains(dragged_file))
                {
                    ProcessOptions opts = new ProcessOptions();

                    opts.Path             = dragged_file;
                    opts.WorkingDirectory = Path.GetDirectoryName(opts.Path);

                    ProcessManager.Add(opts);
                }
            }

            UpdateProcessList();
        }
Example #18
0
        public CreateMultipleResourcesResponse CreateByFiles(ProcessOptions options, params FileInfo[] files)
        {
            if (this.Token == null)
            {
                throw new UnauthorizedAccessException("Empty token!");
            }
            else
            {
                this.Token.Validate();
            }

            string json;

            using (HttpClient client = new HttpClient())
            {
                client.SetCopyleaksClient(HttpContentTypes.Json, this.Token);

                client.Timeout = TimeSpan.FromMinutes(10);                 // Uploading large file may take a while

                HttpResponseMessage msg;

                if (options != null)
                {
                    options.AddHeaders(client);
                }

                using (var content = new MultipartFormDataContent("Upload----" + DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)))
                {
                    string filename;
                    int    counter = 1;
                    foreach (var file in files)
                    {
                        filename = Path.GetFileName(file.FullName);
                        content.Add(new StreamContent(file.OpenRead()), "document_" + (++counter), filename);
                    }
                    msg = client.PostAsync(string.Format("v2/{0}/create-by-file", this.Product.ToName()), content).Result;
                }

                if (!msg.IsSuccessStatusCode)
                {
                    throw new CommandFailedException(msg);
                }

                json = msg.Content.ReadAsStringAsync().Result;
            }

            var dateTimeConverter = new IsoDateTimeConverter {
                DateTimeFormat = "dd/MM/yyyy HH:mm:ss"
            };
            var data = JsonConvert.DeserializeObject <InnerCreateMultipleResourcesResponse>(json, dateTimeConverter);

            CopyleaksProcess[] processes = new CopyleaksProcess[data.Success.Length];
            for (int i = 0; i < data.Success.Length; ++i)
            {
                processes[i] = new CopyleaksProcess(this.Token, this.Product, data.Success[i], null);
            }

            return(new CreateMultipleResourcesResponse()
            {
                Success = processes,
                Errors = data.Errors
            });
        }
Example #19
0
        public void StateChangesDoNotAssumeCrashIfNotRunning()
        {
            ProcessOptions options = ResponsiveWindowedProcessOptions;

            options.CrashedIfNotRunning = false;

            // running to stopped
            options.InitialStateEnumValue = ProcessRunner.Status.Running;
            using (ProcessRunner runner = new ProcessRunner(options))
            {
                runner.Monitor();
                Assert.IsNotNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Running);

                runner.State = ProcessRunner.Status.Stopped;
                runner.Monitor();
                Assert.IsNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Stopped);
            }

            // running to disabled
            options.InitialStateEnumValue = ProcessRunner.Status.Running;
            using (ProcessRunner runner = new ProcessRunner(options))
            {
                runner.Monitor();
                Assert.IsNotNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Running);

                runner.State = ProcessRunner.Status.Disabled;
                runner.Monitor();
                Assert.IsNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Disabled);
            }

            // stopped to running
            options.InitialStateEnumValue = ProcessRunner.Status.Stopped;
            using (ProcessRunner runner = new ProcessRunner(options))
            {
                runner.Monitor();
                Assert.IsNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Stopped);

                runner.State = ProcessRunner.Status.Running;
                runner.Monitor();
                Assert.IsNotNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Running);
            }

            // stopped to disabled
            options.InitialStateEnumValue = ProcessRunner.Status.Stopped;
            using (ProcessRunner runner = new ProcessRunner(options))
            {
                runner.Monitor();
                Assert.IsNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Stopped);

                runner.State = ProcessRunner.Status.Disabled;
                runner.Monitor();
                Assert.IsNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Disabled);
            }

            // disabled to running
            options.InitialStateEnumValue = ProcessRunner.Status.Disabled;
            using (ProcessRunner runner = new ProcessRunner(options))
            {
                runner.Monitor();
                Assert.IsNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Disabled);

                runner.State = ProcessRunner.Status.Running;
                runner.Monitor();
                Assert.IsNotNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Running);
            }

            // disabled to stopped
            options.InitialStateEnumValue = ProcessRunner.Status.Disabled;
            using (ProcessRunner runner = new ProcessRunner(options))
            {
                runner.Monitor();
                Assert.IsNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Disabled);

                runner.State = ProcessRunner.Status.Stopped;
                runner.Monitor();
                Assert.IsNull(runner.Process);
                Assert.AreEqual(runner.State, ProcessRunner.Status.Stopped);
            }
        }
 public virtual IProcessManager Create(ProcessOptions options = null, ProcessStartedEventHandler callback = null)
 {
     return(Create <IProcessManager>(options, callback).Object);
 }
 /// <summary>
 /// Always forces the image to be re-encoded even if it wasn't modified. 
 /// No prevents the image from being modified.
 /// </summary>
 public static ImageUrlBuilder Process(this ImageUrlBuilder builder, ProcessOptions processOption = ProcessOptions.Default)
 {
     return builder.SetParameter(MiscCommands.Process, processOption.ToString().ToLowerInvariant());
 }
        public string Prepare(IRequestContext client, string executable, string arguments, ProcessOptions options,
                              string workingDir, string accessToken)
        {
            if (accessToken != this.accessToken)
            {
                throw new UnauthorizedAccessException();
            }
            if (cts.IsCancellationRequested)
            {
                return(null);
            }

            var outputProcessor = new RaiseUntilDetachOutputProcess();
            var task            = new NativeProcessListTask <string>(taskManager, processEnvironment, executable, arguments,
                                                                     outputProcessor: outputProcessor, cts.Token)
                                  .Configure(processManager, workingDir);

            var startInfo = ProcessInfo.FromStartInfo(task.Wrapper.StartInfo);
            var id        = options.MonitorOptions == MonitorOptions.KeepAlive ? startInfo.GetId() : Guid.NewGuid().ToString();

            SetupProcess(client, new RpcProcess(id, startInfo, options), task, outputProcessor);

            return(id);
        }
            public Task <RpcProcess> Prepare(ProcessInfo startInfo, ProcessOptions options, string accessToken)
            {
                var id = owner.Prepare(client, startInfo, options, accessToken);

                return(Task.FromResult(owner.GetProcess(id)));
            }
            public Task <RpcProcess> Prepare(string executable, string args, ProcessOptions options, string accessToken)
            {
                var id = owner.Prepare(client, executable, args, options, null, accessToken);

                return(Task.FromResult(owner.GetProcess(id)));
            }
Example #25
0
 public IProcessTask <string> NewMonoProcess(string executable, string arguments, ProcessOptions options = default,
                                             string workingDir = default,
                                             Action <IProcessTask <string> > onStart         = null,
                                             Action <IProcessTask <string>, string> onOutput = null,
                                             Action <IProcessTask <string>, string, bool, Exception> onEnd = null,
                                             IOutputProcessor <string> outputProcessor = null,
                                             TaskAffinity affinity   = TaskAffinity.None,
                                             CancellationToken token = default
                                             )
 {
     return(ConfigureProcess(
                new MonoProcessTask <string>(TaskManager, localProcessManager.DefaultProcessEnvironment, Environment,
                                             executable, arguments,
                                             outputProcessor ?? new StringOutputProcessor())
     {
         Affinity = affinity
     },
                options, workingDir, onStart, onOutput, onEnd));
 }
Example #26
0
        /// <summary>
        /// Submitting picture, containing textual content, to plagiarism scan
        /// </summary>
        /// <param name="localfile">The local picture containing the content to scan</param>
        /// <param name="ocrLanguage">
        ///		Specify the language id of the text. Retrive supported languages by calling the
        ///		method "CopyleaksCloud.SupportedOcrLanguages". Only valid language id will be accepted by the server
        ///		Full supported languages list: https://api.copyleaks.com/GeneralDocumentation/OcrLanguages/
        /// </param>
        /// <param name="options">Process Options: include http callback and add custom fields to the process</param>
        /// <exception cref="UnauthorizedAccessException">The login-token is undefined or expired</exception>
        /// <returns>The newly created process</returns>
        public CopyleaksProcess CreateByOcr(FileInfo localfile, string ocrLanguage, ProcessOptions options = null)
        {
            if (this.Token == null)
            {
                throw new UnauthorizedAccessException("Empty token!");
            }
            else
            {
                this.Token.Validate();
            }

            if (!localfile.Exists)
            {
                throw new FileNotFoundException("File not found!", localfile.FullName);
            }

            if (string.IsNullOrEmpty(ocrLanguage))
            {
                throw new ArgumentNullException(nameof(ocrLanguage), "Cannot be null or empty!");
            }

            using (HttpClient client = new HttpClient())
            {
                client.SetCopyleaksClient(HttpContentTypes.Json, this.Token);

                if (options != null)
                {
                    options.AddHeaders(client);
                }

                HttpResponseMessage msg;
                // Uploading the local file to the server

                using (var content = new MultipartFormDataContent("Upload----" + DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)))
                    using (FileStream stream = localfile.OpenRead())
                    {
                        content.Add(new StreamContent(stream, (int)stream.Length), "document", Path.GetFileName(localfile.Name));
                        msg = client.PostAsync(
                            string.Format("{0}/{1}/create-by-file-ocr?language={2}", Resources.ServiceVersion, this.Product.ToName(), Uri.EscapeDataString(ocrLanguage)),
                            content).Result;
                    }

                if (!msg.IsSuccessStatusCode)
                {
                    throw new CommandFailedException(msg);
                }

                string json = msg.Content.ReadAsStringAsync().Result;

                var dateTimeConverter = new IsoDateTimeConverter {
                    DateTimeFormat = "dd/MM/yyyy HH:mm:ss"
                };
                CreateResourceResponse response = JsonConvert.DeserializeObject <CreateResourceResponse>(json, dateTimeConverter);
                if (options == null)
                {
                    return(new CopyleaksProcess(this.Token, this.Product, response, null));
                }
                else
                {
                    return(new CopyleaksProcess(this.Token, this.Product, response, options.CustomFields));
                }
            }
        }
 public SimulationOptions(TerraformingOptions terraformingOptions, ProcessOptions processOptions)
 {
     _terraformingOptions = terraformingOptions;
     ProcessOptions       = processOptions;
 }
Example #28
0
        public static string ConvertToString(ProcessOptions flags)
        {
            string results = null;

            foreach (ProcessOptions flag in Enum.GetValues(typeof(ProcessOptions)))
            {
                switch (flag)
                {
                    case ProcessOptions.None:
                        continue;
                }

                if ((flags & flag) == flag)
                {
                    results += ", " + flag.ToString();
                }
            }

            return results;
        }
Example #29
0
 public QueueItem(SimDescription sim, ProcessOptions options)
 {
     mSim = sim;
     mOptions = options;
 }
Example #30
0
 /// <summary>
 /// Always forces the image to be re-encoded even if it wasn't modified.
 /// No prevents the image from being modified.
 /// </summary>
 public static ImageUrlBuilder Process(this ImageUrlBuilder builder, ProcessOptions processOption = ProcessOptions.Default)
 {
     return(builder.SetParameter(MiscCommands.Process, processOption.ToString().ToLowerInvariant()));
 }
 public string UploadFile(byte[] image, CutSetting cutSetting, SizeSetting sizeSetting, ProcessOptions processOption)
 {
     return saveImage(processImage(image, cutSetting, sizeSetting, processOption)).ToString();
 }
Example #32
0
 public void Configure(ProcessOptions options)
 {
     ProcessOptions = options;
 }
Example #33
0
        public GrowthZoneInfoPathNode(IZoneInfo zoneInfo, ZoneClusterMemberConsumption clusterMemberConsumption, ProcessOptions processOptions, HashSet <BaseGrowthZoneClusterConsumption> undesirableGrowthZones)
            : base(
                zoneInfo: zoneInfo,
                canBeJoinedFunc: (previousPath, currentZoneInfo) =>
        {
            var matchingPath = previousPath;

            if (processOptions.GetStepByStepGrowthCyclingToggled())
            {
                Thread.Sleep(50);
            }

            var evaluatingNonIntersection = false;

            while (!evaluatingNonIntersection)
            {
                var intersection =
                    matchingPath.ZoneInfo.ConsumptionState.GetZoneConsumption() as
                    IntersectingZoneConsumption;

                if (intersection != null)
                {
                    matchingPath = matchingPath.PreviousPathNode;
                }
                else
                {
                    evaluatingNonIntersection = true;
                }
            }
            matchingPath.ZoneInfo.GrowthAlgorithmHighlightState.SetState(HighlightState.Examined);
            currentZoneInfo.MatchingObject.GrowthAlgorithmHighlightState.SetState(HighlightState.Examined);

            Func <bool> isSuccessFunc       = null;
            string currentIsSuccessFuncDesc = String.Empty;

            Action <string, Func <bool> > assignIsSuccessOverrideFuncAction = (description, action) =>
            {
                isSuccessFunc            = action;
                currentIsSuccessFuncDesc = description;
            };

            Action <string, Func <bool> > assignIsSuccessFuncAction = (description, action) =>
            {
                if (isSuccessFunc != null)
                {
                    throw new InvalidOperationException($"Could not set {description} as the 'IsSuccessFunc'. {currentIsSuccessFuncDesc} Is currently set.");
                }
                assignIsSuccessOverrideFuncAction(description, action);
            };

            // If the current zone is a growth zone...
            currentZoneInfo
            .MatchingObject
            .WithZoneClusterIf <BaseGrowthZoneClusterConsumption>(growthZone =>
            {
                if (!growthZone.HasPower)
                {
                    return;
                }

                // And the previous path member was also a growth zone, then
                // they must both be part of the zone cluster that originated this
                // path...
                matchingPath
                .ZoneInfo
                .WithZoneClusterIf <BaseGrowthZoneClusterConsumption>(res =>
                                                                      assignIsSuccessFuncAction("BaseGrowthZoneClusterConsumption",
                                                                                                () =>
                                                                                                res == clusterMemberConsumption.ParentBaseZoneClusterConsumption &&
                                                                                                growthZone == clusterMemberConsumption.ParentBaseZoneClusterConsumption)
                                                                      );

                // And the previous zone was a road zone...
                matchingPath
                .ZoneInfo
                .WithNetworkConsumptionIf <RoadZoneConsumption>(previousRoadZone => assignIsSuccessFuncAction("RoadZoneConsumption", () => true));
            });

            // If the current zone is a road...
            currentZoneInfo
            .MatchingObject
            .WithNetworkConsumptionIf <RoadZoneConsumption>(currentRoadZone =>
            {
                // And the previous zone was a growth zone...
                matchingPath
                .ZoneInfo
                .WithZoneClusterIf <BaseGrowthZoneClusterConsumption>(res => assignIsSuccessFuncAction(
                                                                          "BaseGrowthZoneClusterConsumption", () =>
                                                                          (res ==
                                                                           clusterMemberConsumption
                                                                           .ParentBaseZoneClusterConsumption)));

                // And the previous zone was a trainstation...
                matchingPath
                .ZoneInfo
                .WithZoneClusterIf <TrainStationZoneClusterConsumption>(res => assignIsSuccessOverrideFuncAction("RoadZoneConsumption/TrainStationZoneClusterConsumption", () => true));

                // And the previous one was also a road...
                matchingPath
                .ZoneInfo
                .WithNetworkConsumptionIf <RoadZoneConsumption>(
                    previousRoadZone => assignIsSuccessFuncAction("RoadZoneConsumption", () => true));
            });

            // If the current zone is a railroad...
            currentZoneInfo
            .MatchingObject
            .WithNetworkConsumptionIf <RailRoadZoneConsumption>(currentRailRoad =>
            {
                // And the previous one was also a railroad...
                matchingPath
                .ZoneInfo
                .WithNetworkConsumptionIf <RailRoadZoneConsumption>(
                    previousRailRoadZone => assignIsSuccessFuncAction("RailRoadZoneConsumption", () => true));

                // And the previous zone was a trainstation zone...
                matchingPath
                .ZoneInfo
                .WithZoneClusterIf <TrainStationZoneClusterConsumption>(res =>
                {
                    if (res.HasPower)
                    {
                        assignIsSuccessOverrideFuncAction(
                            "RailRoadZoneConsumption/TrainStationZoneClusterConsumption",
                            () => true
                            );
                    }
                });
            });

            // If the current zone is a trainstation zone...
            currentZoneInfo
            .MatchingObject
            .WithZoneClusterIf <TrainStationZoneClusterConsumption>(growthZone =>
            {
                if (!growthZone.HasPower)
                {
                    return;
                }

                // And the previous zone was part of the same trainstation...
                matchingPath
                .ZoneInfo
                .WithZoneClusterIf <TrainStationZoneClusterConsumption>(res => assignIsSuccessFuncAction("TrainStationZoneClusterConsumption/TrainStationZoneClusterConsumption", () => growthZone == res));

                // And the previous one was a road...
                matchingPath
                .ZoneInfo
                .WithNetworkConsumptionIf <RoadZoneConsumption>(
                    previousRoadZone => assignIsSuccessFuncAction("RoadZoneConsumption", () => true));

                // And the previous one was a road...
                matchingPath
                .ZoneInfo
                .WithNetworkConsumptionIf <RailRoadZoneConsumption>(
                    previousRoadZone => assignIsSuccessFuncAction("RailRoadZoneConsumption", () => true));
            });

            return(isSuccessFunc != null &&
                   isSuccessFunc());
        },
                getDestinationHashCode: (match) =>
        {
            var destinationHashCode = default(int?);

            if (clusterMemberConsumption.ParentBaseZoneClusterConsumption is IndustrialZoneClusterConsumption)
            {
                match.WithZoneClusterIf <ResidentialZoneClusterConsumption>(
                    cluster =>
                {
                    if (undesirableGrowthZones.Contains(cluster))
                    {
                        return;
                    }
                    if (cluster.GetType() !=
                        clusterMemberConsumption.ParentBaseZoneClusterConsumption
                        .GetType())
                    {
                        destinationHashCode = cluster.GetHashCode();
                    }
                });
            }
            else
            {
                match.WithZoneClusterIf <BaseGrowthZoneClusterConsumption>(
                    cluster =>
                {
                    if (undesirableGrowthZones.Contains(cluster))
                    {
                        return;
                    }
                    if (cluster.GetType() !=
                        clusterMemberConsumption.ParentBaseZoneClusterConsumption
                        .GetType())
                    {
                        destinationHashCode = cluster.GetHashCode();
                    }
                });
            }
            return(destinationHashCode);
        },
                distanceTracker: new ZoneInfoDistanceTracker(new Func <Func <IZoneInfo, bool>[]>(() =>
        {
            if (clusterMemberConsumption.ParentBaseZoneClusterConsumption is ResidentialZoneClusterConsumption)
            {
                return(new Func <IZoneInfo, bool>[]
                {
                    x => x.IsGrowthZoneClusterOfType <CommercialZoneClusterConsumption>(),
                    x => x.IsGrowthZoneClusterOfType <IndustrialZoneClusterConsumption>()
                });
            }
            if (clusterMemberConsumption.ParentBaseZoneClusterConsumption is CommercialZoneClusterConsumption)
            {
                return(new Func <IZoneInfo, bool>[]
                {
                    x => x.IsGrowthZoneClusterOfType <ResidentialZoneClusterConsumption>(),
                    x => x.IsGrowthZoneClusterOfType <IndustrialZoneClusterConsumption>()
                });
            }
            if (clusterMemberConsumption.ParentBaseZoneClusterConsumption is IndustrialZoneClusterConsumption)
            {
                return(new Func <IZoneInfo, bool>[]
                {
                    x => x.IsGrowthZoneClusterOfType <ResidentialZoneClusterConsumption>()
                });
            }

            throw new InvalidOperationException();
        })()
                                                             )
                )
        {
            OriginBaseZoneClusterConsumption = clusterMemberConsumption.ParentBaseZoneClusterConsumption;
        }
Example #34
0
 public IProcess Create(ProcessOptions options)
 {
     return(new CommonProcess(options));
 }
        public void Scan(string email, string apiKey)
        {
            Facmng mng    = new Facmng();
            Accmng accmng = new Accmng();
            string path   = @"E:\cscolor\result.txt";
            var    file   = File.CreateText(path);

            file.Close();
            StreamWriter sw = new StreamWriter(path);

            CopyleaksCloud   copyleaks = new CopyleaksCloud(eProduct.Businesses);
            CopyleaksProcess createdProcess;
            ProcessOptions   scanOptions = new ProcessOptions();

            scanOptions.SandboxMode = true; // Sandbox mode --> Read more https://api.copyleaks.com/documentation/headers/sandbox
            ResultRecord[] results;
            try
            {
                #region Login to Copyleaks cloud

                //Console.Write("Login to Copyleaks cloud...");
                copyleaks.Login(email, apiKey);
                //Console.WriteLine("Done!");

                #endregion

                #region Checking account balance

                //Console.Write("Checking account balance...");
                uint creditsBalance = copyleaks.Credits;
                //Console.WriteLine("Done ({0} credits)!", creditsBalance);
                if (!scanOptions.SandboxMode && creditsBalance == 0)
                {
                    MessageBox.Show("ERROR: You do not have enough credits to complete this scan. Your balance is {0}).", Convert.ToString(creditsBalance));

                    Environment.Exit(2);
                }

                #endregion

                #region callbacks

                // add a URL address to get notified using callbacks once the scan results are ready.
                //Read more https://api.copyleaks.com/documentation/headers/http-callback
                //scanOptions.HttpCallback = new Uri("http://callbackurl.com?pid={PID}");
                //scanOptions.InProgressResultsCallback = new Uri("http://callbackurl.com?pid={PID}");

                #endregion

                #region Submitting a new scan process to the server

                // Insert here the URL that you'd like to scan for plagiarism
                createdProcess = copyleaks.CreateByUrl(new Uri("http://cnn.com/"), scanOptions);

                // Insert here the file that you'd like to scan for plagiarism
                Addfac add = new Addfac();
                createdProcess = copyleaks.CreateByFile(new FileInfo(add.ansreturn()), scanOptions);


                //Console.WriteLine("Done (PID={0})!", createdProcess.PID);

                #endregion

                #region Waiting for server's process completion

                // Use this if you are not using callback
                sw.WriteLine("Scanning... ");
                ushort currentProgress;
                while (!createdProcess.IsCompleted(out currentProgress))
                {
                    sw.WriteLine(currentProgress + "%");
                    Thread.Sleep(5000);
                }
                sw.WriteLine("Done.");

                #endregion

                #region Processing finished. Getting results

                results = createdProcess.GetResults();
                if (results.Length == 0)
                {
                    sw.WriteLine("No results.");
                }
                else
                {
                    for (int i = 0; i < results.Length; ++i)
                    {
                        if (results[i].URL != null)
                        {
                            sw.WriteLine("Url: {0}", results[i].URL);
                        }
                        sw.WriteLine("Information: {0} copied words ({1}%)", results[i].NumberOfCopiedWords, results[i].Percents);
                        sw.WriteLine("Comparison report: {0}", results[i].ComparisonReport);
                        //Console.WriteLine("Title: {0}", results[i].Title);
                        //Console.WriteLine("Introduction: {0}", results[i].Introduction);
                        ////Console.WriteLine("Embeded comparison: {0}", results[i].EmbededComparison);
                        //Console.ReadKey();
                    }
                }

                #endregion
            }
            catch (UnauthorizedAccessException)
            {
                sw.WriteLine("Failed!");
                sw.WriteLine("Authentication with the server failed!");
                sw.WriteLine("Possible reasons:");
                sw.WriteLine("* You did not log in to Copyleaks cloud");
                sw.WriteLine("* Your login token has expired");
                Console.ReadKey();
            }
            catch (CommandFailedException theError)
            {
                sw.WriteLine("Failed!");
                sw.WriteLine("*** Error {0}:", theError.CopyleaksErrorCode);
                sw.WriteLine("{0}", theError.Message);
                Console.ReadKey();
            }

            sw.Close();
        }
Example #36
0
            public static void AddToQueue(SimDescription sim, ProcessOptions options)
            {
                bool found = false;
                foreach (QueueItem item in sQueue)
                {
                    if (item.mSim == sim)
                    {
                        item.mOptions |= options;
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    sQueue.Enqueue(new QueueItem (sim, options));
                }

                ProcessQueue();
            }
Example #37
0
        static void Main(string[] args)
        {
            // Usage:
            // SampleCode.exe -e "<YOUR_EMAIL>" -k "Your Account Key" --url "http://site.com/your-webpage"
            // OR
            // SampleCode.exe -e "<YOUR_EMAIL>" -k "Your Account Key" --local-document "C:\your-directory\document.doc"

            CommandLineOptions options = new CommandLineOptions();

            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                Environment.Exit(1);
            }
            else if ((options.URL == null && options.LocalFile == null) || (options.URL != null && options.LocalFile != null))
            {
                Console.WriteLine("Error: You can speicfy either a URL or a local document to scan. For more information please enter '--help'.");
                Environment.Exit(1);
            }

            Uri httpCallback = null;

            if (options.HttpCallback != null)
            {
                // Http callback example value:
                // https://your-website.com/copyleaks-gateway?id={PID}
                // Copyleaks server will replace the "{PID}" token with the actual process id.
                if (!Uri.TryCreate(options.HttpCallback, UriKind.Absolute, out httpCallback))
                {
                    Console.WriteLine("ERROR: Bad Http-Callback.");
                    Environment.Exit(3);
                }
            }

            // For more information, visit Copyleaks "How-To page": https://api.copyleaks.com/Guides/HowToUse
            // Creating Copyleaks account: https://copyleaks.com/Account/Register
            // Use your Copyleaks account information.
            // Generate your Account API Key: https://api.copyleaks.com/Home/Dashboard

            // Copyleaks api supports two products: Publishers and Academic.
            // Select the product the suitible for you.
            CopyleaksCloud   copyleaks = new CopyleaksCloud(eProduct.Businesses);
            CopyleaksProcess createdProcess;

            ResultRecord[] results;
            ProcessOptions scanOptions = new ProcessOptions();

            scanOptions.HttpCallback = httpCallback;

            // In Sandbox scan you don't need credits.
            // Read more @ https://api.copyleaks.com/Documentation/RequestHeaders#sandbox-mode
            // After you finish the integration with Copyleaks, remove this line.
            scanOptions.SandboxMode = true;

            try
            {
                #region Login to Copyleaks cloud

                Console.Write("Login to Copyleaks cloud...");
                copyleaks.Login(options.Email, options.ApiKey);
                Console.WriteLine("Done!");

                #endregion

                #region Checking account balance

                Console.Write("Checking account balance...");
                uint creditsBalance = copyleaks.Credits;
                Console.WriteLine("Done ({0} credits)!", creditsBalance);
                if (creditsBalance == 0)
                {
                    Console.WriteLine("ERROR: You do not have enough credits to complete this scan. Your current credit balance is {0}).", creditsBalance);
                    Environment.Exit(2);
                }

                #endregion

                #region Submitting a new scan process to the server

                Console.Write("Creating process...");
                if (options.URL != null)
                {
                    Uri uri;
                    if (!Uri.TryCreate(options.URL, UriKind.Absolute, out uri))
                    {
                        Console.WriteLine("ERROR: The URL ('{0}') is invalid.", options.URL);                         // Bad URL format.
                        Environment.Exit(1);
                    }

                    createdProcess = copyleaks.CreateByUrl(uri, scanOptions);
                }
                else
                {
                    if (!File.Exists(options.LocalFile))
                    {
                        Console.WriteLine("ERROR: The file '{0}' does not exist.", options.LocalFile);                         // Bad URL format.
                        Environment.Exit(1);
                    }

                    createdProcess = copyleaks.CreateByFile(new FileInfo(options.LocalFile), scanOptions);
                }
                Console.WriteLine("Done (PID={0})!", createdProcess.PID);

                #endregion

                #region Waiting for server's process completion

                // Note: We are strongly recommending to use "callbacks" instead of "busy-polling". Use HTTP-callbacks whenever it's possible.
                // Read more @ https://api.copyleaks.com/GeneralDocumentation/RequestHeaders#http-callbacks
                Console.Write("Scanning... ");
                using (var progress = new ProgressBar())
                {
                    ushort currentProgress;
                    while (!createdProcess.IsCompleted(out currentProgress))
                    {
                        progress.Report(currentProgress / 100d);
                        Thread.Sleep(5000);
                    }
                }
                Console.WriteLine("Done.");

                #endregion

                #region Processing finished. Getting results

                results = createdProcess.GetResults();

                if (results.Length == 0)
                {
                    Console.WriteLine("No results.");
                }
                else
                {
                    for (int i = 0; i < results.Length; ++i)
                    {
                        Console.WriteLine();
                        Console.WriteLine("Result {0}:", i + 1);
                        Console.WriteLine("Url: {0}", results[i].URL);
                        Console.WriteLine("Percents: {0}", results[i].Percents);
                        Console.WriteLine("CopiedWords: {0}", results[i].NumberOfCopiedWords);
                    }
                }

                #endregion
            }
            catch (UnauthorizedAccessException)
            {
                Console.WriteLine("Failed!");
                Console.WriteLine("Authentication with the server failed!");
                Console.WriteLine("Possible reasons:");
                Console.WriteLine("* You did not log in to Copyleaks cloud");
                Console.WriteLine("* Your login token has expired");
                Environment.Exit(1);
            }
            catch (CommandFailedException theError)
            {
                Console.WriteLine("Failed!");
                Console.WriteLine("*** Error {0}:", theError.CopyleaksErrorCode);
                Console.WriteLine("{0}", theError.Message);
                Environment.Exit(1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed!");
                Console.WriteLine("Unhandled Exception");
                Console.WriteLine(ex);
                Environment.Exit(1);
            }

            Environment.Exit(0);             // SUCCESS
        }
Example #38
0
 protected CheckOutfitTask(SimDescription sim, ProcessOptions options)
 {
     mSim = sim;
     mOptions = options;
 }
 protected override void AddOptions(ProcessOptions options)
 {
     options.Add("--name", Settings.Name);
     options.Add("--settings", PathUtils.GetRelativePath(WorkingDirectory, Settings.SettingsFile));
 }
 public SimulationOptions(PersistedSimulation persistedSimulation, ProcessOptions processOptions)
 {
     _persistedSimulation = persistedSimulation;
     ProcessOptions       = processOptions;
 }
Example #41
0
        /// <summary>
        /// Submitting URL to plagiarism scan
        /// </summary>
        /// <param name="url">The url containing the content to scan</param>
        /// <param name="options">Process Options: include http callback and add custom fields to the process</param>
        /// <exception cref="UnauthorizedAccessException">The login-token is undefined or expired</exception>
        /// <exception cref="ArgumentOutOfRangeException">The input URL scheme is different than HTTP or HTTPS</exception>
        /// <returns>The newly created process</returns>
        public CopyleaksProcess CreateByUrl(Uri url, ProcessOptions options = null)
        {
            if (this.Token == null)
            {
                throw new UnauthorizedAccessException("Empty token!");
            }
            else
            {
                this.Token.Validate();
            }

            if (url.Scheme != "http" && url.Scheme != "https")
            {
                throw new ArgumentOutOfRangeException(nameof(url), "Allowed protocols: HTTP, HTTPS");
            }

            using (HttpClient client = new HttpClient())
            {
                client.SetCopyleaksClient(HttpContentTypes.Json, this.Token);

                CreateCommandRequest req = new CreateCommandRequest()
                {
                    URL = url.AbsoluteUri
                };

                HttpResponseMessage msg;
                // Submitting the URL
                HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(req),
                    Encoding.UTF8,
                    HttpContentTypes.Json);

                if (options != null)
                {
                    options.AddHeaders(client);
                }

                msg = client.PostAsync(string.Format("{0}/{1}/{2}", Resources.ServiceVersion, this.Product.ToName(), "create-by-url"), content).Result;

                if (!msg.IsSuccessStatusCode)
                {
                    throw new CommandFailedException(msg);
                }

                string json = msg.Content.ReadAsStringAsync().Result;

                CreateResourceResponse response;
                try
                {
                    var dateTimeConverter = new IsoDateTimeConverter {
                        DateTimeFormat = "dd/MM/yyyy HH:mm:ss"
                    };
                    response = JsonConvert.DeserializeObject <CreateResourceResponse>(json, dateTimeConverter);
                }
                catch (Exception e)
                {
                    throw new Exception("JSON=" + json, e);
                }
                if (options == null)
                {
                    return(new CopyleaksProcess(this.Token, this.Product, response, null));
                }
                else
                {
                    return(new CopyleaksProcess(this.Token, this.Product, response, options.CustomFields));
                }
            }
        }