예제 #1
0
        public override ProcessResult Process()
        {
            ProcessResult res = new ProcessResult();

            try
            {
                Process p = System.Diagnostics.Process.GetProcessById(processID);
                if (p != null)
                {
                    p.Kill();
                    res.ErrorCode = 0;
                    return res;
                }
                else
                {
                    res.ErrorCode = 6;
                    res.ErrorDetails = "Nie ma takiego procesu";
                    return res;
                }
            }
            catch (Exception exc)
            {
                res.ErrorCode = 5;
                res.ErrorDetails = exc.ToString();
            }
            return res;
        }
        public ProcessResult<List<SolicitudVentaDomain>> BuscarSolicitudVenta(int numerosolicitud)
        {
            ProcessResult<List<SolicitudVentaDomain>> list = new ProcessResult<List<SolicitudVentaDomain>>();
            List<SolicitudVentaDomain> listResult = new List<SolicitudVentaDomain>();
            try
            {
                List<SolicitudVentaLogic> solicitudVenta = EmpleadoLogicRepository.BuscarSolicitudVenta(numerosolicitud);

                foreach (var item in solicitudVenta)
                {
                    SolicitudVentaDomain svd = new SolicitudVentaDomain();

                    svd.productoId = item.productoId;
                    svd.descripcionProducto = item.descripcionProducto;
                    svd.presentacionProducto = item.presentacionProducto;
                    svd.cantidadProducto = item.cantidadProducto;
                    svd.descuento = item.descuento;
                    svd.precioProducto = item.precioProducto;
                    svd.subtotal = item.subtotal;

                    listResult.Add(svd);
                }

                list.Result = listResult;

            }
            catch (Exception e)
            {
                list.IsSuccess = true;
                list.Exception = new ApplicationLayerException<SolicitudPermisoService>("Ocurrio un problema en el sistema", e);
            }
            return list;
        }
예제 #3
0
 static void VerifyProcessRan(this Process command, ProcessResult result)
 {
     if (!result.Success)
         throw new ProcessRunnerException(
             string.Format("Failed to execute process \"{0}\". Process status was {1}.",
                 command.Options.CommandLine, result.Status));
 }
        override public ProcessResult Process(ProcessResult lastSiblingResult, TriggerObject trigObject)
        {
            trigObject.CurrentNodeExecutionChain.Add(this);

            ProcessResult result = UserDefinedFunction.Execute(trigObject);

            trigObject.CurrentNodeExecutionChain.Remove(this);
            return result;
        }
        public override ProcessResult Process(string ip, InstructionTask instructionTask)
        {
            ProcessResult result = new ProcessResult();

            result.Done = false;
            result.Message = "设置检测仪IP地址失败!";

            return result;
        }
예제 #6
0
 /// <summary>
 /// Logs the result of a finished process.
 /// </summary>
 public static void LogProcessResult(ProcessResult result)
 {
     var outcome = result.Failed ? "failed" : "succeeded";
     Console.WriteLine($"The process \"{result.ExecutablePath} {result.Args}\" {outcome} with code {result.Code}.");
     Console.WriteLine($"Standard Out:");
     Console.WriteLine(result.StdOut);
     Console.WriteLine($"Standard Error:");
     Console.WriteLine(result.StdErr);
 }
        public override ProcessResult Process(string ip, InstructionTask instructionTask)
        {
            ProcessResult result = new ProcessResult();

            result.Done = true;
            result.Message = "设置检测仪探头阀值下限成功!";

            return result;
        }
        public override ProcessResult Process(string ip, InstructionTask instructionTask)
        {
            ProcessResult result = new ProcessResult();

            result.Done = false;
            result.Message = string.Empty;

            return result;
        }
