Ejemplo n.º 1
0
 public void CreateProcess_Should_Build_Process()
 {
     var subject = new Executable(_executablePath);
     subject.InWorkingDirectory("c:\\temp");
     var processWrapper = subject.CreateProcess();
     Assert.That(processWrapper, Is.Not.Null);
 }
Ejemplo n.º 2
0
		public BracketIndex(Expression root, Token bracketToken, Expression index, Executable owner)
			: base(root.FirstToken, owner)
		{
			this.Root = root;
			this.BracketToken = bracketToken;
			this.Index = index;
		}
Ejemplo n.º 3
0
        public ExecutableNodeFactory(Executable executable,Executables collection)
        {
            _collection = collection;
            _executable = (DtsContainer)executable;
            _host = _executable as TaskHost;
            _seq = _executable as Sequence;
            _foreachloop = _executable as ForEachLoop;
            _forloop = _executable as ForLoop;
            _psExecutable = PSObject.AsPSObject(_executable);

            if (null != _host)
            {
                _psExecutable.Properties.Add( new PSNoteProperty( "IsTaskHost", true ));
                _mainPipe = _host.InnerObject as MainPipe;
            }
            if (null != _mainPipe)
            {
                _psExecutable.Properties.Add(new PSNoteProperty("IsDataFlow", true));
            }
            if (null != _seq)
            {
                _psExecutable.Properties.Add(new PSNoteProperty("IsSequence", true));
            }
            if (null != _foreachloop)
            {
                _psExecutable.Properties.Add(new PSNoteProperty("IsForEachLoop", true));
            }
            if (null != _forloop)
            {
                _psExecutable.Properties.Add(new PSNoteProperty("IsForLoop", true));
            }
        }
Ejemplo n.º 4
0
 public int Executable(Action<Executable> args)
 {
     var implementation = new Executable();
     args(implementation);
     implementation.InternalExecute();
     return implementation.ExitCode;
 }
Ejemplo n.º 5
0
 public int Executable(Func<Executable, object> args)
 {
     var implementation = new Executable();
     args(implementation);
     implementation.InternalExecute();
     return implementation.ExitCode;
 }
Ejemplo n.º 6
0
		public Ternary(Expression condition, Expression trueValue, Expression falseValue, Executable owner)
			: base(condition.FirstToken, owner)
		{
			this.Condition = condition;
			this.TrueValue = trueValue;
			this.FalseValue = falseValue;
		}
Ejemplo n.º 7
0
    public Executable Trigger(Executable e)
    {
        if (!solved) {
            foreach (GameObject sobj in sObjects) {
                Solvable s = sobj.GetComponent(typeof(Solvable)) as Solvable;
                if (!s.solved) return null;
            }
            WrapperExec we = new WrapperExec("door_open");
            we.start = delegate {
                GameState.camCtrl.Focus(transform);
                Camera.mainCamera.audio.PlayOneShot(Resources.Load("audio/se/dooropen") as AudioClip);
                iTween.RotateAdd(gameObject, iTween.Hash(
                    "amount", Vector3.up * 90,
                    "time", 1.5f,
                    "oncomplete", (Action) we.Terminate));
            };

            we.end = delegate {
                Tile t = GameState.mState.grid[exitJ, exitI];
                t.exitable = true;
                solved = true;
            };

            return we;
        }
        return null;
    }
Ejemplo n.º 8
0
		public Increment(Token firstToken, Token incrementToken, bool isIncrement, bool isPrefix, Expression root, Executable owner)
			: base(firstToken, owner)
		{
			this.IncrementToken = incrementToken;
			this.IsIncrement = isIncrement;
			this.IsPrefix = isPrefix;
			this.Root = root;
		}
Ejemplo n.º 9
0
 public void LoadModule(Executable.Module module)
 {
     if (!Program.XBox.Ping()) new Settings().ShowDialog();
     if(this.Visible) this.Enabled = false;
     Program.MainWindow.Enabled = false;
     Program.MainWindow.probar.Style = ProgressBarStyle.Marquee;
     Program.MainWindow.lblStatus.Text = "Loading Module: " + module.Name;
     launchModuleWorker.RunWorkerAsync(module);
 }
Ejemplo n.º 10
0
        public static void LoadExecutables()
        {
            if (!File.Exists("Executables.xml"))
            {
				using (var sw = File.CreateText("Executables.xml"))
				{
					sw.WriteLine("<Executables></Executables>");
				}
            }
			using (var xr = XmlReader.Create(File.OpenRead("Executables.xml")))
			{
				Executable workingExe = null;
				while (!xr.EOF)
				{
					xr.Read();
					switch (xr.Name)
					{
						case "Executable":
							if (xr.NodeType == XmlNodeType.EndElement) continue;
							workingExe = new Executable()
                            { 
                                Name = xr.GetAttribute("Name"),
                                Filename = xr.GetAttribute("Filename")
                            };
							_executables.Add(workingExe);
							break;
						case "Script":
							if (xr.NodeType == XmlNodeType.EndElement) continue;
							Executable.Script script = new Executable.Script()
                            {
							    Name = xr.GetAttribute("Name"),
							    FileType = xr.GetAttribute("FileType"),
							    Code = xr.ReadInnerXml(),
                            };
							workingExe.Scripts.Add(script);
							break;
                        case "Module":
                            if (xr.NodeType == XmlNodeType.EndElement) continue;

                            uint baseAddress = 0;
                            try { baseAddress = Convert.ToUInt32(xr.GetAttribute("BaseAddress"), 16); }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "Error Reading Module For: " + workingExe.Filename, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                break;
                            }

                            Executable.Module module = new Executable.Module(xr.GetAttribute("Filename"), baseAddress)
                            { Name = xr.GetAttribute("Name") };
                            workingExe.Modules.Add(module);
                            break;
					}
				}
			}
        }
