public ProcessResult FillContent(XElement contentControl, IEnumerable<IContentItem> items)
		{
			var processResult = new ProcessResult();
			var handled = false;
			
			foreach (var contentItem in items)
			{
				var itemProcessResult = FillContent(contentControl, contentItem);
				if (!itemProcessResult.Handled) continue;

				handled = true;
				if (!itemProcessResult.Success)
					processResult.Errors.AddRange(itemProcessResult.Errors);
			}

			if (!handled) return ProcessResult.NotHandledResult;

			if (processResult.Success && _isNeedToRemoveContentControls)
			{
				// Remove the content control for the table and replace it with its contents.
				foreach (var xElement in contentControl.AncestorsAndSelf(W.sdt))
				{
					xElement.RemoveContentControl();
				}
			}

			return processResult;
		}
        public ProcessResult Start()
        {
            ProcessResult totalResult = new ProcessResult();

            if (!_fileSystem.DirectoryExists(_settings.BasePath))
            {
                _fileSystem.CreateDirectory(_settings.BasePath);
            }

            string subdir = CreateNewSubdirName(DateTime.Now);
            _settings.UpdateOutputPath(subdir);
            if (!_fileSystem.DirectoryExists(_settings.OutputPath))
            {
                _fileSystem.CreateDirectory(_settings.OutputPath);
            }

            foreach (BaseProcess process in _processes)
            {
                totalResult = process.Process();

                if (totalResult.ResultCode == ExitCode.Failure)
                {
                    break;
                }
            }

            CleanUp();

            return totalResult;
        }