예제 #9
0
        public override ProcessResult Process(ProcessResult lastSiblingResult, TriggerObject trigObject)
        {
            if (InfiniteLoopRisk == true)
                throw new UberScriptException("Line " + LineNumber + ": " + base.ScriptString + "\nAttempted to execute ForLoop with InfiniteLoop risk!  Skipping for loop!");

            int maxLoopNumber = 10000;
            int loopCount = 0;

            // first try to execute the initial statement
            if (InitialStatement != null)
            {
                InitialStatement.Process(ProcessResult.None, trigObject);
            }

            Object result = ConditionalMathTree.Calculate(trigObject);
            while (result is bool && (bool)result)
            {
                //execute the child code
                ProcessResult lastResult = ProcessChildren(trigObject);
                if (lastResult == ProcessResult.Break) // exit out of this for loop
                    return ProcessResult.None;
                if (lastResult == ProcessResult.Return || lastResult == ProcessResult.ReturnOverride)
                {
                    return lastResult;
                }
                // ProcessResult.Continue--just keep going

                //execute the next part of the loop (often ints.i++)
                try
                {
                    RepeatedStatement.Process(ProcessResult.None, trigObject);
                }
                catch (Exception e)
                {
                    throw new UberScriptException("Line " + LineNumber + ": " + base.ScriptString + "\nForLoop Repeated Statement execution error: ", e);
                }
                try
                {
                    // see whether we still meet our condition
                    result = ConditionalMathTree.Calculate(trigObject);
                }
                catch (Exception e)
                {
                    throw new UberScriptException("Line " + LineNumber + ": " + base.ScriptString + "\nForLoop Conditional Statement execution error: ", e);
                }
                
                loopCount++;
                if (loopCount > maxLoopNumber)
                {
                    InfiniteLoopRisk = true;
                    throw new UberScriptException("Attempted to execute ForLoop with InfiniteLoop risk!  Skipping for loop!");
                }
            }

            return ProcessResult.None;
        }
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            var apm = new ProcessResult(cb, context, extraData);

            context.Response.Write(string.Format("<h1>This handler uses a simple custom implementation of the IAsyncResult interface (Async Programming Model)</h1><br/><br/><hr/><br/><br/>"));

            context.Response.Write(string.Format("<br/>Before calling start asynchronously: {0} ThreadPool ID: {1}", DateTime.Now.ToString(), Thread.CurrentThread.ManagedThreadId));
            apm.Start();
            context.Response.Write(string.Format("<br/>After calling start asynchronously: {0} ThreadPool ID: {1}", DateTime.Now.ToString(), Thread.CurrentThread.ManagedThreadId));

            return apm;
        }
예제 #11
0
 public void SetUp()
 {
     _mocks = new MockRepository(MockBehavior.Strict);
     _viewFactoryMock = _mocks.Create<IViewFactory>();
     _viewMock = _mocks.Create<IView<ProcessResult>>();
     _renderedResult = null;
     _viewMock.Setup(it => it.Render(It.IsNotNull<ProcessResult>()))
         .Callback<ProcessResult>(
             result => { _renderedResult = result; }
         );
     _viewFactoryMock.Setup(it => it.CreateView<ProcessResult>("text")).Returns(_viewMock.Object);
 }
예제 #12
0
        static void VerifyExitCode(this Process command, ProcessResult result, ResultExpectation resultExpectation, ILogger logger)
        {
            if (result.ExitCode == SuccessExitCode)
                return;

            string message = string.Format("Process \"{0}\" failed, exit code {1}. All output: {2}",
                command.Options.CommandLine, result.ExitCode, result.AllOutput);

            if (resultExpectation == ResultExpectation.MustNotFail)
                throw new Exception(message);

            logger.LogWarning(message);
        }
예제 #13
0
        public IAsyncResult BeginProcessRequest(object sender, EventArgs e, AsyncCallback cb, object extraData)
        {
            HttpContext.Current.Response.Write(string.Format("<br /> Thread ID: {0} From: {1}", Thread.CurrentThread.ManagedThreadId, MethodInfo.GetCurrentMethod().Name));
            //Func<TimeSpan, DateTime> operation = this.ExecuteLongTimeConsumingOperation;

            //return operation.BeginInvoke(TimeSpan.FromDays(10), cb, extraData);

            var f = new ProcessResult(cb, this.Context, extraData);

            f.Start();

            return f;
        }
