Esempio n. 1
2
    protected void Button1_Click(object sender, EventArgs e)
    {
        ReportExecutionService reportExecutionService = new ReportExecutionService();   // Web Service proxy
        reportExecutionService.Credentials = new NetworkCredential("reportservice", "Asdfghjkl?", "kswh107");

        string reportPath = "/ReconCurrent/ReconInvest";
        string format = "PDF";

        // Render arguments
        byte[] result = null;
        string historyID = null;

        string encoding;
        string mimeType;
        string extension;
        Warning[] warnings = null;
        string[] streamIDs = null;

        ParameterValue[] parameters = new ParameterValue[4];
        parameters[0] = new ParameterValue();
        parameters[0].Name = "StartDate";
        parameters[1] = new ParameterValue();
        parameters[1].Name = "EndDate";
        parameters[2] = new ParameterValue();
        parameters[2].Name = "IsinCode";
        parameters[3] = new ParameterValue();
        parameters[3].Name = "AccountNumber";

        ExecutionInfo execInfo = new ExecutionInfo();
        ExecutionHeader execHeader = new ExecutionHeader();

        reportExecutionService.ExecutionHeaderValue = execHeader;

        execInfo = reportExecutionService.LoadReport(reportPath, historyID);

        String SessionId = reportExecutionService.ExecutionHeaderValue.ExecutionID;
        parameters[0].Value = DatePickerBegin.SelectedDate.ToShortDateString();
        parameters[1].Value = DatePickerEnd.SelectedDate.ToShortDateString();
        parameters[3].Value = ddlAccount.SelectedValue.ToString();
        parameters[2].Value = ddlInstrument.SelectedValue.ToString();
        reportExecutionService.SetExecutionParameters(parameters, "nl-nl");
        result = reportExecutionService.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);

        Response.ClearContent();
        Response.AppendHeader("content-length", result.Length.ToString());
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(result);
        Response.End();
        //Response.Flush();
        //Response.Close();
    }
        //TODO: get from config.json. Use same source across all usages
        public ExecutionInfo Start(string tool, string args, int?pause = 2000)
        {
            var currentDir = Directory.GetCurrentDirectory();

            try
            {
                var fileName = Path.GetFileName(tool);
                EnsureCurrentDirectory(tool, fileName);

                var exitInfo = ProcessExtensions.LaunchApp(fileName, args);

                var result = new ExecutionInfo
                {
                    ProcessId     = exitInfo.ProcessId,
                    OutputStrings = exitInfo.Output,
                    ErrorStrings  = exitInfo.Errors.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries),
                    ExitCode      = exitInfo.ExitCode
                };

                if (pause.HasValue && !exitInfo.IsError)
                {
                    Thread.Sleep(pause.Value);
                }

                return(result);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDir);
            }
        }
        public static ExecutionInfo Execute(string program, string commandLine)
        {
            ExecutionInfo e = new ExecutionInfo();

            e.CommandLine = program + " " + commandLine;
            e.Time        = Environment.TickCount;
            e.ErrorLevel  = -1;
            StreamReader outputReader = null;
            StreamReader errorReader  = null;

            try
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo(program, commandLine);
                processStartInfo.ErrorDialog            = false;
                processStartInfo.UseShellExecute        = false;
                processStartInfo.RedirectStandardError  = true;
                processStartInfo.RedirectStandardInput  = false;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.CreateNoWindow         = true;
                processStartInfo.WindowStyle            = ProcessWindowStyle.Normal;

                Process process = new Process();

                process.StartInfo = processStartInfo;
                bool processStarted = process.Start();

                if (processStarted)
                {
                    outputReader = process.StandardOutput;
                    errorReader  = process.StandardError;
                    process.WaitForExit();
                    e.ErrorLevel  = process.ExitCode;
                    e.Output      = outputReader.ReadToEnd();
                    e.ErrorOutput = errorReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                e.ErrorOutput += "Error lanching the {0} = {1}".format(e.CommandLine, ex.ToString());
            }
            finally
            {
                if (outputReader != null)
                {
                    outputReader.Close();
                }
                if (errorReader != null)
                {
                    errorReader.Close();
                }

                if (e.ErrorLevel != 0)
                {
                    e.ErrorOutput = e.Output;
                    e.Output      = "";
                }
            }
            e.Time = Environment.TickCount - e.Time;
            return(e);
        }
Esempio n. 4
0
 public void ResetExecution()
 {
     Snapshot            = null;
     EventInfo           = null;
     CompiledDataSources = null;
     ExecutionInfo.Reset();
 }
        public override bool Execute(ExecutionInfo exInfo = null)
        {
            ElementSet set = Model.Sets.FindOrCreate <ElementSet>(Name);

            set.Set(Elements);
            return(true);
        }
        public void ShouldNotFetchDuplicateTags()
        {
            var specInfo = new SpecInfo
            {
                Tags     = { "foo" },
                Name     = "",
                FileName = "",
                IsFailed = false
            };
            var scenarioInfo = new ScenarioInfo
            {
                Tags     = { "foo" },
                Name     = "",
                IsFailed = false
            };
            var currentScenario = new ExecutionInfo
            {
                CurrentSpec     = specInfo,
                CurrentScenario = scenarioInfo
            };


            var tags = AssertEx.ExecuteProtectedMethod <ScenarioExecutionStartingProcessor>("GetApplicableTags", currentScenario)
                       .ToList();

            Assert.IsNotEmpty(tags);
            Assert.AreEqual(1, tags.Count);
            Assert.Contains("foo", tags);
        }
        public RSExecutionInfo SetExecutionCredentials(RSDataSourceCredentials[] Credentials)
        {
            DataSourceCredentials[] dsCredentials = (DataSourceCredentials[])Converter.Convert(Credentials);
            ExecutionInfo           outval        = rs.SetExecutionCredentials(dsCredentials);

            return((RSExecutionInfo)Converter.Convert(outval));
        }
        public RSExecutionInfo SetExecutionParameters(RSParameterValue[] Parameters, string ParameterLanguage)
        {
            ParameterValue[] paramValues = (ParameterValue[])Converter.Convert(Parameters);
            ExecutionInfo    outval      = rs.SetExecutionParameters(paramValues, ParameterLanguage);

            return((RSExecutionInfo)Converter.Convert(outval));
        }