Ejemplo n.º 3
0
        public void SetValues(ProcessResult result)
        {
            this.buttonTestDetails.Visible = false;

            _result = result;
            if (result.TestResults != null)
            {
                 this.labelTestsFailingCount.Text = result.TestResults.CountFailed.ToString();
                this.labelTestsPassingCount.Text = result.TestResults.CountPassed.ToString();
                this.labelTestsExecutedCount.Text = result.TestResults.CountExecuted.ToString();

                if (result.TestResults.CountFailed > 0)
                {
                    this.buttonTestDetails.Visible = true;
                }

                if (result.TestResults.CoveredAssemblies != null)
                {
                    foreach (CoveredAssembly assembly in result.TestResults.CoveredAssemblies)
                    {
                        listBoxCoverage.Items.Add(assembly.Name + " " + assembly.GetCoverage().ToString() + "%");
                    }
                }
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Creates a processing result with the specified state.
 /// </summary>
 /// <param name="state">The state.</param>
 /// <param name="message">The message.</param>
 /// <returns></returns>
 public static ProcessResult Create(ProcessState state, string message)
 {
     var result = new ProcessResult();
     result.State = state;
     result.Message = message;
     return result;
 }
        public ProcessResult Execute(ProcessInfo processInfo, ProjectItem item, TaskExecutionContext context)
        {
            var outputFile = context.GeneratePathInWorkingDirectory(item.NameOrType + ".log");
            if ((this.Item == null) || (this.Context == null))
            {
                return this.Execute(processInfo,
                                    item.Project.Name,
                                    item.NameOrType,
                                    outputFile);
            }

            Assert.AreEqual(this.FileName, processInfo.FileName);
            var actual = processInfo.Arguments == null ? null : processInfo.Arguments.ToString();
            Assert.AreEqual(this.Arguments, actual);
            Assert.AreEqual(this.WorkingDirectory, processInfo.WorkingDirectory);
            Assert.AreSame(this.Item, item);
            Assert.AreEqual(this.Context, context);

            var fileSystemMock = new Mock<IFileSystem>();
            fileSystemMock.Setup(fs => fs.OpenFileForRead(outputFile)).Returns(new MemoryStream());
            var result = new ProcessResult(
                fileSystemMock.Object,
                outputFile,
                this.ExitCode,
                this.TimedOut,
                this.Failed);
            return result;
        }
Ejemplo n.º 6
0
        public void doWork(BackgroundWorker worker, DoWorkEventArgs args)
        {
            Exception processEx = null;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(Constantes.language);
            this.modLog.Info(String.Format("Starting worker thread: [{0}]", this.getType().ToString()));

            try
            {
                this.doSpecificWork(worker, args);
            }
            catch (Exception ex) {
                processEx = ex;
            }
            finally
            {
                try
                {
                    ProcessResult pr = new ProcessResult(this.getType());
                    pr.ProcessException = processEx;
                    pr.ProcessOutput = args.Result;

                    if (returnUpdatedDbStats)
                    {
                        pr.DbStatistics = this.chargeData.getDbStatistics();
                    }

                    // Cambiamos el resultado del objeto 'DoWorkEventArgs' (lo que devolvemos hacia fuera) por nuestro
                    // objeto ProcessResult, que además de tener el resultado como tal (processOutput) tiene incluida
                    // la posible excepción que el proceso haya podido lanzar, y las estadísticas actualizadas de BBDD.
                    args.Result = pr;
                }
                catch (Exception) { }
            }
            this.modLog.Info(String.Format("Finished worker thread: [{0}]", this.getType().ToString()));
        }
Ejemplo n.º 7
0
 public void Match(Func<AccountLine, AccountLine, bool> matchmethod)
 {
     this.match = matchmethod;
     ProcessResult pRes = new ProcessResult(skbRepo.GetAll(), true);
     do
     {
         pRes = ProcessMatches(pRes.UnMatched);
     } while (pRes.AnyChange);
 }
        /// <summary>
        /// Get modified files
        /// </summary>
        /// <param name="processResult">stdout process result</param>
        /// <param name="from">start date and time (not used)</param>
        /// <param name="to">end date and time (not used)</param>
        /// <returns></returns>
        public Modification[] GetModifications(ProcessResult processResult, DateTime from, DateTime to)
		{
			Modification[] Result = null;
            string StdOut = processResult.StandardOutput;
            StringReader reader = new StringReader(StdOut);            
            JediVCSFileInfoList Files = GetJediVCSFileInfoList(reader);
            Result = GetModifiedFiles(Files);
            return Result;
        }
Ejemplo n.º 9
0
		public static void Log(ProcessResult result)
		{
			using (var stream = File.Open(path, FileMode.Open, FileAccess.Write))
			{
				results.Add(result);
				var serializer = new DataContractJsonSerializer(typeof(List<ProcessResult>));
				serializer.WriteObject(stream, results);
				stream.Flush();
			}
		}
Ejemplo n.º 10
0
		public void GetModificationsDoesNotCreateLabelWhenThereAreNoModifications()
		{
			ProcessResult result = new ProcessResult("",string.Empty, 0, false);
			Modification[] emptyArray = new Modification[0];
			_historyParser.SetupResult("Parse", emptyArray, typeof(TextReader), typeof(DateTime), typeof(DateTime));
			_executor.ExpectAndReturn("Execute", result, new IsTypeOf(typeof(ProcessInfo)));
			_executor.ExpectNoCall("Execute", typeof(ProcessInfo));

			_vss.GetModifications(IntegrationResultMother.CreateSuccessful(DateTime.Now), IntegrationResultMother.CreateSuccessful(DateTime.Now));
		}
Ejemplo n.º 11
0
 public ProcessTaskResult(ProcessResult result)
 {
     this.result = result;
     if (Failed())
     {
         Log.Info("Task execution failed");
         Log.Info("Task output: " + result.StandardOutput);
         if (! StringUtil.IsBlank(result.StandardError)) Log.Info("Task error: " + result.StandardError);
     }
 }
Ejemplo n.º 12
0
		public static bool TryExecuteJava(string command, out ProcessResult result)
		{
			if (command == null)
				throw new ArgumentNullException("command");

			var javaPath = GetJavaInstallationPath() + "\\bin\\";
			var filename = javaPath + "java.exe";

			return TryExecute(filename, command, out result);
		}
Ejemplo n.º 13
0
 /// <summary>
 /// Formata a saída
 /// </summary>
 /// <param name="word"></param>
 /// <param name="pos"></param>
 /// <param name="deadCats"></param>
 private static void FormatOutput(string word, ProcessResult result)
 {
     if (!result.found)
     {
         Console.WriteLine(String.Format("Palavra não encontrada. Gatos mortos = {2}", word, result.index.ToString(), result.deadCats.ToString()));
     }
     else
     {
         Console.WriteLine(String.Format("Palavra '{0}' encontrada na posição {1}. Gatos mortos = {2}", word, result.index.ToString(), result.deadCats.ToString()));
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Constructor of ProcessTaskResult
        /// </summary>
        /// <param name="result">Process result data.</param>
        /// <param name="ignoreStandardOutputOnSuccess">Set this to true if you do not want the standard output (stdout) of the process to be merged in the build log; otherwise false.</param>
	    public ProcessTaskResult(ProcessResult result, bool ignoreStandardOutputOnSuccess)
		{
			this.result = result;
	        this.ignoreStandardOutputOnSuccess = ignoreStandardOutputOnSuccess;

			if (this.CheckIfSuccess())
			{
				Log.Info("Task output: " + result.StandardOutput);
				string input = result.StandardError;
				if (!string.IsNullOrEmpty(input)) 
					Log.Info("Task error: " + result.StandardError);
			}
		}
Ejemplo n.º 15
0
        public void LogStatistics(Settings settings, ProcessResult result)
        {
            DateTime now = DateTime.Now;
            string path = GetLogFilePath(now, settings);
            string timestamp = GetTimeStamp(now);

            XmlDocument doc = GetXmlDocument(path);
            XmlNode root = GetRootNode(doc);

            AppendTimestampNode(result, timestamp, doc, root);

            Save(doc, path);
        }
 public void ReadStandardErrorOnlyReturnsOutputLines()
 {
     var filename = "testoutput.txt";
     var fileSystemMock = GenerateFileSystemMock(filename, "OLine 1", "ELine 2");
     var result = new ProcessResult(
         fileSystemMock.Object,
         filename,
         0,
         false);
     var actual = result.ReadStandardError().ToArray();
     var expected = new[] { "Line 2" };
     CollectionAssert.AreEqual(expected, actual);
 }
        public void FillContent(XElement contentControl, IContentItem item)
        {
            if (!(item is ImageContent))
            {
                _processResult = ProcessResult.NotHandledResult;
                return;
            }

            var field = item as ImageContent;
            // If image bytes was not provided, then doing nothing
            if (field.Binary == null || field.Binary.Length == 0) { return; }

            // If there isn't a field with that name, add an error to the error string,
            // and continue with next field.
            if (contentControl == null)
            {
                _processResult.Errors.Add(String.Format("Field Content Control '{0}' not found.",
                    field.Name));
                return;
            }


            var blip = contentControl.DescendantsAndSelf(A.blip).First();
            if (blip == null)
            {
                _processResult.Errors.Add(String.Format("Image to replace for '{0}' not found.",
                    field.Name));
                return;
            }

            // Creating a new image part
            var imagePart = _context.WordDocument.MainDocumentPart.AddImagePart(field.MIMEType);
            // Writing image bytes to it
            using (BinaryWriter writer = new BinaryWriter(imagePart.GetStream()))
            {
                writer.Write(field.Binary);
            }
            // Setting reference for CC to newly uploaded image
            blip.Attribute(R.embed).Value = _context.WordDocument.MainDocumentPart.GetIdOfPart(imagePart);

            //var imageId = blip.Attribute(R.embed).Value;
            //var xmlPart = _context.WordDocument.MainDocumentPart.GetPartById(imageId);
            //if (xmlPart is ImagePart)
            //{
            //    ImagePart imagePart = xmlPart as ImagePart;
            //    using (BinaryWriter writer = new BinaryWriter(imagePart.GetStream()))
            //    {
            //        writer.Write(field.Binary);
            //    }
            //}
        }
		public ProcessResult FillContent(XElement contentControl, IEnumerable<IContentItem> items)
		{
			_processResult = new ProcessResult();

			foreach (var contentItem in items)
			{
				FillContent(contentControl, contentItem);
			}


			if (_processResult.Success && _isNeedToRemoveContentControls)
				contentControl.RemoveContentControl();

			return _processResult;
		}
Ejemplo n.º 19
0
		public static bool TryExecute(string filename, string args, out ProcessResult result)
		{
			// Set HomeDirectory for shorter paths ?

			if (filename == null)
				throw new ArgumentNullException("filename");

			if (args == null)
				args = string.Empty;

			string output = string.Empty;
			string error = string.Empty;
			int exitCode = -1;

			var processStartInfo = new ProcessStartInfo(filename, args)
			{
				CreateNoWindow = true,
				WindowStyle = ProcessWindowStyle.Hidden,
				UseShellExecute = false,
				RedirectStandardOutput = true,
				RedirectStandardError = true
				// WorkingDirectory ?
			};

			// Try Execute
			try
			{
				using (var process = Process.Start(processStartInfo))
				{
					output = process.StandardOutput.ReadToEnd();
					error = process.StandardError.ReadToEnd();
					exitCode = process.ExitCode;

					//if (!process.HasExited)	// Needed ? Dispose will probably fix this ?
					//    process.Kill();
				}
			}
			catch (Exception e)
			{
				// Store exeception in ExecuteResult ?
				// Log error somehow ? try/catch in caller instead ?
				// Output to output, or ErrorList ?
			}

			result = new ProcessResult(output, error, exitCode);
			return result.ExitCode == 0;
		}
Ejemplo n.º 20
0
 public static ProcessResult StartProcess(string workingDirectory, string cmdName, string argument, ProcessWindowStyle style = ProcessWindowStyle.Hidden)
 {
     ProcessResult rlt = new ProcessResult();
     Process proc = new Process();
     proc.StartInfo.UseShellExecute = false;
     proc.StartInfo.RedirectStandardOutput = true;
     proc.StartInfo.FileName = cmdName;
     proc.StartInfo.Arguments = argument;
     proc.StartInfo.WindowStyle = style;
     proc.StartInfo.WorkingDirectory = workingDirectory;
     proc.StartInfo.CreateNoWindow = true;
     proc.Start();
     StreamReader reader = proc.StandardOutput;
     proc.WaitForExit();
     rlt.Process = proc;
     return rlt;
 }
        public void LogEvent_BuildFailure_AddEvent_EvellntAdded()
        {
            Settings settings = new Settings();
            settings.BasePath = @"c:\";

            StatisticsLoggerStub stub = new StatisticsLoggerStub();
            
            ProcessResult r = new ProcessResult();
            r.TestResults.CoveredAssemblies = new CoveredAssemblySet();
            CoveredAssembly assembly = new CoveredAssembly();
            assembly.Name = "thename";
            r.TestResults.CoveredAssemblies.Add(assembly);
            
            stub.LogStatistics(settings, r);

            Assert.AreEqual(1, stub.XmlDocument.SelectNodes("timestamps/timestamp/assembly[@id='thename']").Count);
            Assert.IsTrue(stub.IsSaved);
        }
 public void ConstructorSetsPropertiesForError()
 {
     var filename = "testoutput.txt";
     var fileSystemMock = GenerateFileSystemMock(filename, "OLine 1", "ELine 2");
     var exitCode = 32;
     var result = new ProcessResult(
         fileSystemMock.Object,
         filename,
         exitCode,
         false);
     Assert.AreEqual(filename, result.OutputPath);
     Assert.AreEqual(exitCode, result.ExitCode);
     Assert.IsFalse(result.TimedOut);
     Assert.IsTrue(result.Failed);
     Assert.IsFalse(result.Succeeded);
     Assert.AreEqual(1, result.NumberOfOutputLines);
     Assert.AreEqual(1, result.NumberOfErrorLines);
     Assert.IsTrue(result.HasErrorOutput);
 }
		public void FillContent(XElement contentControl, IContentItem item)
		{
			if (!(item is FieldContent))
			{
				_processResult = ProcessResult.NotHandledResult;
				return;
			}

			var field = item as FieldContent;

			// If there isn't a field with that name, add an error to the error string,
			// and continue with next field.
			if (contentControl == null)
			{
				_processResult.Errors.Add(String.Format("Field Content Control '{0}' not found.",
					field.Name));
				return;
			}
			contentControl.ReplaceContentControlWithNewValue(field.Value);

		}
Ejemplo n.º 24
0
		/// <summary>
		/// Creates a new process and adds it to the tracking list.
		/// </summary>
		/// <returns>New Process objects</returns>
		public static ProcessResult CreateProcess(string AppName, bool bAllowSpew, string LogName, Dictionary<string, string> Env = null, UnrealBuildTool.LogEventType SpewVerbosity = UnrealBuildTool.LogEventType.Console)
		{
			var NewProcess = HostPlatform.Current.CreateProcess(LogName);
			if (Env != null)
			{
				foreach (var EnvPair in Env)
				{
					if (NewProcess.StartInfo.EnvironmentVariables.ContainsKey(EnvPair.Key))
					{
						NewProcess.StartInfo.EnvironmentVariables.Remove(EnvPair.Key);
					}
					if (!String.IsNullOrEmpty(EnvPair.Value))
					{
						NewProcess.StartInfo.EnvironmentVariables.Add(EnvPair.Key, EnvPair.Value);
					}
				}
			}
			var Result = new ProcessResult(AppName, NewProcess, bAllowSpew, LogName, SpewVerbosity: SpewVerbosity);
			AddProcess(Result);
			return Result;
		}
        public ProcessResult Pay(string dataPackage, string key, string iv)
        {
            //положить деньги в банк:
            ProcessResult res = new ProcessResult();
            string xml = String.Empty;
            try
            {
                string decryptedKey = CryptoHelper.RSADecrypt(key);
                string decryptedIV = CryptoHelper.RSADecrypt(iv);
                xml = CryptoHelper.SymmetricDecrypt(dataPackage, decryptedKey, decryptedIV);
            }
            catch (Exception e)
            {
                res.content = "Error: " + e.Message;
                res.signature = CryptoHelper.Sign(res.content);
                return res;
            }

            Models.Payment pay = GetPaymentInstanceByInfo(xml);
            res.content = PaymentDAL.Instance.AddMoneyToAccount(pay).ToString();
            PaymentDAL.Instance.AddPaymentToDatabase(pay);
            res.signature = CryptoHelper.Sign(res.content);
            return res;
        }
Ejemplo n.º 26
0
 public async Task StatusChanged(ProcessResult processResult)
 {
 }
Ejemplo n.º 27
0
 override public ProcessResult Process(ProcessResult lastSiblingResult, TriggerObject trigObject) // lastSiblingResult used for conditionals
 {
     return(ProcessResult.Break);
 }
Ejemplo n.º 28
0
        /// <summary>
        ///   Performs the actions needed to add an authentication challenge to the inner IHttpActionResult, if needed.
        /// </summary>
        ///
        /// <param name="context">The authentication challenge context to consider.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        ///
        /// <returns>A Task that will perform the authentication challenge.</returns>
        ///
        /// <remarks>
        ///   This method will be executed by the framework after the action has executed, regardless of whether or not a challenge
        ///   should be generated.  Before generating the challenge, determine if it
        /// </remarks>
        ///
        public async Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var request = context.Request;

            // If there was an authenticated principal associated with the request or there was a result generated that should not
            // overridden, then no challenge is needed.

            if ((cancellationToken.IsCancellationRequested) || (request.GetRequestContext()?.Principal != null) || (!OrderFulfillmentAuthenticateAttributeAttribute.ShouldOverrideResponse(context)))
            {
                return;
            }

            var result = OrderFulfillmentAuthenticateAttributeAttribute.ProcessRequest(request, cancellationToken, true);

            // If there was no available handler located after processing the request, then attempt to retrieve the
            // default challenge handler.

            if (result == null)
            {
                var handler = OrderFulfillmentAuthenticateAttributeAttribute.SelectDefaultChallengeHandler(request.GetDependencyScope());

                if (handler != null)
                {
                    result = new ProcessResult(OrderFulfillmentAuthenticateAttributeAttribute.EmptyStringDictionary, handler);
                }
            }

            // If there was no available challenge handler, authentication is not possible.  Make
            // no alterations to the current response.

            if ((cancellationToken.IsCancellationRequested) || (result == null))
            {
                return;
            }

            // If the handler was able to produce a challenge, then clear any existing result/response and
            // set the new Unauthorized with the correct challenge.

            var challenge = result.AuthenticationHandler.GenerateChallenge(result.AuthenticationTokens, context);

            if (challenge != null)
            {
                context.ActionContext.Response?.Dispose();
                context.ActionContext.Response = null;

                context.Result = new UnauthorizedResult(new[] { challenge }, request);

                try
                {
                    var locator = request.GetDependencyScope();
                    var logger  = (locator.GetService(typeof(ILogger)) as ILogger);

                    if (logger != null)
                    {
                        var body = await request.SafeReadContentAsStringAsync();

                        logger.WithCorrelationId(request?.GetOrderFulfillmentCorrelationId())
                        .Information($"Response: {{Response}} { Environment.NewLine } Authentication is needed; a challenge was issued for {{Route}} with Headers: [{{Headers}}]",
                                     HttpStatusCode.Unauthorized,
                                     request?.RequestUri,
                                     request?.Headers);
                    }
                }

                catch
                {
                    // Do nothing; logging is a non-critical operation that should not cause
                    // cascading failures.
                }
            }
        }
Ejemplo n.º 29
0
 private void ExpectToExecuteWithArgumentsAndReturn(string args, ProcessResult returnValue)
 {
     mockProcessExecutor.ExpectAndReturn("Execute", returnValue, NewProcessInfo(args, DefaultWorkingDirectory));
 }
Ejemplo n.º 30
0
        private static bool IsAlias(string command)
        {
            ProcessResult result = ProcessHelper.Run("git", "config --get alias." + command);

            return(!string.IsNullOrEmpty(result.Output));
        }
Ejemplo n.º 31
0
 static void PrintExitCode(ProcessResult result)
 {
     Console.ForegroundColor = ConsoleColor.Yellow;
     Console.WriteLine($"Process exited with code {result.ExitCode}.");
     Console.ResetColor();
 }
Ejemplo n.º 32
0
        public void SubmitsTracesWithNetStandard(string packageVersion, bool enableCallTarget)
        {
            SetCallTargetSettings(enableCallTarget);

            // ALWAYS: 77 spans
            // - NpgsqlCommand: 21 spans (3 groups * 7 spans)
            // - DbCommand:  42 spans (6 groups * 7 spans)
            // - IDbCommand: 14 spans (2 groups * 7 spans)
            //
            // NETSTANDARD: +56 spans
            // - DbCommand-netstandard:  42 spans (6 groups * 7 spans)
            // - IDbCommand-netstandard: 14 spans (2 groups * 7 spans)
            //
            // CALLTARGET: +7 spans
            // - IDbCommandGenericConstrant<NpgsqlCommand>: 7 spans (1 group * 7 spans)
            //
            // NETSTANDARD + CALLTARGET: +7 spans
            // - IDbCommandGenericConstrant<NpgsqlCommand>-netstandard: 7 spans (1 group * 7 spans)
#if NET452
            var expectedSpanCount = 77;
#else
            var expectedSpanCount = 133;
#endif

            if (enableCallTarget)
            {
#if NET452
                expectedSpanCount = 84;
#else
                expectedSpanCount = 147;
#endif
            }

            const string dbType = "postgres";
            const string expectedOperationName = dbType + ".query";
            const string expectedServiceName   = "Samples.Npgsql-" + dbType;

            // NOTE: opt into the additional instrumentation of calls into netstandard.dll
            // see https://github.com/DataDog/dd-trace-dotnet/pull/753
            SetEnvironmentVariable("OTEL_TRACE_NETSTANDARD_ENABLED", "true");

            int agentPort = TcpPortProvider.GetOpenPort();

            using (var agent = new MockTracerAgent(agentPort))
                using (ProcessResult processResult = RunSampleAndWaitForExit(agent.Port, packageVersion: packageVersion))
                {
                    Assert.True(processResult.ExitCode >= 0, $"Process exited with code {processResult.ExitCode}");

                    var spans           = agent.WaitForSpans(expectedSpanCount, operationName: expectedOperationName);
                    int actualSpanCount = spans.Where(s => s.ParentId.HasValue).Count(); // Remove unexpected DB spans from the calculation
                    // Assert.Equal(expectedSpanCount, spans.Count); // Assert an exact match once we can correctly instrument the generic constraint case

                    if (enableCallTarget)
                    {
                        Assert.Equal(expectedSpanCount, actualSpanCount);
                    }
                    else
                    {
                        Assert.True(actualSpanCount == expectedSpanCount || actualSpanCount == expectedSpanCount + 4, $"expectedSpanCount={expectedSpanCount}, expectedSpanCount+4={expectedSpanCount + 4}, actualSpanCount={actualSpanCount}");
                    }

                    foreach (var span in spans)
                    {
                        Assert.Equal(expectedOperationName, span.Name);
                        Assert.Equal(expectedServiceName, span.Service);
                        Assert.Equal(SpanTypes.Sql, span.Type);
                        Assert.Equal(dbType, span.Tags[Tags.DbType]);
                        Assert.False(span.Tags?.ContainsKey(Tags.Version), "External service span should not have service version tag.");
                    }
                }
        }
        private static Task <ProcessResult> StartProcessFull(
            string command,
            ProcessPriorityClass priorityClass,
            ProcessTaskParams parameters,
            Action <string> progress,
            CancellationToken?cancellation,
            params string[] arguments)
        {
            var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = command,
                    Arguments              = string.Join(" ", arguments),
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                    CreateNoWindow         = true,
                    UseShellExecute        = false,
                    ErrorDialog            = false,
                    StandardOutputEncoding = Encoding.UTF8,
                    StandardErrorEncoding  = Encoding.UTF8,
                },
                EnableRaisingEvents = true,
            };

            var exited = new TaskCompletionSource <ProcessResult>();
            var result = new ProcessResult(proc, parameters);

            proc.Exited += (sender, args) =>
            {
                var exitcode = proc.ExitCode;
                if (exitcode == 0)
                {
                    exited.SetResult(result);
                }
                else
                {
                    exited.TrySetException(new InvalidOperationException(string.Join("\r\n", result.ErrorLines.Any() ? result.ErrorLines : result.ResultLines)));
                }

                proc.Dispose();
            };
            proc.ErrorDataReceived += (sender, args) =>
            {
                if (!string.IsNullOrWhiteSpace(args.Data))
                {
                    result.ErrorLines.AddLast(args.Data);
                    if ((result.Parameters.ErrorLinesLimit != -1) && (result.ErrorLines.Count > result.Parameters.ErrorLinesLimit))
                    {
                        result.ErrorLines.RemoveFirst();
                    }

                    progress?.Invoke(args.Data);
                }
            };
            proc.OutputDataReceived += (sender, args) =>
            {
                result.ResultLines.AddLast(args.Data);
                if ((result.Parameters.ResultLinesLimit != -1) && (result.ResultLines.Count > result.Parameters.ResultLinesLimit))
                {
                    result.ResultLines.RemoveFirst();
                }
            };

            proc.Start();
            proc.PriorityClass = priorityClass;
            proc.BeginErrorReadLine();
            proc.BeginOutputReadLine();

            cancellation?.Register(() =>
            {
                proc.Kill();
                proc.Dispose();
                exited.TrySetCanceled();
            });

            return(exited.Task);
        }
        /// <summary>
        ///     Uninstall the dnscrypt-proxy service.
        /// </summary>
        /// <returns>A ProcessResult.</returns>
        public ProcessResult Uninstall()
        {
            var processResult = new ProcessResult();
            try
            {
                // we do not check if the proxy is installed,
                // just let them clear the registry.
                const int timeout = 9000;
                using (var process = new Process())
                {
                    process.StartInfo.FileName = Path.Combine(Directory.GetCurrentDirectory(),
                        Global.DnsCryptProxyFolder, Global.DnsCryptProxyExecutableName);
                    process.StartInfo.Arguments = "--uninstall";
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.CreateNoWindow = true;
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    process.Start();
                    if (process.WaitForExit(timeout))
                    {
                        if (process.ExitCode == 0)
                        {
                            processResult.Success = true;
                        }
                        else
                        {
                            processResult.Success = false;
                        }
                    }
                    else
                    {
                        // Timed out.
                        throw new Exception("Timed out");
                    }
                }
            }
            catch (Exception exception)
            {
                processResult.StandardError = exception.Message;
                processResult.Success = false;
            }

            return processResult;
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Linear edge-refinement pass, followed by smoothing and projection
        /// - Edges are processed in prime-modulo-order to break symmetry
        /// - smoothing is done in parallel if EnableParallelSmooth = true
        /// - Projection pass if ProjectionMode == AfterRefinement
        /// - number of modified edges returned in ModifiedEdgesLastPass
        /// </summary>
        public virtual void BasicRemeshPass()
        {
            if (mesh.TriangleCount == 0)    // badness if we don't catch this...
            {
                return;
            }

            begin_pass();

            // Iterate over all edges in the mesh at start of pass.
            // Some may be removed, so we skip those.
            // However, some old eid's may also be re-used, so we will touch
            // some new edges. Can't see how we could efficiently prevent this.
            //
            begin_ops();

            int  cur_eid = start_edges();
            bool done    = false;

            ModifiedEdgesLastPass = 0;
            do
            {
                if (mesh.IsEdge(cur_eid))
                {
                    ProcessResult result = ProcessEdge(cur_eid);
                    if (result == ProcessResult.Ok_Collapsed || result == ProcessResult.Ok_Flipped || result == ProcessResult.Ok_Split)
                    {
                        ModifiedEdgesLastPass++;
                    }
                }
                if (Cancelled())        // expensive to check every iter?
                {
                    return;
                }
                cur_eid = next_edge(cur_eid, out done);
            } while (done == false);
            end_ops();

            if (Cancelled())
            {
                return;
            }

            begin_smooth();
            if (EnableSmoothing && SmoothSpeedT > 0)
            {
                if (EnableSmoothInPlace)
                {
                    FullSmoothPass_InPlace(EnableParallelSmooth);
                }
                else
                {
                    FullSmoothPass_Buffer(EnableParallelSmooth);
                }
                DoDebugChecks();
            }
            end_smooth();

            if (Cancelled())
            {
                return;
            }

            begin_project();
            if (target != null && ProjectionMode == TargetProjectionMode.AfterRefinement)
            {
                FullProjectionPass();
                DoDebugChecks();
            }
            end_project();

            if (Cancelled())
            {
                return;
            }

            end_pass();
        }
Ejemplo n.º 36
0
 private static void VerifyResult(ProcessResult result)
 {
     Assert.Equal("", result.Output);
     Assert.Equal("", result.Errors);
     Assert.Equal(0, result.ExitCode);
 }
Ejemplo n.º 37
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="arguments"></param>
        /// <returns></returns>
        private static ProcessResult ExecuteWithArguments(string arguments)
        {
            var processResult = new ProcessResult();

            try
            {
                var dnsCryptProxyExecutablePath = Path.Combine(Directory.GetCurrentDirectory(), Global.DnsCryptProxyFolder,
                                                               Global.DnsCryptProxyExecutableName);
                if (!File.Exists(dnsCryptProxyExecutablePath))
                {
                    throw new Exception($"Missing {dnsCryptProxyExecutablePath}");
                }

                const int timeout = 9000;
                using var process                        = new Process();
                process.StartInfo.FileName               = dnsCryptProxyExecutablePath;
                process.StartInfo.Arguments              = arguments;
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;

                var output = new StringBuilder();
                var error  = new StringBuilder();

                using var outputWaitHandle  = new AutoResetEvent(false);
                using var errorWaitHandle   = new AutoResetEvent(false);
                process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        output.AppendLine(e.Data);
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        error.AppendLine(e.Data);
                    }
                };
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                if (process.WaitForExit(timeout) &&
                    outputWaitHandle.WaitOne(timeout) &&
                    errorWaitHandle.WaitOne(timeout))
                {
                    if (process.ExitCode == 0)
                    {
                        processResult.StandardOutput = output.ToString();
                        processResult.StandardError  = error.ToString();
                        processResult.Success        = true;
                    }
                    else
                    {
                        processResult.StandardOutput = output.ToString();
                        processResult.StandardError  = error.ToString();
                        processResult.Success        = false;
                    }
                }
                else
                {
                    // Timed out.
                    throw new Exception("Timed out");
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception, "ExecuteWithArguments");
                processResult.StandardError = exception.Message;
                processResult.Success       = false;
            }
            return(processResult);
        }