예제 #14
0
파일: Native.cs 프로젝트: Pastor/videotools
 public static string ToString(ProcessResult result)
 {
     switch (result) {
         case ProcessResult.EmptyImage:
             return @"Ошибочное изображение";
         case ProcessResult.NotDetected:
             return @"Не определено лицо";
         case ProcessResult.Success:
             return @"Удачно";
         default:
             return @"Ошибка обработки";
     }
 }
 public override ProcessResult Process()
 {
     ProcessResult result = new ProcessResult();
     try
     {
         activeProcesses = System.Diagnostics.Process.GetProcesses();
     }
     catch (Exception exc)
     {
         result.ErrorCode = 5;
         result.ErrorDetails = exc.ToString();
     }
     return result;
 }
예제 #16
0
 public override ProcessResult Process()
 {
     ProcessResult res = new ProcessResult();
     try
     {
         System.Diagnostics.Process.Start(FilePath);
         res.ErrorCode = 0;
     }
     catch (Exception exc)
     {
         res.ErrorCode = 5;
         res.ErrorDetails = exc.ToString();
     }
     return res;
 }
예제 #17
0
파일: Logger.cs 프로젝트: 13xforever/DeDRM
 internal static void PrintResult(ProcessResult status)
 {
     string result = status.ToString();
     ConsoleColor? color = null;
     switch (status)
     {
         case ProcessResult.Skipped:
             break;
         case ProcessResult.Success:
             color = ConsoleColor.Green;
             break;
         case ProcessResult.Fail:
             color = ConsoleColor.Red;
             break;
         default:
             color = ConsoleColor.Yellow;
             break;
     }
     PrintResult(result, 60, color);
 }
예제 #18
0
        public ProcessResult<EmpleadoDomain> BuscarEmpleadoPorId(int Id)
        {
            ProcessResult<EmpleadoDomain> result = new ProcessResult<EmpleadoDomain>();
            try
            {
                Id = 1;
                EmpleadoLogic empleado = EmpleadoLogicRepository.FindById(Id);

                /*EmpleadoDomain empleado = new EmpleadoDomain();
                empleado.Id = 1;
                empleado.Nombre = "Cesar Kina";
                empleado.TipoEmpleado = 2;

                result.Result = empleado;*/
            }
            catch (Exception e)
            {
                result.IsSuccess = true;
                result.Exception = new ApplicationLayerException<SolicitudPermisoService>("Ocurrio un problema en el sistema", e);
            }

            return result;
        }
예제 #19
0
        public override ProcessResult Process()
        {
            ProcessResult res = new ProcessResult();
            res.ErrorCode = 0;
            Bitmap bmp = null;
            Graphics graph = null;
            FtpClient ftpClient = null;
            try
            {
                bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
                graph = Graphics.FromImage(bmp);
                graph.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
                FileName = string.Format("zrzut_{0}-{1}-{2}_{3}.jpg", DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString(), DateTime.Now.Ticks.ToString());
                bmp.Save(FileName, ImageFormat.Jpeg);
                     ftpClient = new FtpClient(FTPSettings.ServerAddress, FTPSettings.User, FTPSettings.Password);
                     ftpClient.ChangeDir(FTPSettings.Directory);
                ftpClient.Upload(FileName);
                System.IO.File.Delete(FileName);

            }
            catch (Exception exc)
            {
                res.ErrorCode = 5;
                res.ErrorDetails = exc.ToString();
            }
            finally
            {
                if (ftpClient != null)
                ftpClient.Close();
                if (graph != null)
                graph.Dispose();
                if (bmp != null)
                bmp.Dispose();
            }
            return res;
        }