Esempio n. 9
0
 public override bool Execute(ExecutionInfo exInfo = null)
 {
     BuildUp = Model.Create.BuildUpFamily(Name, exInfo);
     BuildUp.Layers.Clear();
     BuildUp.Layers.Add(new BuildUpLayer(Thickness, Material));
     return(true);
 }
        protected bool ExtractOutputs(IAction action, IGH_DataAccess DA, ExecutionInfo exInfo)
        {
            IList <PropertyInfo> outputs = ActionBase.ExtractOutputParameters(ActionType);

            foreach (PropertyInfo pInfo in outputs)
            {
                object outputData = pInfo.GetValue(action, null);
                if (PreviewLayer != null)
                {
                    if (outputData is ICollection) //TODO: This would currently catch mesh faces and other similar objects...
                    {
                        PreviewLayer.TryRegisterAll((ICollection)outputData);
                    }
                    else
                    {
                        PreviewLayer.TryRegister(outputData);
                    }
                }
                outputData = FormatForOutput(outputData, exInfo);
                if (outputData is IList)
                {
                    DA.SetDataList(pInfo.Name, (IEnumerable)outputData);
                }
                else
                {
                    DA.SetData(pInfo.Name, outputData);
                }
            }
            return(true);
        }
Esempio n. 11
0
        public static Tuple<bool, string> ExecuteCommand(ExecutionInfo ei)
        {
            // Start the child process.
            var p = new Process();

            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.FileName = ei.FileName;
            p.StartInfo.Arguments = ei.Arguments;
            // Hide Window
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.Start();

            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            var output = p.StandardOutput.ReadToEnd();
            var error = p.StandardError.ReadToEnd();
            p.WaitForExit();

            return new Tuple<bool, string>(p.ExitCode == 0, output + error);
        }
Esempio n. 12
0
        public ExecutionResult Execute(string hookType, IHooksStrategy strategy, IList <string> applicableTags,
                                       ExecutionInfo info)
        {
            var methods         = GetHookMethods(hookType, strategy, applicableTags);
            var executionResult = new ExecutionResult
            {
                Success = true
            };

            foreach (var method in methods)
            {
                var methodInfo = _registry.MethodFor(method);
                try
                {
                    var context = _executionInfoMapper.ExecutionContextFrom(info);
                    ExecuteHook(methodInfo, context);
                }
                catch (Exception ex)
                {
                    Logger.Debug($"{hookType} Hook execution failed : {methodInfo.DeclaringType.FullName}.{methodInfo.Name}");
                    var innerException = ex.InnerException ?? ex;
                    executionResult.ExceptionMessage = innerException.Message;
                    executionResult.StackTrace       = innerException.StackTrace;
                    executionResult.Source           = innerException.Source;
                    executionResult.Success          = false;
                }
            }

            return(executionResult);
        }
Esempio n. 13
0
        public void ShouldGetEmptyTagListByDefault()
        {
            var specInfo = SpecInfo.CreateBuilder()
                           .AddTags("foo")
                           .SetName("")
                           .SetFileName("")
                           .SetIsFailed(false)
                           .Build();
            var scenarioInfo = ScenarioInfo.CreateBuilder()
                               .AddTags("bar")
                               .SetName("")
                               .SetIsFailed(false)
                               .Build();
            var currentScenario = ExecutionInfo.CreateBuilder()
                                  .SetCurrentScenario(scenarioInfo)
                                  .SetCurrentSpec(specInfo)
                                  .Build();
            var currentExecutionInfo = ScenarioExecutionStartingRequest.CreateBuilder()
                                       .SetCurrentExecutionInfo(currentScenario)
                                       .Build();
            var message = Message.CreateBuilder()
                          .SetScenarioExecutionStartingRequest(currentExecutionInfo)
                          .SetMessageType(Message.Types.MessageType.ScenarioExecutionStarting)
                          .SetMessageId(0)
                          .Build();
            var tags = AssertEx.ExecuteProtectedMethod <ExecutionEndingProcessor>("GetApplicableTags", message);

            Assert.IsEmpty(tags);
        }