Ejemplo n.º 11
0
        public void AddToPathAddsPathEnvironmentValueIfItDoesNotExist()
        {
            // Arrange
            var executable = new Executable(@"x:\some.exe", @"x:\some-dir");

            // Act
            executable.AddToPath(@"x:\path1", @"y:\path1\path2");

            // Assert
            Assert.Equal(@"x:\path1;y:\path1\path2", executable.EnvironmentVariables["PATH"]);
        }
        public void AddToPathAddsPathEnvironmentValueIfItDoesNotExist()
        {
            // Arrange
            var executable = new Executable(@"x:\some.exe", @"x:\some-dir", DeploymentSettingsExtension.DefaultCommandIdleTimeout);

            // Act
            executable.PrependToPath(new[] { @"x:\path1", @"y:\path1\path2" });

            // Assert
            Assert.Equal(@"x:\path1;y:\path1\path2", executable.EnvironmentVariables["PATH"]);
        }
        public void AddToPathAppendsPathEnvironmentValue(string current, string[] input, string expected)
        {
            // Arrange
            var executable = new Executable(@"x:\some.exe", @"x:\some-dir", DeploymentSettingsExtension.DefaultCommandIdleTimeout);
            executable.EnvironmentVariables["PATH"] = current;

            // Act
            executable.PrependToPath(input);

            // Assert
            Assert.Equal(expected, executable.EnvironmentVariables["PATH"]);
        }
Ejemplo n.º 14
0
        public void AddToPathAppendsPathEnvironmentValue(string current, string[] input, string expected)
        {
            // Arrange
            var executable = new Executable(@"x:\some.exe", @"x:\some-dir");
            executable.EnvironmentVariables["PATH"] = current;

            // Act
            executable.AddToPath(input);

            // Assert
            Assert.Equal(expected, executable.EnvironmentVariables["PATH"]);
        }
Ejemplo n.º 15
0
        static void InitProcess(Executable ex)
        {
            /*
                InitProcess is final step in initialization of a process pertaining to a given Executable field
            */
            string prevfileName = ex.PInfo.FileName;
            try
            {
                ex.ExecutableProcess = Process.Start(ex.PInfo);
                ex.ExecutableProcess.WaitForExit();
            }
            catch (Exception e)
            {
                if (e.Message == "The system cannot find the path specified")
                {

                    try
                    {
                        ex.PInfo.FileName = ex.PInfo.FileName.Substring(ex.PInfo.FileName.LastIndexOf('\\') + 1);
                        ex.ExecutableProcess = Process.Start(ex.PInfo as ProcessStartInfo);
                        ex.ExecutableProcess.WaitForExit();

                    }
                    catch (Exception exp)
                    {

                        if (ex.PInfo.FileName.Contains("System32"))
                        {
                            ex.PInfo.FileName = prevfileName;
                            ex.PInfo.FileName.Replace("System32", "Sysnative");
                            ex.ExecutableProcess = Process.Start(ex.PInfo);
                            ex.ExecutableProcess.WaitForExit();

                        }
                        else
                            System.Windows.MessageBox.Show(exp.Message);
                    }
                }
            }
            if (ex.ExecutableProcess != null && ex != null)
                runningExecutables.Add(ex);
        }
Ejemplo n.º 16
0
		public void ConstructPackage(bool createNew)
		{
			
			// Create SSIS package
			package = new Microsoft.SqlServer.Dts.Runtime.Package();

			// Add DataFlow task
			dataFlowTask = package.Executables.Add("STOCK:PipelineTask");
			TaskHost taskhost = dataFlowTask as TaskHost;
			taskhost.Name = "Data Flow Task";
			pipeline = taskhost.InnerObject as MainPipe;

			// Add source connection manager and adapter
            if (SourceProvider == null)
            {
                throw new InvalidOperationException("Empty source provider.");
            }
            else
            {
                srcConnMgr = SourceProvider.AddConnectionManager(package);
                srcComp = SourceProvider.AddSourceAdapter(pipeline, srcConnMgr);
            }


			// Add destination connection manager and adapter, create new table if asked to.
            if (DestProvider == null)
            {
                throw new InvalidOperationException("Empty destination provider.");
            }
            else
            {
                if (createNew)
                {
                    DestProvider.CreateDestination(srcComp.OutputCollection[0].OutputColumnCollection);
                }
                destConnMgr = DestProvider.AddConnectionManager(package);
                destComp = DestProvider.AddDestAdapter(pipeline, destConnMgr, out destDesignTimeComp);
            }

		}
        public void ConstructPackage(bool createNew)
        {
            // Create SSIS package
            package = new Microsoft.SqlServer.Dts.Runtime.Package();

            // Add DataFlow task
            dataFlowTask = package.Executables.Add("STOCK:PipelineTask");
            TaskHost taskhost = dataFlowTask as TaskHost;

            taskhost.Name = "Data Flow Task";
            pipeline      = taskhost.InnerObject as MainPipe;

            // Add source connection manager and adapter
            if (SourceProvider == null)
            {
                throw new InvalidOperationException("Empty source provider.");
            }
            else
            {
                srcConnMgr = SourceProvider.AddConnectionManager(package);
                srcComp    = SourceProvider.AddSourceAdapter(pipeline, srcConnMgr);
            }


            // Add destination connection manager and adapter, create new table if asked to.
            if (DestProvider == null)
            {
                throw new InvalidOperationException("Empty destination provider.");
            }
            else
            {
                if (createNew)
                {
                    DestProvider.CreateDestination(srcComp.OutputCollection[0].OutputColumnCollection);
                }
                destConnMgr = DestProvider.AddConnectionManager(package);
                destComp    = DestProvider.AddDestAdapter(pipeline, destConnMgr, out destDesignTimeComp);
            }
        }
Ejemplo n.º 18
0
        private Executable[] TrimBreak(Executable[] executables)
        {
            TODO.PastelCompileTimeCheckForAbsenceOfBreakInSwitchStatementCodeOtherThanTheEndForTheSakeOfPythonCompilation();
            int length = executables.Length;

            if (length == 0)
            {
                return(executables);
            }
            Executable last = executables[length - 1];

            if (last is BreakStatement)
            {
                Executable[] trimmed = new Executable[length - 1];
                for (int i = length - 2; i >= 0; --i)
                {
                    trimmed[i] = executables[i];
                }
                return(trimmed);
            }
            return(executables);
        }