예제 #20
0
        public override ProcessResult Process(ProcessResult lastSiblingResult, TriggerObject trigObject)
        {
            ProcessResult lastResult = ProcessResult.None;
            // NOTE: I commented out the try here because
            if (trigObject.PausedNodeChain != null)
            {
                if (trigObject.PausedNodeChain.Count == 1 && trigObject.PausedNodeChain.Peek() == this)
                {
                    trigObject.PausedNodeChain = null;
                }
                else
                {
                    // it was paused inside of the spawnentry statement, so just keep going
                    return ProcessChildren(trigObject);
                }
            }

            lastResult = ProcessChildren(trigObject);
            if (lastResult == ProcessResult.Return || lastResult == ProcessResult.ReturnOverride || lastResult == ProcessResult.Break || lastResult == ProcessResult.Continue)
            {
                return lastResult;
            }
            return ProcessResult.None;
        }
 static ProcessResult()
 {
     Ok = new ProcessResult(true);
     Fail = new ProcessResult(false);
 }
예제 #22
0
 /// <summary>
 ///		Stops this process executing until the given process completed with the correct result.
 /// </summary>
 /// <param name="process">Process to wait for.</param>
 /// <param name="result">Result to wait for.</param>
 public virtual void WaitForProcess(Process process, ProcessResult result)
 {
     _waitingForProcess = true;
     _waitForProcess = process;
     _waitForResult = result;
 }
예제 #23
0
 /// <summary>
 ///		Cancels a process wait caused by called WaitForProcess.
 /// </summary>
 public virtual void CancelProcessWait()
 {
     _waitingForProcess = false;
     _waitForResult = 0;
     _waitForProcess = null;
 }
예제 #24
0
 /// <summary>
 ///		Finishes execution of this process permenently, and returns the given result
 ///		to the process manager.
 /// </summary>
 /// <param name="result">Result of process execution.</param>
 public virtual void Finish(ProcessResult result)
 {
     _isFinished = true;
     _finishResult = result;
 }
 /// <summary>
 /// Handles the response.
 /// </summary>
 /// <param name="filterContext">The filter context.</param>
 /// <param name="result">The result.</param>
 /// <returns></returns>
 protected virtual ActionResult HandleResponse(ActionExecutingContext filterContext, ProcessResult result) {
     return Helper.HandleResponse(result, _beetleConfig);
 }
        public override ProcessResult Process(string ip, InstructionTask instructionTask)
        {
            ProcessResult result = null;

            if (Variable.Debug)
            {
                result = new ProcessResult();

                Random random = new Random();
                int randomValue = random.Next(0, 2);
                if (randomValue == 0)
                {
                    result.Done = false;
                }
                else
                {
                    result.Done = true;
                }
            }

            return result;
        }
예제 #27
0
        /// <summary>
        /// Invokes nuget.exe with the appropriate parameters.
        /// </summary>
        /// <param name="arguments">cmd line args to NuGet.exe</param>
        /// <param name="workingDir">working dir if any to be used</param>
        /// <param name="timeout">Timeout in seconds (default = 6min).</param>
        /// <returns></returns>
        public async Task<ProcessResult> InvokeNugetProcess(string arguments, string workingDir = null, int timeout = 360)
        {
            var nugetProcess = new Process();
            var pathToNugetExe = Path.Combine(Environment.CurrentDirectory, NugetExePath);

            WriteLine("The NuGet.exe command to be executed is: " + pathToNugetExe + " " + arguments);

            // During the actual test run, a script will copy the latest NuGet.exe and overwrite the existing one
            ProcessStartInfo nugetProcessStartInfo = new ProcessStartInfo(pathToNugetExe);
            nugetProcessStartInfo.Arguments = arguments;
            nugetProcessStartInfo.RedirectStandardError = true;
            nugetProcessStartInfo.RedirectStandardOutput = true;
            nugetProcessStartInfo.RedirectStandardInput = true;
            nugetProcessStartInfo.UseShellExecute = false;
            nugetProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            nugetProcessStartInfo.CreateNoWindow = true;
            nugetProcess.StartInfo = nugetProcessStartInfo;

            if (workingDir != null)
            {
                nugetProcess.StartInfo.WorkingDirectory = workingDir;
            }

            nugetProcess.Start();

            var standardError = await nugetProcess.StandardError.ReadToEndAsync();
            var standardOutput = await nugetProcess.StandardOutput.ReadToEndAsync();


            WriteLine(standardOutput);

            if (!string.IsNullOrEmpty(standardError))
            {
                WriteLine(standardError);
            }

            nugetProcess.WaitForExit(timeout * 1000);

            var processResult = new ProcessResult(nugetProcess.ExitCode, standardError);
            return processResult;
        }