Esempio n. 14
0
 /// <summary>
 /// Store a generated object keyed by the given execution info of its generating action
 /// </summary>
 /// <param name="exInfo"></param>
 /// <param name="unique"></param>
 public void Set(ExecutionInfo exInfo, ModelObject unique)
 {
     if (exInfo != null && exInfo.SourceReference != null)
     {
         IList <IList <ModelObject> > iterations;
         if (SourceMap.ContainsKey(exInfo.SourceReference))
         {
             iterations = SourceMap[exInfo.SourceReference];
         }
         else
         {
             iterations = new List <IList <ModelObject> >();
             SourceMap[exInfo.SourceReference] = iterations;
         }
         while (exInfo.Iteration >= iterations.Count)
         {
             iterations.Add(null);
         }
         IList <ModelObject> iteration = iterations[exInfo.Iteration];
         if (iteration == null)
         {
             iteration = new List <ModelObject>();
             iterations[exInfo.Iteration] = iteration;
         }
         if (exInfo.HistoryItemCount < iteration.Count)
         {
             iteration[exInfo.HistoryItemCount] = unique;
         }
         else
         {
             iteration.Add(unique);
         }
         exInfo.HistoryItemCount++;
     }
 }
Esempio n. 15
0
        //private rs2005.ReportingService2005 rs;

        public ReporteSSRS(ConexionAFuenteDatos Conexion, Parametros Param)
        {
            _SrvrName             = Conexion.ServerAddress;
            _DbName               = Conexion.Intercompany;
            _IdUsuario            = Conexion.Usuario;
            _Password             = Conexion.Password;
            _IntegratedSecurity   = Conexion.IntegratedSecurity;
            _rutaYReporteSSRS     = Param.rutaReporteSSRS;
            _listaDefParamReporte = Param.ListaParametrosRepSSRS;
            _param = Param;

            try
            {
                _rsExec             = new ReportExecutionService();              // Create a new proxy to the web service
                _rsExec.Credentials = CredentialCache.DefaultCredentials;        // Authenticate to the Web service using Windows credentials
                if (Param.reporteador.Equals("SSRS"))
                {
                    _rsExec.Url = Param.SSRSServer + "/ReportExecution2005.asmx";    // Assign the URL of the Web service
                    _ei         = _rsExec.LoadReport(_rutaYReporteSSRS, _historyID); // Load the selected report.
                }
            }
            catch (Exception Rp)
            {
                ultimoMensaje = "Error al inicializar el reporte [ReporteSSRS]" + Rp.Message;
                numError++;
            }
        }
Esempio n. 16
0
        public void ShouldNotGetDuplicateTags()
        {
            var specInfo = SpecInfo.CreateBuilder()
                           .AddTags("foo")
                           .SetName("")
                           .SetFileName("")
                           .SetIsFailed(false)
                           .Build();
            var scenarioInfo = ScenarioInfo.CreateBuilder()
                               .AddTags("foo")
                               .SetName("")
                               .SetIsFailed(false)
                               .Build();
            var currentScenario = ExecutionInfo.CreateBuilder()
                                  .SetCurrentScenario(scenarioInfo)
                                  .SetCurrentSpec(specInfo)
                                  .Build();
            var currentExecutionInfo = ScenarioExecutionEndingRequest.CreateBuilder()
                                       .SetCurrentExecutionInfo(currentScenario)
                                       .Build();
            var message = Message.CreateBuilder()
                          .SetScenarioExecutionEndingRequest(currentExecutionInfo)
                          .SetMessageType(Message.Types.MessageType.ScenarioExecutionEnding)
                          .SetMessageId(0)
                          .Build();

            var tags = AssertEx.ExecuteProtectedMethod <ScenarioExecutionEndingProcessor>("GetApplicableTags", message).ToList();

            Assert.IsNotEmpty(tags);
            Assert.AreEqual(1, tags.Count);
            Assert.Contains("foo", tags);
        }