Ejemplo n.º 19
0
        private static string PackageArtifactFromFolder(IEnvironment environment, IDeploymentSettingsManager settings, DeploymentContext context, string srcDirectory, string artifactDirectory, string artifactFilename)
        {
            context.Logger.Log("Writing the artifacts to a squashfs file");
            string file = Path.Combine(artifactDirectory, artifactFilename);
            ExternalCommandFactory commandFactory = new ExternalCommandFactory(environment, settings, context.RepositoryPath);
            Executable             exe            = commandFactory.BuildExternalCommandExecutable(srcDirectory, artifactDirectory, context.Logger);

            try
            {
                exe.ExecuteWithProgressWriter(context.Logger, context.Tracer, $"mksquashfs . {file} -noappend");
            }
            catch (Exception)
            {
                context.GlobalLogger.LogError();
                throw;
            }

            int numOfArtifacts = OryxBuildConstants.FunctionAppBuildSettings.ConsumptionBuildMaxFiles;

            DeploymentHelper.PurgeBuildArtifactsIfNecessary(artifactDirectory, BuildArtifactType.Squashfs, context.Tracer, numOfArtifacts);
            return(file);
        }
Ejemplo n.º 20
0
        private static async Task SetupSourceControl()
        {
            try
            {
                var checkGitRepoExe = new Executable("git", "rev-parse --git-dir");
                var result          = await checkGitRepoExe.RunAsync();

                if (result != 0)
                {
                    var exe = new Executable("git", $"init");
                    await exe.RunAsync(l => ColoredConsole.WriteLine(l), l => ColoredConsole.Error.WriteLine(l));
                }
                else
                {
                    ColoredConsole.WriteLine("Directory already a git repository.");
                }
            }
            catch (FileNotFoundException)
            {
                ColoredConsole.WriteLine(WarningColor("unable to find git on the path"));
            }
        }
Ejemplo n.º 21
0
        public RuntimeCore(Heap heap, Options options = null, Executable executable = null)
        {
            // The heap is initialized by the core and is used to allocate strings
            // Use the that heap for runtime
            Validity.Assert(heap != null);
            this.Heap     = heap;
            RuntimeMemory = new RuntimeMemory(Heap);

            this.Options = options;

            InterpreterProps  = new Stack <InterpreterProperties>();
            ReplicationGuides = new List <List <ReplicationGuide> >();
            AtLevels          = new List <AtLevel>();
            executedAstGuids  = new HashSet <Guid>();

            RunningBlock   = 0;
            ExecutionState = (int)ExecutionStateEventArgs.State.Invalid; //not yet started

            ContinuationStruct = new ContinuationStructure();


            watchStack        = new List <StackValue>();
            watchFramePointer = Constants.kInvalidIndex;
            WatchSymbolList   = new List <SymbolNode>();

            FunctionCallDepth   = 0;
            cancellationPending = false;

            watchClassScope = Constants.kInvalidIndex;

            ExecutionInstance = CurrentExecutive = new Executive(this);
            ExecutiveProvider = new ExecutiveProvider();

            RuntimeStatus = new ProtoCore.RuntimeStatus(this);
            StartPC       = Constants.kInvalidPC;
            RuntimeData   = new ProtoCore.RuntimeData();
            DSExecutable  = executable;
            Mirror        = null;
        }
Ejemplo n.º 22
0
        public static List <GameData> Get()
        {
            var gameDatas = new List <GameData>();

            if (thisHWnd == IntPtr.Zero)
            {
                thisHWnd = FindWindow(null, "GameLauncher");
            }

            foreach (var folderName in GameListDAO.Get())
            {
                var exeAsExecutable = new Executable(folderName + "/Exe.lnk");
                exeAsExecutable.OnProcessStarted += (_) =>
                {
                    ShowWindow(thisHWnd, SW_MINIMIZE);
                };

                exeAsExecutable.OnProcessEnded += (sender, e) =>
                {
                    ShowWindow(thisHWnd, SW_RESTORE);
                };

                var sprite = SpriteFactory.Create(folderName + "/Icon.png");
                var descriptionAsExecutable = new Executable(folderName + "/Description.pdf");
                var summary = FileErrorCatcher.CatchError(GetSummaryData, folderName + "/Summary.txt");
                var data    = new GameData(
                    summary[0],
                    summary[1],
                    summary[2],
                    exeAsExecutable,
                    sprite,
                    descriptionAsExecutable);

                gameDatas.Add(data);
            }

            return(gameDatas);
        }
Ejemplo n.º 23
0
        private bool TryGetSubName(Executable Exe, long Position, out string Name)
        {
            Position -= Exe.ImageBase;

            int Left  = 0;
            int Right = Exe.SymbolTable.Count - 1;

            while (Left <= Right)
            {
                int Size = Right - Left;

                int Middle = Left + (Size >> 1);

                ElfSym Symbol = Exe.SymbolTable[Middle];

                long EndPosition = Symbol.Value + Symbol.Size;

                if ((ulong)Position >= (ulong)Symbol.Value && (ulong)Position < (ulong)EndPosition)
                {
                    Name = Symbol.Name;

                    return(true);
                }

                if ((ulong)Position < (ulong)Symbol.Value)
                {
                    Right = Middle - 1;
                }
                else
                {
                    Left = Middle + 1;
                }
            }

            Name = null;

            return(false);
        }
Ejemplo n.º 24
0
        public void GenerateExprExe()
        {
            // TODO Jun: Determine if we really need another executable for the expression interpreter
            Validity.Assert(null == ExprInterpreterExe);
            ExprInterpreterExe = new Executable();
            ExprInterpreterExe.FunctionTable     = FunctionTable;
            ExprInterpreterExe.DynamicVarTable   = DynamicVariableTable;
            ExprInterpreterExe.FuncPointerTable  = FunctionPointerTable;
            ExprInterpreterExe.DynamicFuncTable  = DynamicFunctionTable;
            ExprInterpreterExe.ContextDataMngr   = ContextDataManager;
            ExprInterpreterExe.Configurations    = Configurations;
            ExprInterpreterExe.CodeToLocation    = CodeToLocation;
            ExprInterpreterExe.CurrentDSFileName = CurrentDSFileName;

            // Copy all tables
            ExprInterpreterExe.classTable     = DSExecutable.classTable;
            ExprInterpreterExe.procedureTable = DSExecutable.procedureTable;
            ExprInterpreterExe.runtimeSymbols = DSExecutable.runtimeSymbols;


            ExprInterpreterExe.TypeSystem = TypeSystem;

            // Copy all instruction streams
            // TODO Jun: What method to copy all? Use that
            ExprInterpreterExe.instrStreamList = new InstructionStream[DSExecutable.instrStreamList.Length];
            for (int i = 0; i < DSExecutable.instrStreamList.Length; ++i)
            {
                if (null != DSExecutable.instrStreamList[i])
                {
                    ExprInterpreterExe.instrStreamList[i] = new InstructionStream(DSExecutable.instrStreamList[i].language, this);
                    //ExprInterpreterExe.instrStreamList[i] = new InstructionStream(DSExecutable.instrStreamList[i].language, DSExecutable.instrStreamList[i].dependencyGraph, this);
                    for (int j = 0; j < DSExecutable.instrStreamList[i].instrList.Count; ++j)
                    {
                        ExprInterpreterExe.instrStreamList[i].instrList.Add(DSExecutable.instrStreamList[i].instrList[j]);
                    }
                }
            }
        }