Ejemplo n.º 38
0
        private async Task <bool> CheckCreateCategoryProcessIsValid(string categoryNameToCreate, ProcessResult proccessedResult)
        {
            Category categoryToCreate = await _categoryRepository.Get(p => p.Name == categoryNameToCreate);

            if (categoryToCreate != null)
            {
                proccessedResult.Message = Constants.CategoryService.CategoryToCreateAlreadyExist;
                return(false);
            }
            return(true);
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Realiza el registro de un Parámetro Sección
        /// </summary>
        /// <param name="filtro">Parámetro Sección a Registrar</param>
        /// <returns>Indicador de Error</returns>
        public ProcessResult <string> RegistrarParametroSeccion(ParametroSeccionRequest filtro)
        {
            string result           = "0";
            var    resultadoProceso = new ProcessResult <string>();

            try
            {
                if (filtro.CodigoParametro == null)
                {
                    throw new Exception();
                }

                var seccionRepetida = BuscarParametroSeccion(new ParametroSeccionRequest()
                {
                    CodigoParametro = filtro.CodigoParametro,
                    Nombre          = filtro.Nombre
                }).Result.Where(item => filtro.CodigoSeccion == null || item.CodigoSeccion != filtro.CodigoSeccion).FirstOrDefault();

                if (seccionRepetida != null)
                {
                    result = "2";
                    resultadoProceso.Result    = result;
                    resultadoProceso.IsSuccess = true;

                    return(resultadoProceso);
                }
                if (filtro.CodigoSeccion == null)
                {
                    var parametroSeccionUltimo = BuscarParametroSeccion(new ParametroSeccionRequest()
                    {
                        CodigoParametro = filtro.CodigoParametro,
                        EstadoRegistro  = null
                    }).Result.OrderByDescending(item => item.CodigoSeccion).FirstOrDefault();
                    filtro.CodigoSeccion = parametroSeccionUltimo != null ? parametroSeccionUltimo.CodigoSeccion + 1 : 1;

                    parametroSeccionEntityRepository.Insertar(ParametroSeccionAdapter.ObtenerParametroSeccionEntity(filtro));
                }
                else
                {
                    var entity       = ParametroSeccionAdapter.ObtenerParametroSeccionEntity(filtro);
                    var entityActual = parametroSeccionEntityRepository.GetById(filtro.CodigoParametro, filtro.CodigoSeccion);

                    entityActual.Nombre                          = entity.Nombre;
                    entityActual.CodigoTipoDato                  = entity.CodigoTipoDato;
                    entityActual.IndicadorPermiteModificar       = entity.IndicadorPermiteModificar;
                    entityActual.IndicadorObligatorio            = entity.IndicadorObligatorio;
                    entityActual.CodigoParametroRelacionado      = entity.CodigoParametroRelacionado;
                    entityActual.CodigoSeccionRelacionado        = entity.CodigoSeccionRelacionado;
                    entityActual.CodigoSeccionRelacionadoMostrar = entity.CodigoSeccionRelacionadoMostrar;

                    parametroSeccionEntityRepository.Editar(entityActual);
                }

                parametroSeccionEntityRepository.GuardarCambios();
                resultadoProceso.IsSuccess = true;
            }
            catch (Exception e)
            {
                result = "-1";
                resultadoProceso.Result    = result;
                resultadoProceso.IsSuccess = false;
                resultadoProceso.Exception = new ApplicationLayerException <ParametroValorService>(e);
            }
            return(resultadoProceso);
        }
Ejemplo n.º 40
0
    public static async Task <ProcessResult> ExecuteShellCommand(string command, string arguments, int timeout)
    {
        var result = new ProcessResult();

        using (var process = new Process())
        {
            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 outputCloseEvent = new TaskCompletionSource <bool>();

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

            var errorBuilder    = new StringBuilder();
            var errorCloseEvent = new TaskCompletionSource <bool>();

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

            bool isStarted;

            try
            {
                isStarted = process.Start();
            }
            catch (Exception error)
            {
                // Usually it occurs when an executable file is not found or is not executable

                result.Completed = true;
                result.ExitCode  = -1;
                result.Output    = error.Message;

                isStarted = false;
            }

            if (isStarted)
            {
                // Reads the output stream first and then waits because deadlocks are possible
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                // Creates task to wait for process exit using timeout
                var waitForExit = WaitForExitAsync(process, timeout);

                // Create task to wait for process exit and closing all output streams
                var processTask = Task.WhenAll(waitForExit, outputCloseEvent.Task, errorCloseEvent.Task);

                // Waits process completion and then checks it was not completed by timeout
                if (await Task.WhenAny(Task.Delay(timeout), processTask) == processTask && waitForExit.Result)
                {
                    result.Completed = true;
                    result.ExitCode  = process.ExitCode;

                    // Adds process output if it was completed with error
                    if (process.ExitCode != 0)
                    {
                        result.Output = $"{outputBuilder}{errorBuilder}";
                    }
                }
                else
                {
                    try
                    {
                        // Kill hung process
                        process.Kill();
                    }
                    catch
                    {
                    }
                }
            }
        }

        return(result);
    }
Ejemplo n.º 41
0
        public void SubmitTraces(string packageVersion, bool enableCallTarget)
        {
            List <MockTracerAgent.Span> spans = null;

            try
            {
                SetCallTargetSettings(enableCallTarget);
                SetEnvironmentVariable("DD_TRACE_DEBUG", "1");
                SetEnvironmentVariable("DD_DUMP_ILREWRITE_ENABLED", "1");

                int agentPort = TcpPortProvider.GetOpenPort();

                using (var agent = new MockTracerAgent(agentPort))
                    using (ProcessResult processResult = RunDotnetTestSampleAndWaitForExit(agent.Port, packageVersion: packageVersion))
                    {
                        spans = agent.WaitForSpans(ExpectedSpanCount)
                                .Where(s => !(s.Tags.TryGetValue(Tags.InstrumentationName, out var sValue) && sValue == "HttpMessageHandler"))
                                .ToList();

                        // Check the span count
                        Assert.Equal(ExpectedSpanCount, spans.Count);

                        // ***************************************************************************
                        // the following is a temporal skip to avoid flakiness on xunit 2.2.0 version
                        if (spans.Count == 0 && packageVersion == "2.2.0")
                        {
                            return;
                        }

                        // ***************************************************************************

                        foreach (var targetSpan in spans)
                        {
                            // check the name
                            Assert.Equal("xunit.test", targetSpan.Name);

                            // check the CIEnvironmentValues decoration.
                            CheckCIEnvironmentValuesDecoration(targetSpan);

                            // check the runtime values
                            CheckRuntimeValues(targetSpan);

                            // check the suite name
                            AssertTargetSpanEqual(targetSpan, TestTags.Suite, TestSuiteName);

                            // check the test type
                            AssertTargetSpanEqual(targetSpan, TestTags.Type, TestTags.TypeTest);

                            // check the test framework
                            AssertTargetSpanContains(targetSpan, TestTags.Framework, "xUnit");

                            // check the version
                            AssertTargetSpanEqual(targetSpan, "version", "1.0.0");

                            // checks the origin tag
                            CheckOriginTag(targetSpan);

                            // Check the Environment
                            AssertTargetSpanEqual(targetSpan, Tags.Env, "integration_tests");

                            // check specific test span
                            switch (targetSpan.Tags[TestTags.Name])
                            {
                            case "SimplePassTest":
                                CheckSimpleTestSpan(targetSpan);
                                break;

                            case "SimpleSkipFromAttributeTest":
                                CheckSimpleSkipFromAttributeTest(targetSpan);
                                break;

                            case "SimpleErrorTest":
                                CheckSimpleErrorTest(targetSpan);
                                break;

                            case "TraitPassTest":
                                CheckSimpleTestSpan(targetSpan);
                                CheckTraitsValues(targetSpan);
                                break;

                            case "TraitSkipFromAttributeTest":
                                CheckSimpleSkipFromAttributeTest(targetSpan);
                                CheckTraitsValues(targetSpan);
                                break;

                            case "TraitErrorTest":
                                CheckSimpleErrorTest(targetSpan);
                                CheckTraitsValues(targetSpan);
                                break;

                            case "SimpleParameterizedTest":
                                CheckSimpleTestSpan(targetSpan);
                                AssertTargetSpanAnyOf(
                                    targetSpan,
                                    TestTags.Parameters,
                                    "{\"metadata\":{\"test_name\":\"Samples.XUnitTests.TestSuite.SimpleParameterizedTest(xValue: 1, yValue: 1, expectedResult: 2)\"},\"arguments\":{\"xValue\":\"1\",\"yValue\":\"1\",\"expectedResult\":\"2\"}}",
                                    "{\"metadata\":{\"test_name\":\"Samples.XUnitTests.TestSuite.SimpleParameterizedTest(xValue: 2, yValue: 2, expectedResult: 4)\"},\"arguments\":{\"xValue\":\"2\",\"yValue\":\"2\",\"expectedResult\":\"4\"}}",
                                    "{\"metadata\":{\"test_name\":\"Samples.XUnitTests.TestSuite.SimpleParameterizedTest(xValue: 3, yValue: 3, expectedResult: 6)\"},\"arguments\":{\"xValue\":\"3\",\"yValue\":\"3\",\"expectedResult\":\"6\"}}",
                                    "{\"metadata\":{\"test_name\":\"SimpleParameterizedTest(xValue: 1, yValue: 1, expectedResult: 2)\"},\"arguments\":{\"xValue\":\"1\",\"yValue\":\"1\",\"expectedResult\":\"2\"}}",
                                    "{\"metadata\":{\"test_name\":\"SimpleParameterizedTest(xValue: 2, yValue: 2, expectedResult: 4)\"},\"arguments\":{\"xValue\":\"2\",\"yValue\":\"2\",\"expectedResult\":\"4\"}}",
                                    "{\"metadata\":{\"test_name\":\"SimpleParameterizedTest(xValue: 3, yValue: 3, expectedResult: 6)\"},\"arguments\":{\"xValue\":\"3\",\"yValue\":\"3\",\"expectedResult\":\"6\"}}");
                                break;

                            case "SimpleSkipParameterizedTest":
                                CheckSimpleSkipFromAttributeTest(targetSpan);
                                // On callsite the parameters tags are being sent with no parameters, this is not required due the whole test is skipped.
                                // That behavior has changed in calltarget.
                                if (!enableCallTarget)
                                {
                                    AssertTargetSpanAnyOf(
                                        targetSpan,
                                        TestTags.Parameters,
                                        "{\"metadata\":{\"test_name\":\"Samples.XUnitTests.TestSuite.SimpleSkipParameterizedTest\"},\"arguments\":{\"xValue\":\"(default)\",\"yValue\":\"(default)\",\"expectedResult\":\"(default)\"}}",
                                        "{\"metadata\":{\"test_name\":\"SimpleSkipParameterizedTest\"},\"arguments\":{\"xValue\":\"(default)\",\"yValue\":\"(default)\",\"expectedResult\":\"(default)\"}}");
                                }

                                break;

                            case "SimpleErrorParameterizedTest":
                                CheckSimpleErrorTest(targetSpan);
                                AssertTargetSpanAnyOf(
                                    targetSpan,
                                    TestTags.Parameters,
                                    "{\"metadata\":{\"test_name\":\"Samples.XUnitTests.TestSuite.SimpleErrorParameterizedTest(xValue: 1, yValue: 0, expectedResult: 2)\"},\"arguments\":{\"xValue\":\"1\",\"yValue\":\"0\",\"expectedResult\":\"2\"}}",
                                    "{\"metadata\":{\"test_name\":\"Samples.XUnitTests.TestSuite.SimpleErrorParameterizedTest(xValue: 2, yValue: 0, expectedResult: 4)\"},\"arguments\":{\"xValue\":\"2\",\"yValue\":\"0\",\"expectedResult\":\"4\"}}",
                                    "{\"metadata\":{\"test_name\":\"Samples.XUnitTests.TestSuite.SimpleErrorParameterizedTest(xValue: 3, yValue: 0, expectedResult: 6)\"},\"arguments\":{\"xValue\":\"3\",\"yValue\":\"0\",\"expectedResult\":\"6\"}}",
                                    "{\"metadata\":{\"test_name\":\"SimpleErrorParameterizedTest(xValue: 1, yValue: 0, expectedResult: 2)\"},\"arguments\":{\"xValue\":\"1\",\"yValue\":\"0\",\"expectedResult\":\"2\"}}",
                                    "{\"metadata\":{\"test_name\":\"SimpleErrorParameterizedTest(xValue: 2, yValue: 0, expectedResult: 4)\"},\"arguments\":{\"xValue\":\"2\",\"yValue\":\"0\",\"expectedResult\":\"4\"}}",
                                    "{\"metadata\":{\"test_name\":\"SimpleErrorParameterizedTest(xValue: 3, yValue: 0, expectedResult: 6)\"},\"arguments\":{\"xValue\":\"3\",\"yValue\":\"0\",\"expectedResult\":\"6\"}}");
                                break;
                            }

                            // check remaining tag (only the name)
                            Assert.Single(targetSpan.Tags);
                        }
                    }
            }
            catch
            {
                WriteSpans(spans);
                throw;
            }
        }
Ejemplo n.º 42
0
        public string GetCode(Type type)
        {
            var result = new ProcessResult();

            return(templateEngine.GetViewModelCode(type));
        }
Ejemplo n.º 43
0
 private static void VerifyResult(ProcessResult result)
 {
     Assert.Equal("", result.Output);
     Assert.Equal("", result.Errors);
     Assert.Equal(0, result.ExitCode);
 }
Ejemplo n.º 44
0
        public static async Task <ProcessResult> RunProcessAsync(string command, string arguments, string workingdir, int timeout)
        {
            var result = new ProcessResult();

            using (var process = new Process())
            {
                process.StartInfo.FileName               = command;
                process.StartInfo.Arguments              = arguments;
                process.StartInfo.WorkingDirectory       = workingdir;
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.CreateNoWindow         = true;

                var outputBuilder    = new StringBuilder();
                var outputCloseEvent = new TaskCompletionSource <bool>();

                process.OutputDataReceived += (s, e) =>
                {
                    if (e.Data == null)
                    {
                        outputCloseEvent.SetResult(true);
                    }
                    else
                    {
                        outputBuilder.Append(e.Data);
                        outputBuilder.Append('\n');
                    }
                };

                var errorBuilder    = new StringBuilder();
                var errorCloseEvent = new TaskCompletionSource <bool>();

                process.ErrorDataReceived += (s, e) =>
                {
                    if (e.Data == null)
                    {
                        errorCloseEvent.SetResult(true);
                    }
                    else
                    {
                        errorBuilder.Append(e.Data);
                        errorBuilder.Append('\n');
                    }
                };

                var isStarted = process.Start();
                if (!isStarted)
                {
                    result.ExitCode = process.ExitCode;
                    return(result);
                }

                // Reads the output stream first and then waits because deadlocks are possible
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                // Creates task to wait for process exit using timeout
                var waitForExit = WaitForExitAsync(process, timeout);

                // Create task to wait for process exit and closing all output streams
                var processTask = Task.WhenAll(waitForExit, outputCloseEvent.Task, errorCloseEvent.Task);

                // Waits process completion and then checks it was not completed by timeout
                if (await Task.WhenAny(Task.Delay(timeout), processTask) == processTask && waitForExit.Result)
                {
                    result.ExitCode = process.ExitCode;
                    result.Output   = outputBuilder.ToString();
                    result.Error    = errorBuilder.ToString();
                }
                else
                {
                    try
                    {
                        // Kill hung process
                        process.Kill();
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 45
0
            // Returns 0 on success, 1 on failure.
            public static int DiffCommand(Config config)
            {
                DiffTool diffTool   = NewDiffTool(config);
                string   diffString = $"{diffTool.Name} {config.Metric} Diffs for ";
                bool     needPrefix = false;

                if (config.CoreLib)
                {
                    diffString += "System.Private.CoreLib.dll";
                    needPrefix  = true;
                }
                else if (config.DoFrameworks)
                {
                    diffString += "System.Private.CoreLib.dll, framework assemblies";
                    needPrefix  = true;
                }

                if (config.Benchmarks)
                {
                    if (needPrefix)
                    {
                        diffString += ", ";
                    }
                    diffString += "benchstones and benchmarks game in " + config.TestRoot;
                    needPrefix  = true;
                }
                else if (config.DoTestTree)
                {
                    if (needPrefix)
                    {
                        diffString += ", ";
                    }
                    diffString += "assemblies in " + config.TestRoot;
                    needPrefix  = true;
                }

                foreach (string assembly in config.AssemblyList)
                {
                    if (needPrefix)
                    {
                        diffString += ", ";
                    }
                    diffString += assembly;
                    needPrefix  = true;
                }

                Console.WriteLine($"Beginning {diffString}");

                // Create subjob that runs jit-dasm or jit-dasm-pmi (which should be in path)
                // with the relevent coreclr assemblies/paths.

                List <string> commandArgs = new List <string>();

                commandArgs.Add("--platform");
                commandArgs.Add(config.CoreRoot);

                if (config.GenerateGCInfo)
                {
                    commandArgs.Add("--gcinfo");
                }

                if (config.Tier0)
                {
                    commandArgs.Add("--tier0");
                    diffString += " [tier0]";
                }

                if (config.GenerateDebugInfo)
                {
                    commandArgs.Add("--debuginfo");
                }

                if (config.Verbose)
                {
                    commandArgs.Add("--verbose");
                }

                if (config.AltJit != null)
                {
                    commandArgs.Add("--altjit");
                    commandArgs.Add(config.AltJit);
                }

                if ((config.DoCommand == Commands.PmiDiff) && config.Cctors)
                {
                    commandArgs.Add("--cctors");
                    diffString += " [invoking .cctors]";
                }

                DateTime            startTime        = DateTime.Now;
                List <AssemblyInfo> assemblyWorkList = GenerateAssemblyWorklist(config);
                DasmResult          dasmResult       = diffTool.RunDasmTool(commandArgs, assemblyWorkList);

                Console.WriteLine($"Completed {diffString} in {(DateTime.Now - startTime).TotalSeconds:F2}s");
                string basePath = Path.Combine(config.OutputPath, "base");
                string diffPath = Path.Combine(config.OutputPath, "diff");

                Console.WriteLine($"Diffs (if any) can be viewed by comparing: {basePath} {diffPath}");
                Console.WriteLine("");
                Console.WriteLine($"git diff --no-index --diff-filter=M --exit-code --numstat {diffPath} {basePath}");
                Console.WriteLine("");

                // Analyze completed run.

                if (config.DoAnalyze && config.DoDiffCompiles && config.DoBaseCompiles)
                {
                    List <string> analysisArgs = new List <string>();

                    analysisArgs.Add("--base");
                    analysisArgs.Add(Path.Combine(config.OutputPath, "base"));
                    analysisArgs.Add("--diff");
                    analysisArgs.Add(Path.Combine(config.OutputPath, "diff"));
                    analysisArgs.Add("--count");
                    analysisArgs.Add(config.Count.ToString());
                    analysisArgs.Add("--recursive");
                    analysisArgs.Add("--metric");
                    analysisArgs.Add(config.Metric);
                    analysisArgs.Add("--note");

                    string jitName = config.AltJit ?? "default jit";
                    analysisArgs.Add($"\"{diffString} for {config.Arch} {jitName}\"");

                    if (config.tsv)
                    {
                        analysisArgs.Add("--tsv");
                        analysisArgs.Add(Path.Combine(config.OutputPath, "diffs.tsv"));
                    }

                    if (config.Verbose)
                    {
                        Console.WriteLine("Analyze command: {0} {1}",
                                          s_analysisTool, String.Join(" ", analysisArgs));
                    }

                    Console.WriteLine($"Analyzing {config.Metric} diffs...");
                    startTime = DateTime.Now;
                    ProcessResult analyzeResult = Utility.ExecuteProcess(s_analysisTool, analysisArgs);
                    Console.WriteLine($"Completed analysis in {(DateTime.Now - startTime).TotalSeconds:F2}s");
                }

                // Report any failures to generate asm at the very end (again). This is so
                // this information doesn't get buried in previous output.

                if (!dasmResult.Success)
                {
                    Console.Error.WriteLine("");
                    Console.Error.WriteLine("Warning: Failures detected generating asm: {0} base, {1} diff{2}",
                                            dasmResult.BaseErrors, dasmResult.DiffErrors, (dasmResult.CaughtException ? ", exception occurred" : ""));

                    return(1); // failure result
                }
                else
                {
                    return(0); // success result
                }
            }
Ejemplo n.º 46
0
        /// <summary>
        /// This pass only does edge splits. Returns number of split edges.
        /// Tracks previously-split
        /// </summary>
        public int FastSplitIteration()
        {
            if (mesh.TriangleCount == 0)    // badness if we don't catch this...
            {
                return(0);
            }

            PushState();
            EnableFlips    = EnableCollapses = EnableSmoothing = false;
            ProjectionMode = TargetProjectionMode.NoProjection;

            begin_pass();

            // Iterate over all edges in the mesh at start of pass.
            // Some may be removed, so we skip those.
            // However, some old eid's may also be re-used, so we will touch
            // some new edges. Can't see how we could efficiently prevent this.
            //
            begin_ops();

            IEnumerable <int> edgesItr = EdgesIterator();

            if (modified_edges == null)
            {
                modified_edges = new HashSet <int>();
            }
            else
            {
                edges_buffer.Clear(); edges_buffer.AddRange(modified_edges);
                edgesItr = edges_buffer;
                modified_edges.Clear();
            }

            int startEdges = Mesh.EdgeCount;
            int splitEdges = 0;

            // When we split an edge, we need to check it and the adjacent ones we added.
            // Because of overhead in ProcessEdge, it is worth it to do a distance-check here
            double max_edge_len_sqr = MaxEdgeLength * MaxEdgeLength;

            SplitF = (edgeID, a, b, vNew) => {
                Vector3d v = Mesh.GetVertex(vNew);
                foreach (int eid in Mesh.VtxEdgesItr(vNew))
                {
                    Index2i ev       = Mesh.GetEdgeV(eid);
                    int     othervid = (ev.a == vNew) ? ev.b : ev.a;
                    if (mesh.GetVertex(othervid).DistanceSquared(ref v) > max_edge_len_sqr)
                    {
                        queue_edge(eid);
                    }
                }
                //queue_one_ring(vNew);
            };


            ModifiedEdgesLastPass = 0;
            int processedLastPass = 0;

            foreach (int cur_eid in edgesItr)
            {
                if (Cancelled())
                {
                    goto abort_compute;
                }

                if (mesh.IsEdge(cur_eid))
                {
                    Index2i ev = mesh.GetEdgeV(cur_eid);
                    Index2i ov = mesh.GetEdgeOpposingV(cur_eid);

                    processedLastPass++;
                    ProcessResult result = ProcessEdge(cur_eid);
                    if (result == ProcessResult.Ok_Split)
                    {
                        // new edges queued by SplitF
                        ModifiedEdgesLastPass++;
                        splitEdges++;
                    }
                }
            }
            end_ops();

            //System.Console.WriteLine("FastSplitIteration: start {0}  end {1}  processed: {2}   modified: {3}  queue: {4}",
            //    startEdges, Mesh.EdgeCount, processedLastPass, ModifiedEdgesLastPass, modified_edges.Count);

abort_compute:
            SplitF = null;
            PopState();

            end_pass();

            return(splitEdges);
        }
Ejemplo n.º 47
0
 /// <summary>
 /// process remove
 /// </summary>
 /// <param name="selector">regex replace selector</param>
 /// <param name="result">pre process result</param>
 /// <returns>new process result</returns>
 public override ProcessResult ProcessRemove(RegexReplaceSelector selector, ProcessResult result)
 {
     return(ProcessNeed(selector, result));
 }
Ejemplo n.º 48
0
        public virtual void RemeshIteration()
        {
            if (mesh.TriangleCount == 0)    // badness if we don't catch this...
            {
                return;
            }

            begin_pass();

            // Iterate over all edges in the mesh at start of pass.
            // Some may be removed, so we skip those.
            // However, some old eid's may also be re-used, so we will touch
            // some new edges. Can't see how we could efficiently prevent this.
            //
            begin_ops();

            IEnumerable <int> edgesItr = EdgesIterator();

            if (modified_edges == null)
            {
                modified_edges = new HashSet <int>();
            }
            else
            {
                edges_buffer.Clear(); edges_buffer.AddRange(modified_edges);
                edgesItr = edges_buffer;
                modified_edges.Clear();
            }

            int startEdges = Mesh.EdgeCount;
            int flips = 0, splits = 0, collapes = 0;

            ModifiedEdgesLastPass = 0;
            int processedLastPass = 0;

            foreach (int cur_eid in edgesItr)
            {
                if (Cancelled())
                {
                    return;
                }

                if (mesh.IsEdge(cur_eid))
                {
                    Index2i ev = mesh.GetEdgeV(cur_eid);
                    Index2i ov = mesh.GetEdgeOpposingV(cur_eid);

                    // TODO: optimize the queuing here, are over-doing it!
                    // TODO: be able to queue w/o flip (eg queue from smooth never requires flip check)

                    processedLastPass++;
                    ProcessResult result = ProcessEdge(cur_eid);
                    if (result == ProcessResult.Ok_Collapsed)
                    {
                        queue_one_ring(ev.a); queue_one_ring(ev.b);
                        queue_one_ring(ov.a); queue_one_ring(ov.b);
                        ModifiedEdgesLastPass++;
                        collapes++;
                    }
                    else if (result == ProcessResult.Ok_Split)
                    {
                        queue_one_ring(ev.a); queue_one_ring(ev.b);
                        queue_one_ring(ov.a); queue_one_ring(ov.b);
                        ModifiedEdgesLastPass++;
                        splits++;
                    }
                    else if (result == ProcessResult.Ok_Flipped)
                    {
                        queue_one_ring(ev.a); queue_one_ring(ev.b);
                        queue_one_ring(ov.a); queue_one_ring(ov.b);
                        ModifiedEdgesLastPass++;
                        flips++;
                    }
                }
            }
            end_ops();

            //System.Console.WriteLine("RemeshIteration: start {0}  end {1}  processed: {2}   modified: {3}  queue: {4}",
            //    startEdges, Mesh.EdgeCount, processedLastPass, ModifiedEdgesLastPass, modified_edges.Count);
            //System.Console.WriteLine("   flips {0}  splits {1}  collapses {2}", flips, splits, collapes);

            if (Cancelled())
            {
                return;
            }

            begin_smooth();
            if (EnableSmoothing && SmoothSpeedT > 0)
            {
                TrackedSmoothPass(EnableParallelSmooth);
                DoDebugChecks();
            }
            end_smooth();

            if (Cancelled())
            {
                return;
            }

            begin_project();
            if (ProjectionTarget != null && ProjectionMode == TargetProjectionMode.AfterRefinement)
            {
                //FullProjectionPass();

                if (UseFaceAlignedProjection)
                {
                    for (int i = 0; i < FaceProjectionPassesPerIteration; ++i)
                    {
                        TrackedFaceProjectionPass();
                    }
                }
                else
                {
                    TrackedProjectionPass(EnableParallelProjection);
                }
                DoDebugChecks();
            }
            end_project();

            end_pass();
        }
Ejemplo n.º 49
0
        public override string GetOSVersionInformation()
        {
            ProcessResult result = ProcessHelper.Run("sw_vers", args: string.Empty, redirectOutput: true);

            return(string.IsNullOrWhiteSpace(result.Output) ? result.Errors : result.Output);
        }
Ejemplo n.º 50
0
        private static void PrintStdOutAndErr(Tye.Hosting.Model.Service service, string replica, ProcessResult result)
        {
            if (result.ExitCode != 0)
            {
                if (result.StandardOutput != null)
                {
                    service.Logs.OnNext($"[{replica}]: {result.StandardOutput}");
                }

                if (result.StandardError != null)
                {
                    service.Logs.OnNext($"[{replica}]: {result.StandardError}");
                }
            }
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Realiza el registro de un de Parametro Valor
        /// </summary>
        /// <param name="filtro">Parametro Valor a Registrar</param>
        /// <returns>Indicador de Error</returns>
        public ProcessResult <string> RegistrarParametroValor(ParametroValorRequest filtro)
        {
            string result           = "0";
            var    resultadoProceso = new ProcessResult <string>();

            try
            {
                var listSecciones = parametroSeccionService.BuscarParametroSeccion(new ParametroSeccionRequest()
                {
                    CodigoParametro = filtro.CodigoParametro
                }).Result;

                int  codigoValor     = 0;
                bool isActualizacion = false;

                if (filtro.CodigoValor == null)
                {
                    var ultimoParametroValor = BuscarParametroValor(new ParametroValorRequest()
                    {
                        CodigoParametro = filtro.CodigoParametro,
                        EstadoRegistro  = null
                    }).Result.OrderBy(itemOrderBy => itemOrderBy.CodigoValor).LastOrDefault();

                    if (ultimoParametroValor != null)
                    {
                        codigoValor = ultimoParametroValor.CodigoValor + 1;
                    }
                    else
                    {
                        codigoValor = 1;
                    }
                }
                else
                {
                    codigoValor     = (int)filtro.CodigoValor;
                    isActualizacion = true;
                }

                using (TransactionScope scope = new TransactionScope())
                {
                    try
                    {
                        foreach (var item in filtro.RegistroCadena)
                        {
                            bool isSeccionExistente = false;

                            var seccionActual = listSecciones.Where(itemWhere => itemWhere.CodigoSeccion.ToString() == item.Key).FirstOrDefault();

                            ParametroValorResponse parametroValorActual = null;

                            if (isActualizacion)
                            {
                                parametroValorActual = BuscarParametroValor(new ParametroValorRequest()
                                {
                                    CodigoParametro = filtro.CodigoParametro,
                                    CodigoSeccion   = seccionActual.CodigoSeccion,
                                    CodigoValor     = codigoValor
                                }).Result.FirstOrDefault();

                                isSeccionExistente = (parametroValorActual != null) ? true : false;
                            }

                            string value = "";

                            switch (seccionActual.CodigoTipoDato)
                            {
                            case "ENT":
                                value = item.Value;
                                break;

                            case "DEC":
                                value = item.Value.Replace(',', '.');
                                break;

                            case "FEC":
                                value = item.Value;
                                break;

                            default:
                                value = item.Value;
                                break;
                            }

                            ParametroValorLogic logic = new ParametroValorLogic();
                            logic.CodigoParametro = (int)filtro.CodigoParametro;
                            logic.CodigoSeccion   = seccionActual.CodigoSeccion;
                            logic.CodigoValor     = codigoValor;
                            logic.Valor           = value;

                            if (!isActualizacion || !isSeccionExistente)
                            {
                                logic.EstadoRegistro = DatosConstantes.EstadoRegistro.Activo;

                                if (parametroValorLogicRepository.RegistrarParametroValor(logic) <= 0)
                                {
                                    throw new Exception();
                                }
                            }
                            else
                            {
                                logic.EstadoRegistro = null;

                                if (parametroValorLogicRepository.ModificarParametroValor(logic) <= 0)
                                {
                                    throw new Exception();
                                }
                            }
                        }

                        scope.Complete();

                        resultadoProceso.Result    = "1";
                        resultadoProceso.IsSuccess = true;
                    }
                    catch (Exception e)
                    {
                        scope.Dispose();
                        throw e;
                    }
                }
            }
            catch (Exception)
            {
                result = "-1";
                resultadoProceso.Result    = result;
                resultadoProceso.IsSuccess = false;
            }
            return(resultadoProceso);
        }
        public async Task StartOrchestratorScheduler(
            [OrchestrationTrigger]
            IDurableOrchestrationContext context,
            ILogger log)
        {
            var taskItem = context.GetInput <TaskItem>();

            if (taskItem == null)
            {
                var error = new ProcessResult {
                    Sucess = false, Information = "Error getting task information"
                };
                AddLog(log, error);
                return;
            }
            TaskTypeEnum taskType = (TaskTypeEnum)taskItem.TaskType;

            string prepare  = ActivityFunctionPrepare(taskType);
            string process  = ActivityFunctionProcess(taskType);
            string complete = ActivityFunctionComplete(taskType);


            double secondInAFullDay = 86400;



            //// hvordan tjekker vi at task'en ikke allerde er scheduleret ?
            //// i så fald skal den terminineres.

            var      date            = context.CurrentUtcDateTime.Hour > taskItem.MonitorHour ? context.CurrentUtcDateTime.AddDays(1) : context.CurrentUtcDateTime;
            var      nextTime        = new DateTime(date.Year, date.Month, date.Day, taskItem.MonitorHour, 0, 0);
            var      pollingInterval = nextTime.Subtract(context.CurrentUtcDateTime).TotalSeconds;
            DateTime expiryTime      = new DateTime(3000, 1, 1);

            while (context.CurrentUtcDateTime < expiryTime)
            {
                // Orchestration sleeps until this time.
                var nextCheck = context.CurrentUtcDateTime.AddSeconds(pollingInterval);
                await context.CreateTimer(nextCheck, CancellationToken.None);

                var resultPrepare = await context.CallActivityAsync <ProcessResult>(prepare, taskItem.CustomerId);

                AddLog(log, resultPrepare);

                if (resultPrepare.Sucess)
                {
                    var resultProcess = await context.CallActivityAsync <ProcessResult>(process, taskItem.CustomerId);

                    AddLog(log, resultProcess);

                    if (resultProcess.Sucess)
                    {
                        var resultComplete = await context.CallActivityAsync <ProcessResult>(complete, taskItem.CustomerId);

                        AddLog(log, resultComplete);
                    }
                }
                // her sikres at denne uendelig løkke, ikke medfører at durable storage account fyldes op.
                context.ContinueAsNew(null); // her har man mulighed for at have informationer til næste genneløb
                pollingInterval = secondInAFullDay;
            }
        }
Ejemplo n.º 53
0
        private void CryptoObfuscate(string file, string signatureFileName, bool testLoad = false, bool debug = false, bool renameSymbols = false, bool embed = false)
        {
            bool isProgram = Path.GetExtension(file).ToLower() == ".exe";

            if (!isProgram && embed)
            {
                return;
            }

            SystemConsole.Write("Obfuscate <cyan>{0}<default>...", Path.GetFileName(file));
            Stopwatch watch      = Stopwatch.StartNew();
            string    @namespace = ".";

            string sourceDir  = Path.GetDirectoryName(file);
            string workDir    = FileSystem.Combine(sourceDir, "tmp");
            string obprojFile = FileSystem.Combine(workDir, Path.GetFileName(file) + ".obproj");

            Directory.CreateDirectory(workDir);

            using (StreamWriter writer = File.CreateText(obprojFile))
            {
                writer.WriteLine($"<Project ProjectFileVersion=\"4\" UseRelativePaths=\"True\" CheckVersionsWhileResolvingAssemblies=\"True\" DisabledFromMSBuild=\"False\" ID=\"" + Guid.NewGuid() + "\">");
                writer.WriteLine($"  <SearchDirectories />");//{Path.GetFileNameWithoutExtension(file)}
                writer.WriteLine($"  <OutputSettings OutputPath=\"{workDir}\" MainAssemblyPath=\"{workDir}\" OverwriteInputFiles=\"False\">");
                writer.WriteLine($"  </OutputSettings>");
                writer.WriteLine($"  <ObfuscationSettings RenamingScheme=\"2\" UseOverloadedFieldNames=\"True\" UseOverloadedMethodNames=\"True\" HonorObfuscationAttributes=\"True\" ExcludeSerializedTypes=\"True\" ProcessInlineStrings=\"True\" ForceXAMLProcessingModeExclude=\"False\" ForceRenameParams=\"False\" EncryptionActive=\"True\" CompressionActive=\"True\" />");
                writer.WriteLine($"  <Assembly Load=\"true\" Path=\"{file}\" KeyFilePath=\"{signatureFileName}\" KeyFileContainsPublicKeyOnly=\"False\" Rfc3161TimestampURL=\"False\" Embed=\"True\" AddExceptionReporting=\"False\" IsWinRTAssembly=\"False\">");
                writer.WriteLine($"    <ObfuscationSettings EncryptStrings=\"True\" EncryptMethods=\"True\" EncryptConstants=\"True\" SuppressReflector=\"{isProgram}\" ReduceMetaData=\"{isProgram}\" ObfuscationDisposition=\"1\" FlowObfuscation=\"1\" CodeMasking=\"0\" SuppressILDASM=\"True\" SuppressReflection=\"False\" CombineResources=\"True\" EncryptResources=\"True\" CompressResources=\"True\" MarkAsSealed=\"{isProgram}\" EnableTamperDetection=\"True\" EnableAntiDebugging=\"{isProgram}\" SymbolRenaming=\"{renameSymbols}\" HideExternalCalls=\"True\" HideInternalCalls=\"True\" GeneratePdbFile=\"False\" ObfuscatePdbFileNames=\"False\" IncludeLocalVariablesInPdbFile=\"True\" Encrypt=\"{isProgram}\" Compress=\"{isProgram}\" MSBuild=\"False\" ObfuscatedNamespace=\"{@namespace}\" RetainNamespace=\"False\" ModuleInitializationMethod=\"\" LicensingMerge=\"False\" RemoveConstants=\"{isProgram}\">");
                writer.WriteLine($"    </ObfuscationSettings>");
                writer.WriteLine($"  </Assembly>");
                if (embed)
                {
                    foreach (string dll in Directory.GetFiles(Path.GetDirectoryName(file), "*.dll"))
                    {
                        writer.WriteLine($"  <Assembly Load=\"true\" Path=\"{dll}\" KeyFilePath=\"{signatureFileName}\" KeyFileContainsPublicKeyOnly=\"False\" Rfc3161TimestampURL=\"False\" Embed=\"True\" AddExceptionReporting=\"False\" IsWinRTAssembly=\"False\">");
                        writer.WriteLine($"    <ObfuscationSettings EncryptStrings=\"True\" EncryptMethods=\"True\" EncryptConstants=\"True\" SuppressReflector=\"{isProgram}\" ReduceMetaData=\"{isProgram}\" ObfuscationDisposition=\"1\" FlowObfuscation=\"1\" CodeMasking=\"0\" SuppressILDASM=\"True\" SuppressReflection=\"False\" CombineResources=\"True\" EncryptResources=\"True\" CompressResources=\"True\" MarkAsSealed=\"{isProgram}\" EnableTamperDetection=\"True\" EnableAntiDebugging=\"{isProgram}\" SymbolRenaming=\"{renameSymbols}\" HideExternalCalls=\"True\" HideInternalCalls=\"True\" GeneratePdbFile=\"False\" ObfuscatePdbFileNames=\"False\" IncludeLocalVariablesInPdbFile=\"True\" Encrypt=\"{isProgram}\" Compress=\"{isProgram}\" MSBuild=\"False\" ObfuscatedNamespace=\"{@namespace}\" RetainNamespace=\"False\" ModuleInitializationMethod=\"\" LicensingMerge=\"False\" RemoveConstants=\"{isProgram}\">");
                        writer.WriteLine($"    </ObfuscationSettings>");
                        writer.WriteLine($"  </Assembly>");
                    }
                }
                writer.WriteLine($"  <Warnings SaveWarningsToFile=\"\" FailOnUnsuppressedWarning=\"False\" SaveSuppressedWarnings=\"False\" SaveUnsuppressedWarnings=\"False\" />");
                writer.WriteLine($"</Project>");
            }
            ProcessResult result = Shell.FindAndRun("co", "Crypto Obfuscator", $"projectfile={obprojFile}");

            if (debug)
            {
                foreach (string line in result.Combined.SplitNewLine())
                {
                    if (line.Trim().Length > 0)
                    {
                        SystemConsole.WriteLine("D " + line.Trim());
                    }
                }
            }
            if (result.ExitCode != 0)
            {
                SystemConsole.WriteLine(" {0} <red>error", StringExtensions.FormatTime(watch.Elapsed));
                SystemConsole.WriteLine();
                foreach (string line in result.Combined.SplitNewLine())
                {
                    SystemConsole.WriteLine(new XTItem(XTColor.Red, XTStyle.Default, line));
                }
                throw new Exception("Obfuscation Exception");
            }
            SystemConsole.WriteLine(" {0} <green>ok", StringExtensions.FormatTime(watch.Elapsed));

            ObfucatorComplete(sourceDir, file, embed, testLoad);
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Gets the most recent folder version via Vault's versionhistory command.
        ///
        /// If we don't yet have a folder version, we need to get one so getSource and LabelSource have a version to work with,
        /// whether there's been changes or not.  (On a forced build or a multi-source control setup, we might get and/or label
        /// when there's been no change.)
        ///
        /// So if we have no folder version, we get the latest version of the folder via Vault's versionhistory command and see
        /// if the timestamp on that folder is more recent than the last build.  If we already have a folder version, we simply
        /// ask Vault to give us the most recent folder version after then one we already know about.
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        private bool GetFolderVersion(IIntegrationResult from, IIntegrationResult to)
        {
            bool bFoundChanges = false;

            // If we don't yet have a folder version, we need to just get the latest, rather than checking for a change.
            bool bForceGetLatestVersion = (_folderVersion == 0);

            // get version history
            ProcessResult result = ExecuteWithRetries(VersionHistoryProcessInfo(from, to, bForceGetLatestVersion));

            // parse out changes
            string      versionHistory    = Vault3.ExtractXmlFromOutput(result.StandardOutput);
            XmlDocument versionHistoryXml = new XmlDocument();

            versionHistoryXml.LoadXml(versionHistory);
            XmlNodeList versionNodeList   = versionHistoryXml.SelectNodes("/vault/history/item");
            XmlNode     folderVersionNode = null;

            if (bForceGetLatestVersion)
            {
                Debug.Assert(versionNodeList.Count == 1, "Attempted to retrieve folder's current version and got no results.");
                folderVersionNode = versionNodeList.Item(0);
            }
            else
            {
                Debug.Assert(versionNodeList.Count == 0 || versionNodeList.Count == 1, "Vault versionhistory -rowlimit 1 returned more than 1 row.");
                if (versionNodeList.Count == 1)
                {
                    folderVersionNode = versionNodeList.Item(0);
                    // We asked vault for only new folder versions, so if we got one, the folder has changed.
                    bFoundChanges = true;
                }
            }

            if (folderVersionNode != null)
            {
                if (bForceGetLatestVersion)
                {
                    // We asked Vault for the most recent folder version.  We have to check its date to
                    // see if this represents a change since the last integration.
                    XmlAttribute dateAttr = (XmlAttribute)folderVersionNode.Attributes.GetNamedItem("date");
                    Debug.Assert(dateAttr != null, "date attribute not found in version history");
                    DateTime dtLastChange = DateTime.Parse(dateAttr.Value, culture);
                    if (dtLastChange > from.StartTime)
                    {
                        bFoundChanges = true;
                    }
                }
                // get the new most recent folder version
                XmlAttribute versionAttr = (XmlAttribute)folderVersionNode.Attributes.GetNamedItem("version");
                Debug.Assert(versionAttr != null, "version attribute not found in version history");
                _folderVersion = long.Parse(versionAttr.Value);
                Log.Debug("Most recent folder version: " + _folderVersion);

                // get the new most recent TxId
                XmlAttribute txIdAttr = (XmlAttribute)folderVersionNode.Attributes.GetNamedItem("txid");
                Debug.Assert(txIdAttr != null, "txid attribute not found in version history");
                _lastTxID = long.Parse(txIdAttr.Value);
                Log.Debug("Most recent TxID: " + _lastTxID);
            }

            return(bFoundChanges);
        }
Ejemplo n.º 55
0
        private ProcessResult ProcessFile(string ifcFile, StreamWriter writer)
        {
            RemoveFiles(ifcFile);
            long geomTime = -1;  long parseTime = -1;
            using (EventTrace eventTrace = LoggerFactory.CreateEventTrace())
            {
                ProcessResult result = new ProcessResult() { Errors = -1 };
                try
                {

                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    using (XbimModel model = ParseModelFile(ifcFile,Params.Caching))
                    {
                        parseTime = watch.ElapsedMilliseconds;
                        string xbimFilename = BuildFileName(ifcFile, ".xbim");
                        //model.Open(xbimFilename, XbimDBAccess.ReadWrite);
                        //if (_params.GeometryV1)
                        //    XbimMesher.GenerateGeometry(model, Logger, null);
                        //else
                        //{
                            Xbim3DModelContext context = new Xbim3DModelContext(model);
                            context.CreateContext(XbimGeometryType.PolyhedronBinary);
                        //}
                        geomTime = watch.ElapsedMilliseconds - parseTime;
                        //XbimSceneBuilder sb = new XbimSceneBuilder();
                        //string xbimSceneName = BuildFileName(ifcFile, ".xbimScene");
                        //sb.BuildGlobalScene(model, xbimSceneName);
                       // sceneTime = watch.ElapsedMilliseconds - geomTime;
                        IIfcFileHeader header = model.Header;
                        watch.Stop();
                        IfcOwnerHistory ohs = model.Instances.OfType<IfcOwnerHistory>().FirstOrDefault();
                        result = new ProcessResult
                        {
                            ParseDuration = parseTime,
                            GeometryDuration = geomTime,
                           // SceneDuration = sceneTime,
                            FileName = ifcFile.Remove(0,Params.TestFileRoot.Length).TrimStart('\\'),
                            Entities = model.Instances.Count,
                            IfcSchema = header.FileSchema.Schemas.FirstOrDefault(),
                            IfcDescription = String.Format("{0}, {1}", header.FileDescription.Description.FirstOrDefault(), header.FileDescription.ImplementationLevel),
                            GeometryEntries = model.GeometriesCount,
                            IfcLength = ReadFileLength(ifcFile),
                            XbimLength = ReadFileLength(xbimFilename),
                           // SceneLength = ReadFileLength(xbimSceneName),
                            IfcProductEntries = model.Instances.CountOf<IfcProduct>(),
                            IfcSolidGeometries = model.Instances.CountOf<IfcSolidModel>(),
                            IfcMappedGeometries = model.Instances.CountOf<IfcMappedItem>(),
                            BooleanGeometries = model.Instances.CountOf<IfcBooleanResult>(),
                            Application = ohs == null ? "Unknown" : ohs.OwningApplication.ToString(),
                        };
                        model.Close();
                    }
                }

                catch (Exception ex)
                {
                    Logger.Error(String.Format("Problem converting file: {0}", ifcFile), ex);
                    result.Failed = true;
                }
                finally
                {
                    result.Errors = (from e in eventTrace.Events
                                     where (e.EventLevel == EventLevel.ERROR)
                                     select e).Count();
                    result.Warnings = (from e in eventTrace.Events
                                       where (e.EventLevel == EventLevel.WARN)
                                       select e).Count();
                    result.FileName = ifcFile.Remove(0, Params.TestFileRoot.Length).TrimStart('\\');
                    if (eventTrace.Events.Count > 0)
                    {
                        CreateLogFile(ifcFile, eventTrace.Events);
                    }

                    lock (thisLock)
                    {
                        writer.WriteLine(result.ToCsv());
                        writer.Flush();
                    }
                }
                return result;
            }
        }
Ejemplo n.º 56
0
        private void Obfuscar(string file, string signatureFile, bool testLoad, bool debug, bool embed = false)
        {
            bool isProgram = Path.GetExtension(file).ToLower() == ".exe";

            if (!isProgram && embed)
            {
                return;
            }

            SystemConsole.Write("Obfuscate <cyan>{0}<default>...", Path.GetFileName(file));
            Stopwatch watch = Stopwatch.StartNew();

            string sourceDir  = Path.GetDirectoryName(file);
            string workDir    = FileSystem.Combine(sourceDir, "tmp");
            string configFile = FileSystem.Combine(workDir, "obfuscar.xml");

            Directory.CreateDirectory(workDir);

            using (StreamWriter writer = File.CreateText(configFile))
            {
                writer.WriteLine($"<?xml version='1.0'?>");
                writer.WriteLine($"<Obfuscator>");
                writer.WriteLine($"<Var name=\"InPath\" value=\"{sourceDir}\" />");
                writer.WriteLine($"<Var name=\"OutPath\" value=\"{workDir}\" />");
                writer.WriteLine($"<Var name=\"HidePrivateApi\" value=\"true\" />");
                writer.WriteLine($"<Var name=\"KeepPublicApi\" value=\"true\" />");
                writer.WriteLine($"<Var name=\"KeyFile\" value=\"{signatureFile}\" />");
                writer.WriteLine($"<Var name=\"RegenerateDebugInfo\" value=\"true\" />");
                writer.WriteLine($"<Module file=\"{file}\" />");
                if (embed)
                {
                    foreach (string dll in Directory.GetFiles(Path.GetDirectoryName(file), "*.dll"))
                    {
                        writer.WriteLine($"<Module file=\"{dll}\" />");
                    }
                }
                writer.WriteLine($"</Obfuscator>");
            }
            ProcessResult result = Shell.FindAndRun("Obfuscar.Console", "Obfuscar Console", $"-s \"{configFile}\"");

            if (debug)
            {
                foreach (string line in result.Combined.SplitNewLine())
                {
                    if (line.Trim().Length > 0)
                    {
                        SystemConsole.WriteLine("D " + line.Trim());
                    }
                }
            }
            if (result.ExitCode != 0)
            {
                SystemConsole.WriteLine(" {0} <red>error", StringExtensions.FormatTime(watch.Elapsed));
                SystemConsole.WriteLine();
                foreach (string line in result.Combined.SplitNewLine())
                {
                    SystemConsole.WriteLine(new XTItem(XTColor.Red, XTStyle.Default, line));
                }
                throw new Exception("Obfuscation Exception");
            }
            SystemConsole.WriteLine(" {0} <green>ok", StringExtensions.FormatTime(watch.Elapsed));

            ObfucatorComplete(sourceDir, file, embed, testLoad);
        }
Ejemplo n.º 57
0
        private void VerifyResultAndOutput(ProcessResult result, TempDirectory path, string expectedOutput)
        {
            using (var resultFile = GetResultFile(path, "hello.exe"))
            {
                VerifyResult(result);

                var runningResult = RunCompilerOutput(resultFile);
                Assert.Equal(expectedOutput, runningResult.Output);
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Retorna el valor por defecto de las variables de sistema
        /// </summary>
        /// <param name="filtro">Datos de la variable de sistema</param>
        /// <returns>Retorna el valor por defecto</returns>
        public ProcessResult <string> ObtenerValorDefecto(ValorPorDefectoRequest filtro, UnidadOperativaResponse unidadOperativa)
        {
            var resultado = new ProcessResult <string>();

            try
            {
                switch (filtro.IdentificadorVariable)
                {
                case DatosConstantes.IdentificadorVariableDefecto.NumeroContrato:
                    resultado.Result = "";
                    break;

                case DatosConstantes.IdentificadorVariableDefecto.NombreProyecto:
                    resultado.Result = filtro.NombreUnidadOperativa;
                    break;

                case DatosConstantes.IdentificadorVariableDefecto.NombreEmpresa:
                case DatosConstantes.IdentificadorVariableDefecto.DniPrimerRepresentanteEmpresa:
                case DatosConstantes.IdentificadorVariableDefecto.PrimerRepresentanteEmpresa:
                case DatosConstantes.IdentificadorVariableDefecto.DniSegundoRepresentanteEmpresa:
                case DatosConstantes.IdentificadorVariableDefecto.SegundoRepresentanteEmpresa:
                    resultado.Result = ObtenerDatoUnidadOperativa(filtro.IdentificadorVariable, unidadOperativa);
                    break;

                case DatosConstantes.IdentificadorVariableDefecto.RucProveedor:
                    resultado.Result = filtro.RucProveedor;
                    break;

                case DatosConstantes.IdentificadorVariableDefecto.NombreProveedor:
                case DatosConstantes.IdentificadorVariableDefecto.ProveedorNombre:
                    resultado.Result = filtro.NombreProveedor;
                    break;

                case DatosConstantes.IdentificadorVariableDefecto.MonedaContrato:
                    resultado.Result = filtro.DescripcionMoneda;
                    break;

                case DatosConstantes.IdentificadorVariableDefecto.MontoContrato:
                    resultado.Result = filtro.MontoContratoString;
                    break;

                case DatosConstantes.IdentificadorVariableDefecto.PlazoVigenciaDesde:
                case DatosConstantes.IdentificadorVariableDefecto.FechaInicioContrato:
                    resultado.Result = filtro.FechaInicioContratoString;
                    break;

                case DatosConstantes.IdentificadorVariableDefecto.PlazoVigenciaHasta:
                case DatosConstantes.IdentificadorVariableDefecto.FechaFinContrato:
                    resultado.Result = filtro.FechaFinContratoString;
                    break;

                case DatosConstantes.IdentificadorVariableDefecto.FechaActual:
                    resultado.Result = DateTime.Today.ToString(DatosConstantes.Formato.FormatoFecha);
                    break;

                case DatosConstantes.IdentificadorVariableDefecto.FechaActualLetra:
                    resultado.Result = DateTime.Today.ToString(DatosConstantes.Formato.FormatoFecha);
                    break;

                default:
                    resultado.Result = "";
                    break;
                }
            }
            catch (Exception e)
            {
                resultado.IsSuccess = false;
                resultado.Exception = new ApplicationLayerException <VariableService>(e);
            }
            return(resultado);
        }
        /// <summary>
        ///     Install the dnscrypt-proxy service.
        /// </summary>
        /// <returns>A ProcessResult.</returns>
        public ProcessResult Install()
        {
            var processResult = new ProcessResult();
            try
            {
                if (!IsDnsCryptProxyInstalled())
                {
                    const bool actAsGateway = false;
                    const int timeout = 9000;

                    var arguments = "--install";
                    // update the registry
                    WriteRegistry(DnsCryptProxy.Type);

                    arguments += " -R \"" + DnsCryptProxy.Parameter.ResolverName + "\"";
                    arguments += " -L \"" +
                                 Path.Combine(Directory.GetCurrentDirectory(), Global.DnsCryptProxyFolder,
                                     Global.DnsCryptProxyResolverListName) + "\"";
                    if (actAsGateway)
                    {
                        arguments += " -a 0.0.0.0";
                    }
                    if (DnsCryptProxy.Type == DnsCryptProxyType.Primary)
                    {
                        arguments += " -a " + Global.PrimaryResolverAddress + ":" + Global.PrimaryResolverPort;
                    }
                    else
                    {
                        arguments += " -a " + Global.SecondaryResolverAddress + ":" + Global.SecondaryResolverPort;
                    }
                    // always use ephermeral keys
                    arguments += " -E";
                    using (var process = new Process())
                    {
                        process.StartInfo.FileName = Path.Combine(Directory.GetCurrentDirectory(),
                            Global.DnsCryptProxyFolder, Global.DnsCryptProxyExecutableName);
                        process.StartInfo.Arguments = arguments;
                        process.StartInfo.UseShellExecute = false;
                        process.StartInfo.CreateNoWindow = true;
                        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        process.StartInfo.RedirectStandardOutput = true;
                        process.StartInfo.RedirectStandardError = true;

                        var output = new StringBuilder();
                        var error = new StringBuilder();

                        using (var outputWaitHandle = new AutoResetEvent(false))
                        using (var errorWaitHandle = new AutoResetEvent(false))
                        {
                            process.OutputDataReceived += (sender, e) =>
                            {
                                if (e.Data == null)
                                {
                                    outputWaitHandle.Set();
                                }
                                else
                                {
                                    output.AppendLine(e.Data);
                                }
                            };
                            process.ErrorDataReceived += (sender, e) =>
                            {
                                if (e.Data == null)
                                {
                                    errorWaitHandle.Set();
                                }
                                else
                                {
                                    error.AppendLine(e.Data);
                                }
                            };
                            process.Start();
                            process.BeginOutputReadLine();
                            process.BeginErrorReadLine();
                            if (process.WaitForExit(timeout) &&
                                outputWaitHandle.WaitOne(timeout) &&
                                errorWaitHandle.WaitOne(timeout))
                            {
                                if (process.ExitCode == 0)
                                {
                                    ReadRegistry(DnsCryptProxy.Type);
                                    processResult.StandardOutput = output.ToString();
                                    processResult.StandardError = error.ToString();
                                    processResult.Success = true;
                                }
                                else
                                {
                                    processResult.StandardOutput = output.ToString();
                                    processResult.StandardError = error.ToString();
                                    processResult.Success = false;
                                }
                            }
                            else
                            {
                                // Timed out.
                                throw new Exception("Timed out");
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                processResult.StandardError = exception.Message;
                processResult.Success = false;
            }
            return processResult;
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Registrar Variable
        /// </summary>
        /// <param name="filtro">Variable a registrar</param>
        /// <returns>Indicador de conformidad
        /// 0: Registro satisfactorio
        /// 2: Identificador repetido
        /// 3: Nombre repetido
        /// -1: Ocurrio un Error Inesperado</returns>
        public ProcessResult <string> RegistrarVariable(VariableRequest filtro)
        {
            ProcessResult <string> resultado = new ProcessResult <string>();

            resultado.Result = "0";
            try
            {
                var listaVariable = BuscarVariable(new VariableRequest()
                {
                }).Result;

                //Validar si el Idetificador de la variable es repetido
                if (listaVariable.Any(itemAny => (filtro.CodigoVariable == null || new Guid(filtro.CodigoVariable) != itemAny.CodigoVariable) &&
                                      (filtro.IndicadorGlobal == true || itemAny.CodigoPlantilla == new Guid(filtro.CodigoPlantilla)) &&
                                      itemAny.Identificador == filtro.Identificador))
                {
                    resultado.Result    = "2";
                    resultado.IsSuccess = false;
                    return(resultado);
                }

                //Validar si el Nombre de la variable es repetido
                if (listaVariable.Any(itemAny => (filtro.CodigoVariable == null || new Guid(filtro.CodigoVariable) != itemAny.CodigoVariable) &&
                                      (filtro.IndicadorGlobal == true || itemAny.CodigoPlantilla == new Guid(filtro.CodigoPlantilla)) &&
                                      itemAny.Nombre == filtro.Nombre))
                {
                    resultado.Result    = "3";
                    resultado.IsSuccess = false;
                    return(resultado);
                }

                var entidad = VariableAdapter.ObtenerVariableEntityDesdeVariableRequest(filtro);


                if (filtro.CodigoVariable == null)
                {
                    variableEntityRepository.Insertar(entidad);

                    variableEntityRepository.GuardarCambios();
                    //Agregar una columna por default si es tabla
                    if (entidad.CodigoTipo == DatosConstantes.TipoVariable.Tabla)
                    {
                        var campo = new VariableCampoEntity();
                        campo.CodigoVariableCampo = Guid.NewGuid();
                        campo.CodigoVariable      = entidad.CodigoVariable;
                        campo.Nombre           = "Título";
                        campo.Orden            = 1;
                        campo.Tamanio          = 100;
                        campo.TipoAlineamiento = "center";
                        variableCampoEntityRepository.Insertar(campo);
                        variableCampoEntityRepository.GuardarCambios();
                    }
                }
                else
                {
                    var varibleActual = variableEntityRepository.GetById(entidad.CodigoVariable);
                    varibleActual.CodigoPlantilla          = entidad.CodigoPlantilla;
                    varibleActual.CodigoTipo               = entidad.CodigoTipo;
                    varibleActual.Identificador            = entidad.Identificador;
                    varibleActual.Nombre                   = entidad.Nombre;
                    varibleActual.IndicadorGlobal          = entidad.IndicadorGlobal;
                    varibleActual.Descripcion              = entidad.Descripcion;
                    varibleActual.IndicadorVariableSistema = entidad.IndicadorVariableSistema;
                    variableEntityRepository.Editar(varibleActual);

                    variableEntityRepository.GuardarCambios();
                }

                resultado.IsSuccess = true;
            }
            catch (Exception e)
            {
                resultado.Result    = "-1";
                resultado.IsSuccess = false;
                resultado.Exception = new ApplicationLayerException <VariableService>(e);
            }

            return(resultado);
        }