Esempio n. 17
0
        public void TriggerQueueView_History_IsHistoryExpanded_True()
        {
            var resourceId = Guid.NewGuid();

            var executionInfo = new ExecutionInfo(DateTime.Now, DateTime.Now - DateTime.UtcNow, DateTime.Today, QueueRunStatus.Success, Guid.NewGuid(), "");

            var history = new List <IExecutionHistory>
            {
                new ExecutionHistory(resourceId, "output", executionInfo, "username")
            };

            var mockServer             = new Mock <IServer>();
            var mockResourceRepository = new Mock <IResourceRepository>();

            mockResourceRepository.Setup(resourceRepository => resourceRepository.GetTriggerQueueHistory(resourceId)).Returns(history);

            mockServer.Setup(server => server.ResourceRepository).Returns(mockResourceRepository.Object);

            var triggerQueueView = new TriggerQueueView(mockServer.Object, new SynchronousAsyncWorker())
            {
                TriggerId         = resourceId,
                ResourceId        = resourceId,
                IsHistoryExpanded = true
            };

            Assert.IsNotNull(triggerQueueView.History);
            Assert.AreEqual(1, triggerQueueView.History.Count);
            Assert.IsFalse(triggerQueueView.IsProgressBarVisible);
            mockResourceRepository.Verify(resourceRepository => resourceRepository.GetTriggerQueueHistory(resourceId), Times.Exactly(1));
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Host.EnsureInitialisation();
            LastExecuted = null;
            if (ActionType != null)
            {
                IAction action = (IAction)Activator.CreateInstance(ActionType, true);
                if (action != null)
                {
                    if (action is IModelDocumentAction && !GrasshopperManager.Instance.AutoBake)
                    {
                        IModelDocumentAction mDAction = (IModelDocumentAction)action;
                        mDAction.Document = GrasshopperManager.Instance.BackgroundDocument(OnPingDocument());
                    }

                    if (ExtractInputs(action, DA))
                    {
                        ExecutionInfo exInfo = new ExecutionInfo(InstanceGuid.ToString(), DA.Iteration);
                        if (action.PreExecutionOperations(exInfo))
                        {
                            if (action.Execute(exInfo))
                            {
                                if (action.PostExecutionOperations(exInfo))
                                {
                                    ExtractOutputs(action, DA, exInfo);
                                    LastExecuted      = action;
                                    LastExecutionInfo = exInfo;
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Crea ed esegue un singolo task
        /// </summary>
        /// <param name="urlServer"></param>
        /// <param name="job2Execute"></param>
        /// <returns></returns>
        private Task <FeedbackInfo> CreateTask(int taskID, string urlServer, JobInfo job2Execute)
        {
            return(Task.Run(() =>
            {
                FeedbackInfo feedback = new FeedbackInfo()
                {
                    TaskID = taskID, Name = job2Execute.Name
                };
                WebClient webClient = CreateHttpClient(urlServer);

                //lista parametri condivisa tra le call (serve per recuperare i parametri da una chiamata e passarli alla successiva)
                Dictionary <string, string> parameters = new Dictionary <string, string>
                {
                    { "##server##", "/api" },
                    { "##sessionID##", taskID.ToString() }
                };

                foreach (string call in job2Execute.Calls)
                {
                    ExecutionInfo result = ExecuteCall(webClient, call, parameters);
                    feedback.Executions.Add(result);
                }
                return feedback;
            }));
        }
Esempio n. 20
0
        /// <summary>
        /// Crea ed esegue un singolo task
        /// </summary>
        /// <param name="url"></param>
        /// <param name="job2Execute"></param>
        /// <returns></returns>
        private Task <FeedbackInfo> CreateTask(string url, JobInfo job2Execute)
        {
            return(Task.Run(async() =>
            {
                FeedbackInfo feedback = new FeedbackInfo()
                {
                    Name = job2Execute.Name
                };
                HttpClient httpClient = CreateHttpClient(url);

                //lista parametri condivisa tra le call (serve per recuperare i parametri da una chiamata e passarli alla successiva)
                Dictionary <string, string> parameters = new Dictionary <string, string>();
                foreach (var call in job2Execute.Calls)
                {
                    ExecutionInfo result = await ExecuteCall(httpClient, call, parameters);
                    feedback.Executions.Add(result);
                }
                return feedback;
            }).ContinueWith(res =>
            {
                return new FeedbackInfo()
                {
                    Name = job2Execute.Name
                };
            }, TaskContinuationOptions.OnlyOnFaulted));
        }
Esempio n. 21
0
        /// <summary>
        /// Returns an enumerator that iterates through the <see cref="TableQuery{TElement}"/>.
        /// </summary>
        /// <returns>An <see cref="IEnumerator{TElement}"/> for the <see cref="TableQuery{TElement}"/>.</returns>
        public virtual IEnumerator <TElement> GetEnumerator()
        {
            if (this.Expression == null)
            {
                TableRequestOptions defaultRequestOptions = TableRequestOptions.ApplyDefaults(null, this.queryProvider.Table.ServiceClient);

                // TODO should we just throw here?
                // Standard Query Mode
                return(this.ExecuteInternal(this.queryProvider.Table.ServiceClient, this.queryProvider.Table, defaultRequestOptions, null /* OperationContext */).GetEnumerator());
            }
            else
            {
                ExecutionInfo executionInfo = this.Bind();

                if (executionInfo.Resolver != null)
                {
                    // Execute the query.
                    return(this.ExecuteInternal <TElement>(this.queryProvider.Table.ServiceClient, this.queryProvider.Table, executionInfo.Resolver, executionInfo.RequestOptions, executionInfo.OperationContext).GetEnumerator());
                }
                else
                {
                    return(this.ExecuteInternal(this.queryProvider.Table.ServiceClient, this.queryProvider.Table, executionInfo.RequestOptions, executionInfo.OperationContext).GetEnumerator());
                }
            }
        }
Esempio n. 22
0
 /// <summary>
 /// Replace the previous data stored with this execution information with the specified new value.
 /// If a stored object exists and is of the same type as the new one, it will be updated to match the new values
 /// otherwise the record will be replaced with the new object.
 /// </summary>
 /// <param name="exInfo">The execution information for the current operation</param>
 /// <param name="unique">The potential new item</param>
 /// <returns>The current object - either the orginal stored value if it was updated, or the new object
 /// if it was replaced</returns>
 public TModelObject Update <TModelObject>(ExecutionInfo exInfo, TModelObject unique)
     where TModelObject : ModelObject
 {
     if (exInfo != null)
     {
         ModelObject original = Get(exInfo);
         if (original != null && unique != null && original is TModelObject)
         {
             //original.CopyFieldsFrom(unique);
             original.Undelete();
             exInfo.HistoryItemCount++;
             return((TModelObject)original);
         }
         else
         {
             if (unique != null)
             {
                 Set(exInfo, unique);
             }
             else
             {
                 exInfo.HistoryItemCount++;
             }
             if (original != null)
             {
                 original.Delete();
             }
             return(unique);
         }
     }
     else
     {
         return(unique);
     }
 }
Esempio n. 23
0
        public void ShouldGetEmptyTagListByDefault()
        {
            var specInfo = new SpecInfo
            {
                Tags     = { "foo" },
                Name     = "",
                FileName = "",
                IsFailed = false
            };
            var scenarioInfo = new ScenarioInfo
            {
                Tags     = { "bar" },
                Name     = "",
                IsFailed = false
            };
            var currentScenario = new ExecutionInfo
            {
                CurrentScenario = scenarioInfo,
                CurrentSpec     = specInfo
            };
            var currentExecutionInfo = new ScenarioExecutionStartingRequest
            {
                CurrentExecutionInfo = currentScenario
            };
            var message = new Message
            {
                ScenarioExecutionStartingRequest = currentExecutionInfo,
                MessageType = Message.Types.MessageType.ScenarioExecutionStarting,
                MessageId   = 0
            };

            var tags = AssertEx.ExecuteProtectedMethod <ExecutionStartingProcessor>("GetApplicableTags", message);

            Assert.IsEmpty(tags);
        }
Esempio n. 24
0
        public override bool Execute(ExecutionInfo exInfo = null)
        {
            LoadCase lCase = Model.LoadCases.FindByName(Case);

            if (lCase == null || lCase.IsDeleted)
            {
                lCase = Model.Create.LoadCase(Case, exInfo);
            }
            GravityLoad nLoad = Model.Create.GravityLoad(lCase, exInfo);

            nLoad.Name = Name;
            //nLoad.Axes = Axes;
            nLoad.Direction = Direction;
            nLoad.Value     = Value;
            if (ApplyTo == null)
            {
                nLoad.AppliedTo.Clear();
                nLoad.AppliedTo.All = true;
            }
            else
            {
                nLoad.AppliedTo.Set(ApplyTo);
            }
            Load = nLoad;
            return(true);
        }
Esempio n. 25
0
        private void TimerCallback(object state)
        {
            Action executeAction = null;

            lock (m_lockObj)
            {
                if (m_executionInfo != null)
                {
                    if (DateTime.Now - m_executionInfo.Timestamp >= TimeSpan.FromMilliseconds(m_delay))
                    {
                        Debug.WriteLine("Action is set to be executed.");
                        executeAction   = m_executionInfo.Action;
                        m_executionInfo = null;
                        ChangeTimer(false);
                    }
                }
            }
            if (executeAction != null)
            {
                try
                {
                    executeAction();
                }
                catch (Exception exc)
                {
                    //Logger.Instance.Error("Exeption during delayed execution", exc);
                }
            }
        }
Esempio n. 26
0
        public static ExecutionInfo RunCompiler(string srcPath, ProcessInfo compilerProcessInfo)
        {
            var embedObjs = new EmbedmentObjectDictionary <string>();

            embedObjs.UpdateObject("srcPath", srcPath);

            var execInfo = new ExecutionInfo();

            var proc = new Process
            {
                StartInfo = compilerProcessInfo.CreateProcessStartInfo(embedObjs)
            };

            proc.Start();

            proc.WaitForExit();

            execInfo.SetMemoryNoData();
            execInfo.SetTime(proc.UserProcessorTime.TotalMilliseconds, "ms");
            execInfo.ExitCode = proc.ExitCode;
            execInfo.stdout   = proc.StandardOutput.ReadToEnd();
            execInfo.stderr   = proc.StandardError.ReadToEnd();

            proc.Close();

            return(execInfo);
        }
Esempio n. 27
0
        public override bool Execute(ExecutionInfo exInfo = null)
        {
            Result = false;
            if (FilePath.IsValid && Write)
            {
                if (Options == null)
                {
                    Options = new RobotConversionOptions(true);
                }

                Document.Model.GenerateNodes(new NodeGenerationParameters());
                var robot = new RobotController();
                robot.Message += HandleMessage;
                RobotIDMappingTable idMap = null;
                if (Document.IDMappings.ContainsKey(FilePath))
                {
                    idMap = Document.IDMappings[FilePath] as RobotIDMappingTable;
                }
                if (idMap == null)
                {
                    idMap = Document.IDMappings.GetLatest(".rtd") as RobotIDMappingTable;
                }
                if (idMap == null)
                {
                    idMap = new RobotIDMappingTable();
                    Document.IDMappings.Add(FilePath, idMap);
                }
                robot.UpdateRobotFromModel(FilePath, Model, ref idMap, Options);
                //robot.WriteModelToRobot(FilePath, Document.Model, ref idMap);
                robot.Close();
                robot.Release();
                Result = true;
            }
            return(true);
        }
        public void ShouldGetTagListFromScenarioAndSpecAndIgnoreDuplicates()
        {
            var specInfo = new SpecInfo
            {
                Tags     = { "foo" },
                Name     = "",
                FileName = "",
                IsFailed = false
            };
            var scenarioInfo = new ScenarioInfo
            {
                Tags     = { "foo" },
                Name     = "",
                IsFailed = false
            };
            var currentScenario = new ExecutionInfo
            {
                CurrentScenario = scenarioInfo,
                CurrentSpec     = specInfo
            };
            var currentExecutionInfo = new StepExecutionEndingRequest
            {
                CurrentExecutionInfo = currentScenario
            };

            var tags = AssertEx.ExecuteProtectedMethod <StepExecutionEndingProcessor>("GetApplicableTags", currentScenario)
                       .ToList();

            Assert.IsNotEmpty(tags);
            Assert.AreEqual(1, tags.Count);
            Assert.Contains("foo", tags);
        }
        public async Task <IActionResult> StartInstance(string key, int port)
        {
            ExecutionInfo r = await _runner.GetByExecutionInfoKeyAsync(key);

            if (r != null)
            {
                return(BadRequest("Instance is alread running"));
            }


            GameInstance instance = _servers.GetById(key);

            if (instance == null)
            {
                return(NotFound(key));
            }

            r = await _runner.StartInstanceAsync("localhost", port, instance);

            if (r == null)
            {
                BadRequest();
            }

            instance.CurrentExecution = r;
            return(Ok(instance));
        }
        public async Task <IActionResult> RestartInstace(string key)
        {
            ExecutionInfo r = await _runner.GetByExecutionInfoKeyAsync(key);

            if (r == null)
            {
                return(BadRequest("Instance is not running"));
            }

            GameInstance instance = _servers.GetById(key);

            if (instance == null)
            {
                NotFound(key);
            }

            await _runner.StopInstanceAsync(key);

            r = await _runner.StartInstanceAsync(r.Hostname, r.Port, instance);

            if (r == null)
            {
                return(BadRequest());
            }

            instance.CurrentExecution = r;
            return(Ok(instance));
        }
Esempio n. 31
0
        public void ShouldGetTagListFromExecutionInfo()
        {
            var specInfo = new SpecInfo
            {
                Tags     = { "foo" },
                Name     = "",
                FileName = "",
                IsFailed = false
            };
            var executionInfo = new ExecutionInfo
            {
                CurrentSpec = specInfo
            };
            var currentExecutionInfo = new SpecExecutionEndingRequest
            {
                CurrentExecutionInfo = executionInfo
            };
            var message = new Message
            {
                SpecExecutionEndingRequest = currentExecutionInfo,
                MessageType = Message.Types.MessageType.StepExecutionEnding,
                MessageId   = 0
            };

            var tags = AssertEx.ExecuteProtectedMethod <SpecExecutionEndingProcessor>("GetApplicableTags", message)
                       .ToList();

            Assert.IsNotEmpty(tags);
            Assert.AreEqual(1, tags.Count);
            Assert.Contains("foo", tags);
        }
        public void ShouldGetEmptyTagListByDefault()
        {
            var specInfo = new SpecInfo
            {
                Tags     = { "foo" },
                Name     = "",
                FileName = "",
                IsFailed = false
            };
            var scenarioInfo = new ScenarioInfo
            {
                Tags     = { "bar" },
                Name     = "",
                IsFailed = false
            };
            var currentScenario = new ExecutionInfo
            {
                CurrentScenario = scenarioInfo,
                CurrentSpec     = specInfo
            };


            var tags = AssertEx.ExecuteProtectedMethod <ExecutionStartingProcessor>("GetApplicableTags", currentScenario);

            Assert.IsEmpty(tags);
        }
Esempio n. 33
0
        public void Creating_an_execution_info_populated_properties(IOperation operation, Exception error, DateTimeOffset started, DateTimeOffset completed)
        {
            var sut = new ExecutionInfo(operation, error, started, completed);

            Assert.Equal(operation, sut.Operation);
            Assert.Equal(error, sut.Error);
            Assert.Equal(started, sut.Started);
            Assert.Equal(completed, sut.Completed);
        }
Esempio n. 34
0
        public static ExecutionInfo Execute(string program, string commandLine)
        {
            ExecutionInfo e = new ExecutionInfo();
            e.CommandLine = program + " " + commandLine;
            e.Time = Environment.TickCount;
            e.ErrorLevel = -1;
            StreamReader outputReader = null;
            StreamReader errorReader = null;
            try
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo(program, commandLine);
                processStartInfo.ErrorDialog = false;
                processStartInfo.UseShellExecute = false;
                processStartInfo.RedirectStandardError = true;
                processStartInfo.RedirectStandardInput = false;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.CreateNoWindow = true;
                processStartInfo.WindowStyle = ProcessWindowStyle.Normal;

                Process process = new Process();

                process.StartInfo = processStartInfo;
                bool processStarted = process.Start();

                if (processStarted)
                {
                    outputReader = process.StandardOutput;
                    errorReader = process.StandardError;
                    process.WaitForExit();
                    e.ErrorLevel = process.ExitCode;
                    e.Output = outputReader.ReadToEnd();
                    e.ErrorOutput = errorReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                e.ErrorOutput += "Error lanching the {0} = {1}".format(e.CommandLine, ex.ToString());
            }
            finally
            {
                if (outputReader != null)
                    outputReader.Close();
                if (errorReader != null)
                    errorReader.Close();

                if (e.ErrorLevel != 0)
                {
                    e.ErrorOutput = e.Output;
                    e.Output = "";
                }
            }
            e.Time = Environment.TickCount - e.Time;
            return e;
        }
Esempio n. 35
0
		/////////////////////////////////////////////////////////////////////////////

		public RazorRunnerException( RunHow runHow, string error, string razorError, string code )
			: base( error )
		{
			// ******
			RunContext = runHow;
			RazorError = razorError;
			Code = code;

			// ******
			var stackDump = new StringBuilder();
			this.ExecutionInfo = ThreadContext.GetExecutionInfo( stackDump, error );
			StackDump = stackDump.ToString();
		}
Esempio n. 36
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        ReportExecutionService reportExecutionService = new ReportExecutionService();   // Web Service proxy
        reportExecutionService.Credentials = new NetworkCredential("reportservice", "Asdfghjkl?", "kswh107");

        string reportPath = "/ReconCurrent/ReconCurrent";
        string format = "PDF";

        // Render arguments
        byte[] result = null;
        string historyID = null;

        string encoding;
        string mimeType;
        string extension;
        Warning[] warnings = null;
        string[] streamIDs = null;

        ExecutionInfo execInfo = new ExecutionInfo();
        ExecutionHeader execHeader = new ExecutionHeader();

        reportExecutionService.ExecutionHeaderValue = execHeader;

        execInfo = reportExecutionService.LoadReport(reportPath, historyID);

        String SessionId = reportExecutionService.ExecutionHeaderValue.ExecutionID;

        result = reportExecutionService.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);

        Response.ClearContent();
        Response.AppendHeader("content-length", result.Length.ToString());
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(result);
        Response.End();
        //Response.Flush();
        //Response.Close();
    }
            public void TakeFreeCell(ExecutionInfo[] executionInfos, string[] threadNames)
            {
                Contract.Require(TplTask == null, "TplTask == null");
                  Contract.Require(_ownedCellIndex == Free, "_ownedCellIndex == Free");

                  for (int index = 0; index < executionInfos.Length; index++)
                  {
                  var cell = executionInfos[index];

                  var cellAlreadyOwned = cell != null;
                  //First check to skip unnecessary CAS operation.
                  if (cellAlreadyOwned) continue;

                  var originalValue = Interlocked.CompareExchange(ref cell, this, null);

                  //Second check for interlocked result;
                  cellAlreadyOwned = originalValue != null;

                  if (cellAlreadyOwned) continue;
                  _ownedCellIndex = index;
                  ThreadName = threadNames[index];
                  break;
                  }
            }
Esempio n. 38
0
		///////////////////////////////////////////////////////////////////////////////

		public void Trace( ExecutionInfo ei, string fmt, params object [] args )
		{
			System.Diagnostics.Trace.WriteLine( Helpers.SafeStringFormat(fmt, args) );
		}
Esempio n. 39
0
		///////////////////////////////////////////////////////////////////////////////

		public void WriteMessage( ExecutionInfo ei, string fmt, params object [] args )
		{
			Console.WriteLine( Helpers.SafeStringFormat(fmt, args) );
		}
Esempio n. 40
0
		///////////////////////////////////////////////////////////////////////////////

		public void WriteMessage( ExecutionInfo ei, string msg, params object [] args )
		{
			task.Log.LogMessage( msg, args );
		}
Esempio n. 41
0
        private object RunInternal(MethodOverloads methodOverloads, object[] rawParams)
        {
            // TODO: Security
            FileIOPermission phoenixLauncherFile = new FileIOPermission(FileIOPermissionAccess.AllAccess, System.IO.Path.Combine(Core.Directory, "PhoenixLauncher.xml"));
            phoenixLauncherFile.Deny();

            // First create ParameterData array
            ParameterData[] parameters = new ParameterData[rawParams.Length];
            for (int i = 0; i < rawParams.Length; i++) {
                parameters[i] = new ParameterData(rawParams[i]);
            }

            // Get valid overloads (array is never empty)
            Method[] methods = methodOverloads.FindOverloads(parameters);

            Exception exception = null;

            foreach (Method m in methods) {
                ExecutionInfo info = new ExecutionInfo(m);

                ExecutionAttribute[] execAttributes = (ExecutionAttribute[])m.MethodInfo.GetCustomAttributes(typeof(ExecutionAttribute), false);

                try {
                    // Call all Execution attributes
                    for (int i = 0; i < execAttributes.Length; i++) {
                        execAttributes[i].Starting(m);
                    }

                    // Add execution to running list
                    lock (syncRoot) {
                        if (runningExecutions.Count >= Executions.MaxExecutions) {
                            throw new RuntimeException("Executions limit exceeded.");
                        }

                        RuntimeCore.AddAssemblyObject(info, this);
                        runningExecutions.Add(info);

                        try {
                            // Raise Started event
                            executionStarted.Invoke(this, new ExecutionsChangedEventArgs(info));
                        }
                        catch (Exception e) {
                            Core.ShowMessageBoxAsync("Unhandled exception in Executions.ExecutionStarted event handler.\r\nMessage: " + e.Message, "Warning");
                        }
                    }

                    // Init thread-dependent classes
                    if (!threadInitialized) {
                        ScriptErrorException.ThreadInit();
                        WorldData.World.ThreadInit();
                        Journal.ThreadInit();
                        threadInitialized = true;
                    }

                    // Invoke
                    try {
                        return m.Invoke(parameters);
                    }
                    catch (System.Reflection.TargetInvocationException e) {
                        // Im interested only in exception thrown by code
                        throw e.InnerException;
                    }
                }
                catch (ParameterException e) {
                    exception = e;
                }
                catch (ExecutionBlockedException e) {
                    exception = e;
                }
                finally {
                    // Remove execution from running list
                    lock (syncRoot) {
                        runningExecutions.Remove(info);
                        RuntimeCore.RemoveAssemblyObject(info);

                        try {
                            // Raise Finished event
                            executionFinished.Invoke(this, new ExecutionsChangedEventArgs(info));
                        }
                        catch (Exception e) {
                            Core.ShowMessageBoxAsync("Unhandled exception in Executions.ExecutionFinished event handler.\r\nMessage: " + e.Message, "Warning");
                        }
                    }

                    // Call all Execution attributes
                    for (int i = 0; i < execAttributes.Length; i++) {
                        execAttributes[i].Finished(m);
                    }
                }
            }

            if (exception != null) {
                throw exception;
            }
            else {
                throw new InternalErrorException();
            }
        }
Esempio n. 42
0
 public ExecutionsChangedEventArgs(ExecutionInfo ei)
 {
     executionInfo = ei;
 }
Esempio n. 43
0
		///////////////////////////////////////////////////////////////////////////////

		public void Trace( ExecutionInfo ei, string fmt, params object [] args )
		{
			System.Diagnostics.Trace.WriteLine( string.Format("at Line {0}, in {1}:", ei.Line, ei.FileName) );
			System.Diagnostics.Trace.WriteLine( Helpers.SafeStringFormat(fmt, args) );
		}
Esempio n. 44
0
        /// <summary>
        /// This first version of RenderReport is strictly for legacy support of NIFTransferShipment.  NIFTransferShipment should be re-worked to use the rendorReport
        /// version that accepts an array of ParameterValues.
        /// </summary>
        /// <param name="reportPath"></param>
        /// <param name="identifier"></param>
        /// <returns></returns>
        public byte[][] renderReport(string reportPath, ParameterValue[] reportParameters)
        {
            // Private variables for rendering
            string historyID = null;
            ExecutionHeader execHeader = new ExecutionHeader();

            try
            {
                rs.Timeout = 300000;
                rs.ExecutionHeaderValue = execHeader;

                ExecutionInfo execInfo = new ExecutionInfo();
                execInfo = rs.LoadReport(reportPath, historyID);

                if (reportParameters != null)
                {
                    rs.SetExecutionParameters(reportParameters, "en-us");
                }

                Byte[][] pages = new Byte[0][];
                string format = "IMAGE";
                int numberOfPages = 1;
                byte[] currentPageStream = new byte[1] { 0x00 }; // this single byte will prime the while loop
                string extension = null;
                string encoding = null;
                string mimeType = null;
                string[] streamIDs = null;
                Warning[] warnings = null;

                while (currentPageStream.Length > 0)
                {
                    string deviceInfo = String.Format(@"<DeviceInfo><OutputFormat>EMF</OutputFormat><PrintDpiX>96</PrintDpiX><PrintDpiY>96</PrintDpiY><StartPage>{0}</StartPage></DeviceInfo>", numberOfPages);

                    //Execute the report and get page count.
                    currentPageStream = rs.Render(
                       format,
                       deviceInfo,
                       out extension,
                       out encoding,
                       out mimeType,
                       out warnings,
                       out streamIDs);
                    
                    if (currentPageStream.Length == 0 && numberOfPages == 1)
                    {
                        break;  // nothing rendered
                    }

                    if (currentPageStream.Length > 0)
                    {
                        Array.Resize(ref pages, pages.Length + 1);
                        pages[pages.Length - 1] = currentPageStream;
                        numberOfPages++;
                    }

                }

                m_numberOfPages = numberOfPages - 1;

                return pages;
            }
            catch (SoapException ex)
            {
                eventLog.WriteEntry(ex.Detail.InnerXml, EventLogEntryType.Information, 7001);
                Console.WriteLine(ex.Detail.InnerXml);
            }
            catch (Exception ex)
            {
                eventLog.WriteEntry(ex.Message, EventLogEntryType.Information, 7001);
                Console.WriteLine(ex.Message);
            }
            finally
            {
            }

            return null;
        }
Esempio n. 45
0
		///////////////////////////////////////////////////////////////////////////////

		public void Trace( ExecutionInfo ei, string msg, params object [] args )
		{
			// ******
			string message = SafeStringFormat( msg, args );
			if( null == ei ) {
				new ExecutionInfo();
			}

			Messages.Add( new NmpResult.HostMessage() {	MessageType = TraceMessage, 
																				DistressLevel = ei.DistressLevel, 
																				FullMessage = ei.FullMessage,
																				Message = message,
																				Line = ei.Line, 
																				Column = ei.Column
																			}
									);

			System.Diagnostics.Trace.WriteLine( message );
		}
Esempio n. 46
0
File: Host.cs Progetto: jmclain/Nmp
		///////////////////////////////////////////////////////////////////////////////

		public void WriteMessage( ExecutionInfo ei, string fmt, params object [] args )
		{
			//if( null != ei ) {
			//	Console.WriteLine( "at Line {0}, in {1}:", ei.Line, ei.FileName );
			//}

			// ******
			Console.WriteLine( Helpers.SafeStringFormat(fmt, args) );
		}
Esempio n. 47
0
        private void TryStartNewThread(IExecutionQueue executor)
        {
            BEGIN:
            if (_disposed) return;

            //Second check to ensure concurrency threshold would not be exceeded.
            var currentConcurrency = Interlocked.Increment(ref _currentConcurrency);

            if (currentConcurrency > _maxConcurrency)
            {
                currentConcurrency = Interlocked.Decrement(ref _currentConcurrency);

                if (currentConcurrency == 0)
                {
                    goto BEGIN;
                }

                return;
            }
            ExecutionEnvelope envelope;
            if (executor == null)
            {
                envelope = TakeNextTask();
            }
            else
            {
                envelope = executor.Dequeue();
            }

            if (envelope == null)
            {
                Interlocked.Decrement(ref _currentConcurrency);
                return;
            }

            if (Logger.IsDebugEnabled)
            {
                Logger.Debug("Starting new execution thread.");
            }

            var executionInfo = new ExecutionInfo { CurrentTask = envelope };

            var tplTask = new Task(PerformTasks, executionInfo);

            executionInfo.TakeFreeCell(_executionInfos, _threadNames);

            executionInfo.TplTask = tplTask;

            tplTask.Start();
        }