Ejemplo n.º 25
0
        public override void OnInspectorGUI()
        {
            // Draw the default inspector
            DrawDefaultInspector();

            rayColor  = EditorGUILayout.ColorField(rayColor);
            rayOffset = EditorGUILayout.Vector3Field("Ray offset", rayOffset);
            if (GUILayout.Button("Find executables with ray"))
            {
                SerializedProperty array = serializedObject.FindProperty("executables");
                var        _class        = target as GS.Executes.Executor;
                Executable exe           = null;
                for (int i = 0; i < array.arraySize; i++)
                {
                    exe = array.GetArrayElementAtIndex(i).objectReferenceValue as GS.Executes.Executable;
                    if (exe == null)
                    {
                        continue;
                    }
                    DrawRayToPoint(_class.gameObject.transform.position, exe.gameObject.transform.position, rayOffset);
                }
            }
        }
Ejemplo n.º 26
0
        public static TestRepository Clone(string repositoryPath, string source, bool createDirectory = false)
        {
            // Gets full path in case path is relative
            repositoryPath = GetRepositoryPath(repositoryPath);

            // Make sure the directory is empty
            FileSystemHelpers.DeleteDirectorySafe(repositoryPath);
            Executable gitExe = GetGitExe(repositoryPath);

            if (createDirectory)
            {
                var result = gitExe.Execute("clone \"{0}\"", source);

                // Cloning into '{0}'...
                var    m          = Regex.Match(result.Item1, @"Cloning\s+into\s+\'?(\w+)'?\.*", RegexOptions.IgnoreCase);
                string folderName = m.Groups[1].Value;
                return(new TestRepository(Path.Combine(repositoryPath, folderName)));
            }

            gitExe.Execute("clone \"{0}\" .", source);

            return(new TestRepository(repositoryPath));
        }
Ejemplo n.º 27
0
        public static string Push(string repositoryPath, string url, string localBranchName = "master", string remoteBranchName = "master")
        {
            Executable gitExe = GetGitExe(repositoryPath);

            string stdErr = null;

            if (localBranchName.Equals("master"))
            {
                stdErr = gitExe.Execute("push {0} {1}", url, remoteBranchName).Item2;

                // Dump out the error stream (git curl verbose)
                Debug.WriteLine(stdErr);
            }
            else
            {
                // Dump out the error stream (git curl verbose)
                stdErr = gitExe.Execute("push {0} {1}:{2}", url, localBranchName, remoteBranchName).Item2;

                Debug.WriteLine(stdErr);
            }

            return(stdErr);
        }
        private static async Task RestorePythonRequirementsPackapp(string functionAppRoot, string packagesLocation)
        {
            var packApp = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "tools", "python", "packapp");

            var pythonExe = await ValidatePythonVersion(errorOutIfOld : true);

            var exe      = new Executable(pythonExe, $"\"{packApp}\" --platform linux --python-version 36 --packages-dir-name {Constants.ExternalPythonPackages} \"{functionAppRoot}\" --verbose");
            var sbErrors = new StringBuilder();
            var exitCode = await exe.RunAsync(o => ColoredConsole.WriteLine(o), e => sbErrors.AppendLine(e));

            if (exitCode != 0)
            {
                var errorMessage = "There was an error restoring dependencies. " + sbErrors.ToString();
                // If --build-native-deps if required, we exit with this specific code to notify other toolings
                // If this exit code changes, partner tools must be updated
                if (exitCode == ExitCodes.BuildNativeDepsRequired)
                {
                    ColoredConsole.WriteLine(ErrorColor(errorMessage));
                    Environment.Exit(ExitCodes.BuildNativeDepsRequired);
                }
                throw new CliException(errorMessage);
            }
        }
Ejemplo n.º 29
0
        protected virtual bool MapPath(string path, out string driveName)
        {
            var cmd = new Executable("cmd", GetWindowsFolder());

            driveName = null;

            foreach (var letter in DriveLetters)
            {
                try
                {
                    // There's probably an API for this as well but this is easy to do
                    // Not as easy to parse out the results of net use
                    cmd.Execute("/c net use {0}: {1}", letter, path);
                    driveName = letter + @":\";
                    return(true);
                }
                catch
                {
                }
            }

            return(false);
        }