예제 #28
0
파일: MockVimBuffer.cs 프로젝트: 0-F/VsVim
 public void RaiseKeyInputProcessed(KeyInput ki, ProcessResult result)
 {
     if (KeyInputProcessed != null)
     {
         KeyInputProcessed(this, new KeyInputProcessedEventArgs(ki, result));
     }
 }
예제 #29
0
        public static ProcessResult TryExecuteProcessSync(string command, string arguments = "", int timeout = DefaultTimeout)
        {
            var result = new ProcessResult();

            using (var process = new Process())
            {
                // При запуске на Linux bash-скриптов, возможен код ошибки 255.
                // Решением является добавление заголовка #!/bin/bash в начало скрипта.

                process.StartInfo.FileName               = command;
                process.StartInfo.Arguments              = arguments;
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardInput  = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.CreateNoWindow         = true;

                var outputBuilder = new StringBuilder();
                var errorBuilder  = new StringBuilder();

                using (var outputCloseEvent = new AutoResetEvent(false))
                    using (var errorCloseEvent = new AutoResetEvent(false))
                    {
                        // Подписка на события записи в выходные потоки процесса

                        var copyOutputCloseEvent = outputCloseEvent;

                        process.OutputDataReceived += (s, e) =>
                        {
                            // Поток output закрылся (процесс завершил работу)
                            if (string.IsNullOrEmpty(e.Data))
                            {
                                copyOutputCloseEvent.Set();
                            }
                            else
                            {
                                outputBuilder.AppendLine(e.Data);
                            }
                        };

                        var copyErrorCloseEvent = errorCloseEvent;

                        process.ErrorDataReceived += (s, e) =>
                        {
                            // Поток error закрылся (процесс завершил работу)
                            if (string.IsNullOrEmpty(e.Data))
                            {
                                copyErrorCloseEvent.Set();
                            }
                            else
                            {
                                errorBuilder.AppendLine(e.Data);
                            }
                        };

                        bool isStarted;

                        try
                        {
                            isStarted = process.Start();
                        }
                        catch (Exception error)
                        {
                            // Не удалось запустить процесс, скорей всего, файл не существует или не является исполняемым

                            result.Completed = true;
                            result.ExitCode  = -1;
                            result.Output    = string.Format(Properties.Resources.CannotExecuteCommand, command, arguments, error.Message);

                            isStarted = false;
                        }

                        if (isStarted)
                        {
                            // Начало чтения выходных потоков процесса в асинхронном режиме, чтобы не создать блокировку
                            process.BeginOutputReadLine();
                            process.BeginErrorReadLine();

                            // Ожидание завершения процесса и закрытия выходных потоков
                            if (process.WaitForExit(timeout) &&
                                outputCloseEvent.WaitOne(timeout) &&
                                errorCloseEvent.WaitOne(timeout))
                            {
                                result.Completed = true;
                                result.ExitCode  = process.ExitCode;

                                // Вывод актуален только при наличии ошибки
                                if (process.ExitCode != 0)
                                {
                                    result.Output = $"{outputBuilder}{errorBuilder}";
                                }
                            }
                            else
                            {
                                try
                                {
                                    // Зависшие процессы завершаются принудительно
                                    process.Kill();
                                }
                                catch
                                {
                                    // Любые ошибки в данном случае игнорируются
                                }
                            }
                        }
                    }
            }

            return(result);
        }
예제 #30
0
파일: MockVimBuffer.cs 프로젝트: sehe/VsVim
 public void RaiseKeyInputProcessed(KeyInput ki, ProcessResult result)
 {
     if (KeyInputProcessed != null)
     {
         KeyInputProcessed(this, Tuple.Create(ki, result));
     }
 }