Ejemplo n.º 30
0
        private static Executable ParseTry(Parser parser, TokenStream tokens, Executable owner)
        {
            Token tryToken = tokens.PopExpected("try");
            IList <Executable> tryBlock     = Parser.ParseBlock(parser, tokens, true, owner);
            Token catchToken                = null;
            IList <Executable> catchBlock   = null;
            Token exceptionToken            = null;
            Token finallyToken              = null;
            IList <Executable> finallyBlock = null;

            if (tokens.IsNext("catch"))
            {
                catchToken = tokens.Pop();
                if (tokens.PopIfPresent("("))
                {
                    exceptionToken = tokens.Pop();
                    char firstChar = exceptionToken.Value[0];
                    if (firstChar != '_' &&
                        !(firstChar >= 'a' && firstChar <= 'z') &&
                        !(firstChar >= 'A' && firstChar <= 'Z'))
                    {
                        throw new ParserException(exceptionToken, "Invalid name for variable.");
                    }
                    tokens.PopExpected(")");
                }

                catchBlock = Parser.ParseBlock(parser, tokens, true, owner);
            }

            if (tokens.IsNext("finally"))
            {
                finallyToken = tokens.Pop();
                finallyBlock = Parser.ParseBlock(parser, tokens, true, owner);
            }

            return(new TryStatement(tryToken, tryBlock, catchToken, exceptionToken, catchBlock, finallyToken, finallyBlock, owner));
        }
        public void TestChangeRowsProcessedOutputSetColumnProperty()
        {
            Microsoft.SqlServer.Dts.Runtime.Package package = new Microsoft.SqlServer.Dts.Runtime.Package();
            Executable exec = package.Executables.Add("STOCK:PipelineTask");

            Microsoft.SqlServer.Dts.Runtime.TaskHost thMainPipe = exec as Microsoft.SqlServer.Dts.Runtime.TaskHost;
            MainPipe dataFlowTask        = thMainPipe.InnerObject as MainPipe;
            ComponentEventHandler events = new ComponentEventHandler();

            dataFlowTask.Events = DtsConvert.GetExtendedInterface(events as IDTSComponentEvents);

            IDTSComponentMetaData100 textFileSplitter = dataFlowTask.ComponentMetaDataCollection.New();

            textFileSplitter.Name             = "Row Splitter Test";
            textFileSplitter.ComponentClassID = typeof(Martin.SQLServer.Dts.TextFileSplitter).AssemblyQualifiedName;
            CManagedComponentWrapper instance = textFileSplitter.Instantiate();

            instance.ProvideComponentProperties();

            IDTSOutput100 errorOutput = textFileSplitter.OutputCollection[3];

            ManageProperties.AddMissingOutputColumnProperties(errorOutput.OutputColumnCollection[0].CustomPropertyCollection);

            Boolean exceptionThrown = false;

            try
            {
                instance.SetOutputColumnProperty(errorOutput.ID, errorOutput.OutputColumnCollection[0].ID, ManageProperties.dotNetFormatString, String.Empty);
            }
            catch (COMException ex)
            {
                Assert.AreEqual(MessageStrings.CantChangeOutputProperties("RowsProcessed"), ex.Message, "Exception Message Wrong");
                exceptionThrown = true;
            }

            Assert.IsTrue(exceptionThrown, "Exception Not Thrown");
        }
Ejemplo n.º 32
0
        private bool LE_Broadcast(Executable executable, int to_sn)
        {
            alive.Add(remoteSLE(executable));
            //Broadcast to everyone
            int replies = 0;

            foreach (string serverURL in otherServers.Values)
            {
                Thread thread = new Thread(() =>
                {
                    try
                    {
                        ServerInstance s = (ServerInstance)Activator.GetObject(
                            typeof(ServerInstance),
                            serverURL
                            );
                        alive.Add(s.remoteSLE(executable));
                        replies++;
                    } catch (Exception e)
                    {
                    }
                });
                thread.Start();
            }
            double timer = 0;

            while (replies < maxFaults)
            {
                if (timer >= 2)
                {
                    return(false);
                }
                System.Threading.Thread.Sleep(50);
                timer += 0.05;
            }
            return(true);
        }
Ejemplo n.º 33
0
        public Executable BuildExternalCommandExecutable(string workingDirectory, string deploymentTargetPath, ILogger logger)
        {
            // Creates an executable pointing to cmd and the working directory being
            // the repository root
            var exe = new Executable(StarterScriptPath, workingDirectory, _deploymentSettings.GetCommandIdleTimeout());

            exe.AddDeploymentSettingsAsEnvironmentVariables(_deploymentSettings);
            UpdateToDefaultIfNotSet(exe, SourcePath, _repositoryPath, logger);
            UpdateToDefaultIfNotSet(exe, TargetPath, deploymentTargetPath, logger);
            UpdateToDefaultIfNotSet(exe, WebRootPath, _environment.WebRootPath, logger);
            UpdateToDefaultIfNotSet(exe, MSBuildPath, PathUtility.ResolveMSBuildPath(), logger);
            UpdateToDefaultIfNotSet(exe, KuduSyncCommandKey, KuduSyncCommand, logger);
            UpdateToDefaultIfNotSet(exe, SelectNodeVersionCommandKey, SelectNodeVersionCommand, logger);
            UpdateToDefaultIfNotSet(exe, NpmJsPathKey, PathUtility.ResolveNpmJsPath(), logger);

            // Disable this for now
            // exe.EnvironmentVariables[NuGetCachePathKey] = Environment.NuGetCachePath;

            // NuGet.exe 1.8 will require an environment variable to make package restore work
            exe.EnvironmentVariables[WellKnownEnvironmentVariables.NuGetPackageRestoreKey] = "true";

            exe.SetHomePath(_environment.SiteRootPath);

            // Set the path so we can add more variables
            exe.EnvironmentVariables["PATH"] = System.Environment.GetEnvironmentVariable("PATH");

            // Add the msbuild path and git path to the %PATH% so more tools are available
            var toolsPaths = new[] {
                Path.GetDirectoryName(PathUtility.ResolveMSBuildPath()),
                Path.GetDirectoryName(PathUtility.ResolveGitPath()),
                Path.GetDirectoryName(PathUtility.ResolveVsTestPath())
            };

            exe.AddToPath(toolsPaths);

            return(exe);
        }
Ejemplo n.º 34
0
        private Executable ParseEnumDefinition(TokenStream tokens, Executable owner)
        {
            Token enumToken = tokens.PopExpected(this.parser.Keywords.ENUM);
            Token nameToken = tokens.Pop();

            this.parser.VerifyIdentifier(nameToken);
            string         name = nameToken.Value;
            EnumDefinition ed   = new EnumDefinition(enumToken, nameToken, parser.CurrentNamespace, owner);

            tokens.PopExpected("{");
            bool              nextForbidden = false;
            List <Token>      items         = new List <Token>();
            List <Expression> values        = new List <Expression>();

            while (!tokens.PopIfPresent("}"))
            {
                if (nextForbidden)
                {
                    tokens.PopExpected("}");                // crash
                }
                Token enumItem = tokens.Pop();
                this.parser.VerifyIdentifier(enumItem);
                if (tokens.PopIfPresent("="))
                {
                    values.Add(this.parser.ExpressionParser.Parse(tokens, ed));
                }
                else
                {
                    values.Add(null);
                }
                nextForbidden = !tokens.PopIfPresent(",");
                items.Add(enumItem);
            }

            ed.SetItems(items, values);
            return(ed);
        }
Ejemplo n.º 35
0
        private void RemoveAcls(string appName, string appPoolName)
        {
            // Setup Acls for this user
            var icacls = new Executable(@"C:\Windows\System32\icacls.exe", Directory.GetCurrentDirectory());

            string applicationPath = _pathResolver.GetApplicationPath(appName);

            try
            {
                // Give full control to the app folder (we can make it minimal later)
                icacls.Execute(@"""{0}"" /remove ""IIS AppPool\{1}""", applicationPath, appPoolName);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            try
            {
                icacls.Execute(@"""{0}"" /remove ""IIS AppPool\{1}""", _pathResolver.ServiceSitePath, appPoolName);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            try
            {
                // Give full control to the temp folder
                string windowsTemp = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Temp");
                icacls.Execute(@"""{0}"" /remove ""IIS AppPool\{1}""", windowsTemp, appPoolName);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 36
0
        public IDTSResultBinding Modify_ExecSQL_AddResultSetBinding(Executable ex,
                                                                    string ResultName,
                                                                    string VariableName
                                                                    )
        {
            TaskHost       SQLth = (TaskHost)ex;
            ExecuteSQLTask task  = SQLth.InnerObject as ExecuteSQLTask;

            int i = 0;

            foreach (IDTSResultBinding z in task.ResultSetBindings)
            {
                i++;
            }

            // Add result set binding, map the id column to variable
            task.ResultSetBindings.Add();
            IDTSResultBinding rb = task.ResultSetBindings.GetBinding(i);

            rb.ResultName      = ResultName;
            rb.DtsVariableName = VariableName;

            return(rb);
        }
Ejemplo n.º 37
0
        public void Compile_no_errors()
        {
            var csSource = new Sourcecode
            {
                Filename = "program_no_errors.cs",
                Text     = @"using System;
public class Program {
  public static void Main(string[] args) {
    #region main
var answer = 42;
Console.WriteLine(answer);
    #endregion
  }
}
".Split('\n')
            };

            Executable result = null;

            CSCompiler.Compile(csSource,
                               exe => result = exe,
                               errors => {
                foreach (var err in errors)
                {
                    Console.WriteLine($"{err.Filename} - {err.LineNumber},{err.ColumnNumber}: {err.Description}");
                }
                Assert.Fail("There should not be any errors!");
            });

            Assert.NotNull(result);


            var output = ConsoleOutput.Capture(() => result.Main());

            Assert.AreEqual("42", output.Trim());
        }
Ejemplo n.º 38
0
        public async Task RepairCardsAsync(ulong oldId, ulong newId)
        {
            var response = await _shClient.GetCharacterInfoAsync(newId);

            if (!response.IsSuccessStatusCode())
            {
                await "New character ID is invalid!".ToResponse(500).ExecuteResultAsync(ControllerContext);
                return;
            }

            var exe = new Executable($"api-repair oc{oldId} c{newId}", new Task(() =>
            {
                using (var db = new Database.UserContext(_config))
                {
                    var userRelease = new List <string>()
                    {
                        "users"
                    };
                    var cards = db.Cards.Where(x => x.Character == oldId);

                    foreach (var card in cards)
                    {
                        card.Character = newId;
                        userRelease.Add($"user-{card.GameDeckId}");
                    }

                    db.SaveChanges();

                    QueryCacheManager.ExpireTag(userRelease.ToArray());
                }
            }));

            await _executor.TryAdd(exe, TimeSpan.FromSeconds(1));

            await "Success".ToResponse(200).ExecuteResultAsync(ControllerContext);
        }
Ejemplo n.º 39
0
    public Executable Trigger(Executable trigger)
    {
        Debug.Log("trigger");
        Tile t = entity.tile;
        if (!solved && t.entities.Count > entity.tileIndex + 1) {
            DungeonEntity pe = t.entities[entity.tileIndex + 1];
            Pot p = pe.transform.GetComponent<Pot>();
            if (p != null && p.color == color) {

                WrapperUpdateFunction upf = delegate {
                    panelRenderer.material.color = Color.Lerp(panelRenderer.material.color, targetColor, 0.2f);
                    return (panelRenderer.material.color == targetColor);
                };

                WrapperEndFunction ef = delegate {
                    solved = true;
                };

                WrapperExec we = new WrapperExec("floorPanel_change", WrapperExec.DefaultDoNothing, upf, ef);
                return we;
            }
        }
        return null;
    }
Ejemplo n.º 40
0
        public static void Commit(string repositoryPath, string message)
        {
            Executable gitExe = GetGitExe(repositoryPath);

            try
            {
                GitExecute(gitExe, "add -A", message);
                GitExecute(gitExe, "commit -m \"{0}\"", message);
            }
            catch (Exception ex)
            {
                // Swallow exceptions on commit, since things like changing line endings
                // show up as an error
                TestTracer.Trace("Commit failed with {0}", ex);
            }

            // Verify that the commit did go thru
            string lastCommitMessage = GitExecute(gitExe, "log --oneline -1").Item1;

            if (lastCommitMessage == null || !lastCommitMessage.Contains(message))
            {
                throw new InvalidOperationException(String.Format("Mismatched commit message '{0}' != '{1}'", lastCommitMessage, message));
            }
        }
Ejemplo n.º 41
0
        public static string Push(string repositoryPath, string url, string localBranchName = "master", string remoteBranchName = "master")
        {
            using (new LatencyLogger("git push " + repositoryPath))
            {
                Executable gitExe = GetGitExe(repositoryPath);

                string stdErr = null;

                if (localBranchName.Equals("master"))
                {
                    stdErr = GitExecute(gitExe, "push {0} {1}", url, remoteBranchName).Item2;
                }
                else
                {
                    // Checkout the local branch, making sure it points to the correct origin branch
                    GitExecute(gitExe, "checkout -B {0} origin/{0}", localBranchName);

                    // Dump out the error stream (git curl verbose)
                    stdErr = GitExecute(gitExe, "push {0} {1}:{2}", url, localBranchName, remoteBranchName).Item2;
                }

                return(stdErr);
            }
        }
Ejemplo n.º 42
0
        public void Run()
        {
            SetActiveApplication(_parent);

            AppEnvironment.Settings.AddToHistory(Executable, CommandLineArgs);
            NotifyPropertyChanged("CommandLineHistory");

            var executableFullPath = OutputDirectory + @"\" + Executable;

            if (AppEnvironment.Settings.TestMode)
            {
                executableFullPath = @"DummyExe.exe";
            }

            var commandLineExpanded = Extensions.ExpandCommandLine(CommandLineArgs);

            ExecutableObj = new Executable(executableFullPath);
            Status        = ApplicationStatus.Running;
            ExecutableObj.RunAsync(commandLineExpanded);
            ExecutableObj.ExecutionCompleted += (s, e) =>
            {
                Status = ApplicationStatus.BuildCompleted;
            };
        }
Ejemplo n.º 43
0
        private Executable[] TrimBreak(Executable[] executables)
        {
            // TODO: compile time check for absence of break in switch statement code
            // aside from the one at the end of each case. This will simply be a limitation
            // of Pastel for the sake of Python compatibility.
            int length = executables.Length;

            if (length == 0)
            {
                return(executables);
            }
            Executable last = executables[length - 1];

            if (last is BreakStatement)
            {
                Executable[] trimmed = new Executable[length - 1];
                for (int i = length - 2; i >= 0; --i)
                {
                    trimmed[i] = executables[i];
                }
                return(trimmed);
            }
            return(executables);
        }
Ejemplo n.º 44
0
        public void SetVariableRuntime(SetVariablesSetVariable[] sqlTaskSetVariables, string stepName, string setName)
        {
            int iVarCount = 0;

            foreach (var sqlSetVariable in sqlTaskSetVariables)
            {
                Executable sqlSetVariableExe = AddExecutableSQLTask(sqlSetVariable.SQLStatement, sqlSetVariable.TargetConnection, "Set Variable-" + stepName + "_" + setName + iVarCount.ToString(), string.Empty);
                TaskHost   srcth             = sqlSetVariableExe as TaskHost;
                //  srcth.Properties["BypassPrepare"].SetValue(srcth, true);
                // srcth.Properties["Connection"].SetValue(srcth, sqlSetVariable.TargetConnection);
                // srcth.Properties["SqlStatementSourceType"].SetValue(srcth, SqlStatementSourceType.DirectInput);
                //srcth.Properties["SqlStatementSource"].SetValue(srcth, sqlSetVariable.SQLStatement);
                srcth.Properties["ResultSetType"].SetValue(srcth, ResultSetType.ResultSetType_SingleRow);
                var sqlTaskSRC = srcth.InnerObject as IDTSExecuteSQL;
                foreach (var resultSet in sqlSetVariable.ResultSet)
                {
                    IDTSResultBinding resultbinding = sqlTaskSRC.ResultSetBindings.Add();
                    resultbinding.ResultName      = resultSet.Order;
                    resultbinding.DtsVariableName = GetVariableValue(resultSet.VariableName).QualifiedName;
                }
                AddPrecedenceConstraints(sqlSetVariableExe);
                iVarCount++;
            }
        }
Ejemplo n.º 45
0
        public Executable BuildCommandExecutable(string commandPath, string workingDirectory, TimeSpan idleTimeout, ILogger logger)
        {
            // Creates an executable pointing to cmd and the working directory being
            // the repository root
            var exe = new Executable(commandPath, workingDirectory, idleTimeout);

            exe.AddDeploymentSettingsAsEnvironmentVariables(_deploymentSettings);
            UpdateToDefaultIfNotSet(exe, WellKnownEnvironmentVariables.WebRootPath, _environment.WebRootPath, logger);
            UpdateToDefaultIfNotSet(exe, WellKnownEnvironmentVariables.MSBuildPath, PathUtility.ResolveMSBuildPath(), logger);
            UpdateToDefaultIfNotSet(exe, WellKnownEnvironmentVariables.KuduSyncCommandKey, KuduSyncCommand, logger);
            UpdateToDefaultIfNotSet(exe, WellKnownEnvironmentVariables.NuGetExeCommandKey, NuGetExeCommand, logger);
            UpdateToDefaultIfNotSet(exe, WellKnownEnvironmentVariables.NpmJsPathKey, PathUtility.ResolveNpmJsPath(), logger);

            exe.SetHomePath(_environment);

            // Set the path so we can add more variables
            string path = System.Environment.GetEnvironmentVariable("PATH");

            exe.EnvironmentVariables["PATH"] = path;

            // Add the msbuild path and git path to the %PATH% so more tools are available
            var toolsPaths = new List <string> {
                Path.GetDirectoryName(PathUtility.ResolveMSBuildPath()),
                Path.GetDirectoryName(PathUtility.ResolveGitPath()),
                Path.GetDirectoryName(PathUtility.ResolveVsTestPath()),
                Path.GetDirectoryName(PathUtility.ResolveSQLCmdPath()),
                _environment.ScriptPath
            };

            toolsPaths.AddRange(PathUtility.ResolveNodeNpmPaths());

            toolsPaths.Add(PathUtility.ResolveNpmGlobalPrefix());

            exe.PrependToPath(toolsPaths);
            return(exe);
        }
Ejemplo n.º 46
0
        private void TO_Broadcast(Executable executable, int to_sn)
        {
            this.Change_TO_SN(executable, to_sn);

            //Broadcast to everyone
            foreach (string serverURL in otherServers.Values)
            {
                Thread thread = new Thread(() =>
                {
                    try
                    {
                        ServerInstance s = (ServerInstance)Activator.GetObject(
                            typeof(ServerInstance),
                            serverURL
                            );
                        s.Change_TO_SN(executable, to_sn);
                    }
                    catch (Exception e)
                    {
                    }
                });
                thread.Start();
            }
        }
Ejemplo n.º 47
0
 public DynamicCmd(Executable startInstance)
 {
     this.Cmd = startInstance;
 }
Ejemplo n.º 48
0
 public override void OnPostExecute(Executable exec, ref bool fireAgain)
 {
     ExecutionTime = DateTime.Now.Subtract(StartTime);
     base.OnPreExecute(exec, ref fireAgain);
 }
Ejemplo n.º 49
0
 public override void OnPreExecute(Executable exec, ref bool fireAgain)
 {
     StartTime = DateTime.Now;
     base.OnPreExecute(exec, ref fireAgain);
 }
Ejemplo n.º 50
0
 public Executable Trigger(Executable e)
 {
     if (trigger != null && trigger.solved) {}
     return null;
 }
Ejemplo n.º 51
0
        private static void CreateDepsInPackageCache(LibraryRange toolLibrary, string projectPath)
        {
            var context = ProjectContext.Create(projectPath,
                FrameworkConstants.CommonFrameworks.DnxCore50, new[] { DefaultRid });

            var toolDescription = context.LibraryManager.GetLibraries()
                .Select(l => l as PackageDescription)
                .Where(l => l != null)
                .FirstOrDefault(l => l.Identity.Name == toolLibrary.Name);

            var depsPath = Path.Combine(
                toolDescription.Path,
                Path.GetDirectoryName(toolDescription.Target.RuntimeAssemblies.First().Path),
                toolDescription.Identity.Name + FileNameSuffixes.Deps);

            var calculator = context.GetOutputPathCalculator(context.ProjectDirectory);
            var executable = new Executable(context, calculator);

            executable.MakeCompilationOutputRunnable(Constants.DefaultConfiguration);

            if (File.Exists(depsPath)) File.Delete(depsPath);

            File.Move(Path.Combine(calculator.GetOutputDirectoryPath(Constants.DefaultConfiguration), "bin" + FileNameSuffixes.Deps), depsPath);
        }
Ejemplo n.º 52
0
 public Executable Trigger(Executable t)
 {
     return null;
 }
Ejemplo n.º 53
0
		public NegativeSign(Token sign, Expression root, Executable owner)
			: base(sign, owner)
		{
			this.Root = root;
		}
Ejemplo n.º 54
0
		public void OnExecutionStatusChanged(Executable exec, DTSExecStatus newStatus, ref bool fireAgain)
		{
		}
Ejemplo n.º 55
0
        private void MakeRunnableIfNecessary()
        {
            var compilationOptions = CompilerUtil.ResolveCompilationOptions(_rootProject, _args.ConfigValue);

            // TODO: Make this opt in via another mechanism
            var makeRunnable = compilationOptions.EmitEntryPoint.GetValueOrDefault() ||
                               _rootProject.IsTestProject();

            if (makeRunnable)
            {
                var outputPathCalculator = _rootProject.GetOutputPathCalculator(_args.OutputValue);
                var rids = new List<string>();
                if (string.IsNullOrEmpty(_args.RuntimeValue))
                {
                    rids.AddRange(PlatformServices.Default.Runtime.GetAllCandidateRuntimeIdentifiers());
                }
                else
                {
                    rids.Add(_args.RuntimeValue);
                }

                var runtimeContext = ProjectContext.Create(_rootProject.ProjectDirectory, _rootProject.TargetFramework, rids);
                var executable = new Executable(runtimeContext, outputPathCalculator);
                executable.MakeCompilationOutputRunnable(_args.ConfigValue);
            }
        }
Ejemplo n.º 56
0
        private void MakeRunnable()
        {
            var runtimeContext = _rootProject.CreateRuntimeContext(_args.GetRuntimes());
            var outputPaths = runtimeContext.GetOutputPaths(_args.ConfigValue, _args.BuildBasePathValue, _args.OutputValue);
            var libraryExporter = runtimeContext.CreateExporter(_args.ConfigValue, _args.BuildBasePathValue);
            CopyCompilationOutput(outputPaths);
            var executable = new Executable(runtimeContext, outputPaths, libraryExporter);
            executable.MakeCompilationOutputRunnable();

            PatchMscorlibNextToCoreClr(runtimeContext, _args.ConfigValue);
        }
Ejemplo n.º 57
0
		public void OnPostExecute(Executable exec, ref bool fireAgain)
		{
		}
Ejemplo n.º 58
0
        public AssemblyLoadResult Load(LoadContext loadContext)
        {
            string name = loadContext.AssemblyName;

            string targetDir = Path.Combine(_solutionDir, name);

            // Bail if there's a project settings file
            if (Project.HasProjectFile(targetDir))
            {
                return null;
            }

            string projectFile = Path.Combine(targetDir, name + ".csproj");

            if (!System.IO.File.Exists(projectFile))
            {
                // There's a solution so check for a project one deeper
                if (System.IO.File.Exists(Path.Combine(targetDir, name + ".sln")))
                {
                    // Is there a project file here?
                    projectFile = Path.Combine(targetDir, name, name + ".csproj");

                    if (!System.IO.File.Exists(projectFile))
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }

            WatchProject(projectFile);

            string projectDir = Path.GetDirectoryName(projectFile);

            foreach (var exePath in _msBuildPaths)
            {
                if (!System.IO.File.Exists(exePath))
                {
                    continue;
                }

                var executable = new Executable(exePath, projectDir);

                string outputFile = null;
                var process = executable.Execute(line =>
                {
                    // Look for {project} -> {outputPath}
                    int index = line.IndexOf('-');

                    if (index != -1 && index + 1 < line.Length && line[index + 1] == '>')
                    {
                        string projectName = line.Substring(0, index).Trim();
                        if (projectName.Equals(name, StringComparison.OrdinalIgnoreCase))
                        {
                            outputFile = line.Substring(index + 2).Trim();
                        }
                    }

                    return true;
                },
                _ => true,
                Encoding.UTF8,
                projectFile + " /m");

                process.WaitForExit();

                if (process.ExitCode != 0)
                {
                    // REVIEW: Should this throw?
                    return null;
                }

                return new AssemblyLoadResult(Assembly.LoadFile(outputFile));
            }

            return null;
        }
Ejemplo n.º 59
0
 public void Initialize(Executable e, EndProc ep)
 {
     exe = e;
     endProc = ep;
 }
Ejemplo n.º 60
0
		public void OnPreValidate(Executable exec, ref bool fireAgain)
		{
		}