예제 #31
0
        public Object SpawnAndReturnObject(ProcessResult lastSiblingResult, TriggerObject trigObject)
        {
            // IF YOU EDIT THIS FUNCTION, BE SURE TO MAKE THE CORRESPONDING CHANGE TO THE Process FUNCTION!
            // this is just like Process, except it returns the spawned object (useful only in StatementNodes such that the object
            // can be assigned to the lefthand side of the statement node
            // e.g.
            // objs.test = orc
            // {
            //    name = goober
            // }
            Object prevSpawnedObject = trigObject.Spawn;
            Object callingObj = trigObject.Spawn != null ? trigObject.Spawn : trigObject.This;
            if (this.ScriptString != null)
            {
                // it's a spawn node, so we need to spawn an object here
                trigObject.Spawn = SpawnHandlers.Spawn(ScriptString, callingObj);
            }
            if (this.Children.Count > 0) // there is a special script associated with the spawn
            {
                ProcessChildren(trigObject); // ignore any overrides within spawn definitions
                IEntity spawnedObject = trigObject.Spawn as IEntity;
                if (spawnedObject != null && this.TriggerNodes.Count > 0)
                {
                    XmlScript script = new XmlScript(UberTreeParser.CurrentFileBeingParsed);
                    AddRootNodeIndeces(this, script.RootNodeIndeces);
                    XmlAttach.AttachTo(spawnedObject, script);
                }
            }
            // if it was already given a location in it's children, then don't give it one... otherwise place it
            // on the caller
            Item callerItem = null;
            Mobile callerMob = null;
            if (callingObj is Item) { callerItem = callingObj as Item; }
            else if (callingObj is Mobile) { callerMob = callingObj as Mobile; }
            
            Object o = trigObject.Spawn;
            Mobile m = null;
            Item item = null;
            if (o is Mobile) { m = (Mobile)o; }
            else if (o is Item) { item = (Item)o; }

            if ((m != null && m.Location == Point3D.Zero && m.Map == Map.Internal) || (item != null && item.Location == Point3D.Zero && item.Map == Map.Internal && item.RootParentEntity == null))
            {
                try
                {
                    if (m != null)
                    {
                        if (callerItem != null)
                        {
                            if (callerItem.RootParentEntity != null)
                            {
                                m.MoveToWorld(callerItem.RootParentEntity.Location, callerItem.RootParentEntity.Map);
                            }
                            else
                            {
                                m.MoveToWorld(callerItem.Location, callerItem.Map);
                            }
                        }
                        else if (callerMob != null) { m.MoveToWorld(callerMob.Location, callerMob.Map); }
                        else if (callingObj is IPoint3D)
                        {
                            m.MoveToWorld(new Point3D((IPoint3D)callingObj), Map.Felucca);
                        }
                        else throw new UberScriptException("Spawn caller (the thing XmlScript is attached to) was neither mobile or item! It was: " + callingObj);
                        //loc = GetSpawnPosition(requiresurface, packrange, packcoord, spawnpositioning, m);                  

                        if (m is BaseCreature)
                        {
                            BaseCreature c = (BaseCreature)m;
                            c.Home = c.Location;
                        }
                        trigObject.Spawn = prevSpawnedObject;
                        return o;
                    }
                    else if (item != null)
                    {
                        if (callerItem != null)
                        {
                            item.MoveToWorld(callerItem.Location, callerItem.Map);
                        }
                        else if (callerMob != null)
                        {
                            item.MoveToWorld(callerMob.Location, callerMob.Map);
                        }
                        else if (callingObj is IPoint3D)
                        {
                            item.MoveToWorld(new Point3D((IPoint3D)callingObj), Map.Felucca);
                        }
                        else throw new UberScriptException("Spawn caller (the thing XmlScript is attached to) was neither mobile or item! It was: " + callingObj);
                        trigObject.Spawn = prevSpawnedObject;
                        return o;
                    }
                }
                catch (Exception ex) { throw new UberScriptException(String.Format("When spawning {0}", o), ex); }
            }
            else if (m != null && m is BaseCreature)
            {
                BaseCreature c = (BaseCreature)m;
                c.Home = c.Location;
            }

            trigObject.Spawn = prevSpawnedObject;
            return o;
        }