示例#1
0
        public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger log, ITestCaseDiscoverySink discoverySink)
        {
            log.Version();

            RemotingUtility.CleanUpRegisteredChannels();

            foreach (var assemblyPath in sources)
            {
                try
                {
                    if (AssemblyDirectoryContainsFixie(assemblyPath))
                    {
                        log.Info("Processing " + assemblyPath);

                        using (var environment = new ExecutionEnvironment(assemblyPath))
                        {
                            var methodGroups = environment.DiscoverTestMethodGroups(new Options());

                            foreach (var methodGroup in methodGroups)
                                discoverySink.SendTestCase(new TestCase(methodGroup.FullName, VsTestExecutor.Uri, assemblyPath));
                        }
                    }
                    else
                    {
                        log.Info("Skipping " + assemblyPath + " because it is not a test assembly.");
                    }
                }
                catch (Exception exception)
                {
                    log.Error(exception);
                }
            }
        }
示例#2
0
        public void RunTests(IEnumerable<string> sources, IRunContext runContext, IFrameworkHandle frameworkHandle)
        {
            IMessageLogger log = frameworkHandle;

            log.Version();

            HandlePoorVisualStudioImplementationDetails(runContext, frameworkHandle);

            foreach (var assemblyPath in sources)
            {
                try
                {
                    if (AssemblyDirectoryContainsFixie(assemblyPath))
                    {
                        log.Info("Processing " + assemblyPath);

                        var listener = new VisualStudioListener(frameworkHandle, assemblyPath);

                        using (var environment = new ExecutionEnvironment(assemblyPath))
                        {
                            environment.RunAssembly(new Options(), listener);
                        }
                    }
                    else
                    {
                        log.Info("Skipping " + assemblyPath + " because it is not a test assembly.");
                    }
                }
                catch (Exception exception)
                {
                    log.Error(exception);
                }
            }
        }
 public void ExploreAssembly(
     IProject project, 
     IMetadataAssembly assembly, 
     IUnitTestElementsObserver observer,
     CancellationToken cancellationToken)
 {
     var environment = new ExecutionEnvironment(assembly.Location.FullPath);
     var methodGroups = environment.DiscoverTestMethodGroups(null);
 }
示例#4
0
        static AssemblyResult Execute(string assemblyPath, Options options)
        {
            var listener = CreateListener(options);

            using (var environment = new ExecutionEnvironment(assemblyPath))
            {
                return environment.RunAssembly(options, listener);
            }
        }
示例#5
0
文件: Program.cs 项目: ninjanye/fixie
        static AssemblyResult Execute(string assemblyPath, string[] args)
        {
            var assemblyFullPath = Path.GetFullPath(assemblyPath);

            using (var environment = new ExecutionEnvironment(assemblyFullPath))
            {
                var runner = environment.Create<ConsoleRunner>();
                return runner.RunAssembly(assemblyFullPath, args);
            }
        }
 public static void Main()
 {
     using (var listener = new DaSpecListener())
     {
         using (var environment = new ExecutionEnvironment("."))
         {
             environment.RunAssembly(new Options(), listener);
         }
     }
 }
示例#7
0
文件: Program.cs 项目: jbogard/fixie
        static AssemblyResult Execute(string assemblyPath, Options options)
        {
            using (var environment = new ExecutionEnvironment(assemblyPath))
            {
                if (ShouldUseTeamCityListener(options))
                    using (var listener = new TeamCityListener())
                        return environment.RunAssembly(options, listener);

                if (ShouldUseAppVeyorListener())
                    using (var listener = new AppVeyorListener())
                        return environment.RunAssembly(options, listener);

                using (var listener = new ConsoleListener())
                    return environment.RunAssembly(options, listener);
            }
        }
      private static void RunTests(IReadOnlyCollection<string> testAssemblyPaths, string uri)
      {
         try
         {
            var executionResult = new ExecutionResult();

            foreach (var assemblyPath in testAssemblyPaths)
            {
               var listener = CreateListener(uri);
               using (var environment = new ExecutionEnvironment(assemblyPath))
                  executionResult.Add(environment.RunAssembly(new Options(), listener));
            }
         }
         catch (Exception exception)
         {
            Debug.Fail(exception.ToString());
         }
      }
 public IExport GetExport(string exportName, ExecutionEnvironment environment)
 {
     return null;
 }
示例#10
0
 private void color(ExecutionEnvironment env, Color orig, Action<Color> setColor)
 {
     using (var colorDlg = new ColorDialog { Color = orig })
         if (colorDlg.ShowDialog() == DialogResult.OK)
         {
             setColor(colorDlg.Color);
             env.IfType((HexagonyEnv e) => { e.UpdateWatch(); });
         }
 }
示例#11
0
        private static void CheckIsAssignableFrom(ExecutionEnvironment executionEnvironment, Type dstType, Type srcType)
        {
            // byref types do not have a TypeHandle so we must treat these separately.
            if (dstType.IsByRef && srcType.IsByRef)
            {
                if (!dstType.Equals(srcType))
                    throw new ArgumentException(SR.Arg_DlgtTargMeth);
            }

            // Enable pointers (which don't necessarily have typehandles). todo:be able to handle intptr <-> pointer, check if we need to handle 
            // casts via pointer where the pointer types aren't identical
            if (dstType.Equals(srcType))
            {
                return;
            }

            // If assignment compatible in the normal way, allow
            if (executionEnvironment.IsAssignableFrom(dstType.TypeHandle, srcType.TypeHandle))
            {
                return;
            }

            // they are not compatible yet enums can go into each other if their underlying element type is the same
            // or into their equivalent integral type
            Type dstTypeUnderlying = dstType;
            if (dstType.GetTypeInfo().IsEnum)
            {
                dstTypeUnderlying = Enum.GetUnderlyingType(dstType);
            }
            Type srcTypeUnderlying = srcType;
            if (srcType.GetTypeInfo().IsEnum)
            {
                srcTypeUnderlying = Enum.GetUnderlyingType(srcType);
            }
            if (dstTypeUnderlying.Equals(srcTypeUnderlying))
            {
                return;
            }

            throw new ArgumentException(SR.Arg_DlgtTargMeth);
        }
示例#12
0
        void AddEvaluatedDebugItem(IExecutionEnvironment environment, int innerCount, IAssignValue assignValue, int update, DebugItem debugItem, string VariableLabelText, string NewFieldLabelText)
        {
            var oldValueResult = environment.Eval(assignValue.Name, update);
            var newValueResult = environment.Eval(assignValue.Value, update);

            AddDebugItem(new DebugItemStaticDataParams("", innerCount.ToString(CultureInfo.InvariantCulture)), debugItem);
            if (oldValueResult.IsWarewolfAtomResult && newValueResult.IsWarewolfAtomResult)
            {
                var valueResult  = newValueResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomResult;
                var scalarResult = oldValueResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomResult;
                if (valueResult != null && scalarResult != null)
                {
                    AddDebugItem(new DebugItemWarewolfAtomResult(ExecutionEnvironment.WarewolfAtomToString(scalarResult.Item), ExecutionEnvironment.WarewolfAtomToString(valueResult.Item), assignValue.Name, environment.EvalToExpression(assignValue.Value, update), VariableLabelText, NewFieldLabelText, "="), debugItem);
                }
            }
            else if (newValueResult.IsWarewolfAtomResult && oldValueResult.IsWarewolfAtomListresult)
            {
                AddDebugItem(new DebugItemWarewolfAtomListResult(null, newValueResult, environment.EvalToExpression(assignValue.Value, update), environment.EvalToExpression(assignValue.Name, update), VariableLabelText, NewFieldLabelText, "="), debugItem);
            }
            else if (oldValueResult.IsWarewolfAtomResult && newValueResult.IsWarewolfAtomListresult)
            {
                AddDebugItem(new DebugItemWarewolfAtomListResult(null, newValueResult, environment.EvalToExpression(assignValue.Value, update), environment.EvalToExpression(assignValue.Name, update), VariableLabelText, NewFieldLabelText, "="), debugItem);
            }
            else
            {
                if (oldValueResult.IsWarewolfAtomListresult && newValueResult.IsWarewolfAtomListresult)
                {
                    var recSetResult = oldValueResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomListresult;
                    AddDebugItem(new DebugItemWarewolfAtomListResult(recSetResult, newValueResult, environment.EvalToExpression(assignValue.Value, update), environment.EvalToExpression(assignValue.Name, update), VariableLabelText, NewFieldLabelText, "="), debugItem);
                }
            }
        }
        private DebugItem AddSingleInputDebugItem(IExecutionEnvironment environment, int innerCount, IAssignValue assignValue, int update)
        {
            var          debugItem         = new DebugItem();
            const string VariableLabelText = "Variable";
            const string NewFieldLabelText = "New Value";

            try
            {
                if (!DataListUtil.IsEvaluated(assignValue.Value))
                {
                    if (assignValue.Name.EndsWith("()]]"))
                    {
                        throw new Exception("Append data to array");
                    }
                    CommonFunctions.WarewolfEvalResult evalResult = environment.Eval(assignValue.Name, update);
                    AddDebugItem(new DebugItemStaticDataParams("", innerCount.ToString(CultureInfo.InvariantCulture)), debugItem);
                    if (evalResult.IsWarewolfAtomResult)
                    {
                        var scalarResult = evalResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomResult;
                        if (scalarResult != null)
                        {
                            AddDebugItem(new DebugItemWarewolfAtomResult(ExecutionEnvironment.WarewolfAtomToString(scalarResult.Item), assignValue.Value, environment.EvalToExpression(assignValue.Name, update), "", VariableLabelText, NewFieldLabelText, "="), debugItem);
                        }
                    }
                    else if (evalResult.IsWarewolfAtomListresult)
                    {
                        AddDebugItem(new DebugItemWarewolfAtomListResult(null, assignValue.Value, "", environment.EvalToExpression(assignValue.Name, update), VariableLabelText, NewFieldLabelText, "="), debugItem);
                    }
                }
                else if (DataListUtil.IsEvaluated(assignValue.Value))
                {
                    if (assignValue.Name.EndsWith("()]]"))
                    {
                        throw new Exception("Append data to array");
                    }
                    var oldValueResult = environment.Eval(assignValue.Name, update);
                    var newValueResult = environment.Eval(assignValue.Value, update);
                    AddDebugItem(new DebugItemStaticDataParams("", innerCount.ToString(CultureInfo.InvariantCulture)), debugItem);
                    if (oldValueResult.IsWarewolfAtomResult && newValueResult.IsWarewolfAtomResult)
                    {
                        var valueResult  = newValueResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomResult;
                        var scalarResult = oldValueResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomResult;
                        if (valueResult != null && scalarResult != null)
                        {
                            AddDebugItem(new DebugItemWarewolfAtomResult(ExecutionEnvironment.WarewolfAtomToString(scalarResult.Item), ExecutionEnvironment.WarewolfAtomToString(valueResult.Item), assignValue.Name, environment.EvalToExpression(assignValue.Value, update), VariableLabelText, NewFieldLabelText, "="), debugItem);
                        }
                    }
                    else if (newValueResult.IsWarewolfAtomResult && oldValueResult.IsWarewolfAtomListresult)
                    {
                        AddDebugItem(new DebugItemWarewolfAtomListResult(null, newValueResult, environment.EvalToExpression(assignValue.Value, update), assignValue.Name, VariableLabelText, NewFieldLabelText, "="), debugItem);
                    }
                    else if (oldValueResult.IsWarewolfAtomResult && newValueResult.IsWarewolfAtomListresult)
                    {
                        AddDebugItem(new DebugItemWarewolfAtomListResult(null, newValueResult, environment.EvalToExpression(assignValue.Value, update), assignValue.Name, VariableLabelText, NewFieldLabelText, "="), debugItem);
                    }
                    else if (oldValueResult.IsWarewolfAtomListresult && newValueResult.IsWarewolfAtomListresult)
                    {
                        var old = (CommonFunctions.WarewolfEvalResult.WarewolfAtomListresult)oldValueResult;
                        if (!old.Item.Any())
                        {
                            AddDebugItem(new DebugItemWarewolfAtomListResult(null, newValueResult, environment.EvalToExpression(assignValue.Value, update), assignValue.Name, VariableLabelText, NewFieldLabelText, "="), debugItem);
                        }
                        else
                        {
                            var recSetResult = oldValueResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomListresult;
                            AddDebugItem(new DebugItemWarewolfAtomListResult(recSetResult, newValueResult, environment.EvalToExpression(assignValue.Value, update), assignValue.Name, VariableLabelText, NewFieldLabelText, "="), debugItem);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (e.Message.Contains("ParseError"))
                {
                    AddDebugItem(new DebugItemWarewolfAtomResult("", assignValue.Value, environment.EvalToExpression(assignValue.Name, update), "", VariableLabelText, NewFieldLabelText, "="), debugItem);
                    return(debugItem);
                }
                string errorMessage;
                if (!ExecutionEnvironment.IsValidVariableExpression(assignValue.Name, out errorMessage, update))
                {
                    return(null);
                }
                AddDebugItem(new DebugItemStaticDataParams("", innerCount.ToString(CultureInfo.InvariantCulture)), debugItem);
                if (DataListUtil.IsEvaluated(assignValue.Value))
                {
                    var newValueResult = environment.Eval(assignValue.Value, update);

                    if (newValueResult.IsWarewolfAtomResult)
                    {
                        var valueResult = newValueResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomResult;
                        if (valueResult != null)
                        {
                            AddDebugItem(new DebugItemWarewolfAtomResult("", ExecutionEnvironment.WarewolfAtomToString(valueResult.Item), environment.EvalToExpression(assignValue.Name, update), assignValue.Value, VariableLabelText, NewFieldLabelText, "="), debugItem);
                        }
                    }
                    else if (newValueResult.IsWarewolfAtomListresult)
                    {
                        AddDebugItem(new DebugItemWarewolfAtomListResult(null, newValueResult, environment.EvalToExpression(assignValue.Value, update), assignValue.Name, VariableLabelText, NewFieldLabelText, "="), debugItem);
                    }
                }
                else
                {
                    AddDebugItem(new DebugItemWarewolfAtomResult("", assignValue.Value, environment.EvalToExpression(assignValue.Name, update), "", VariableLabelText, NewFieldLabelText, "="), debugItem);
                }
            }
            return(debugItem);
        }
示例#14
0
 public override TurtValue Eval(ExecutionEnvironment env) => TurtNil.NIL;
        static int DoCompilation(string compilerName, string compilerArgs, string working_dir, ExecutionEnvironment envVars, List <string> gacRoots, ref string output, ref string error)
        {
            output = Path.GetTempFileName();
            error  = Path.GetTempFileName();

            StreamWriter outwr = new StreamWriter(output);
            StreamWriter errwr = new StreamWriter(error);

            ProcessStartInfo pinfo = new ProcessStartInfo(compilerName, compilerArgs);

            pinfo.StandardErrorEncoding  = Encoding.UTF8;
            pinfo.StandardOutputEncoding = Encoding.UTF8;
            pinfo.WorkingDirectory       = working_dir;

            if (gacRoots.Count > 0)
            {
                // Create the gac prefix string
                string gacPrefix = string.Join("" + Path.PathSeparator, gacRoots.ToArray());
                string oldGacVar = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX");
                if (!string.IsNullOrEmpty(oldGacVar))
                {
                    gacPrefix += Path.PathSeparator + oldGacVar;
                }
                pinfo.EnvironmentVariables ["MONO_GAC_PREFIX"] = gacPrefix;
            }

            envVars.MergeTo(pinfo);

            pinfo.UseShellExecute        = false;
            pinfo.RedirectStandardOutput = true;
            pinfo.RedirectStandardError  = true;

            MonoDevelop.Core.Execution.ProcessWrapper pw = Runtime.ProcessService.StartProcess(pinfo, outwr, errwr, null);
            pw.WaitForOutput();
            int exitCode = pw.ExitCode;

            outwr.Close();
            errwr.Close();
            pw.Dispose();
            return(exitCode);
        }
示例#16
0
        private int DoCompilation(string compilerName, string responseFileName, TempFileCollection tf, string working_dir, ExecutionEnvironment envVars, ref string output)
        {
            StringWriter outwr = new StringWriter();

            try
            {
                ProcessStartInfo pinfo = new ProcessStartInfo(compilerName, "\"@" + responseFileName + "\"");
                pinfo.WorkingDirectory = working_dir;
                envVars.MergeTo(pinfo);

                pinfo.UseShellExecute        = false;
                pinfo.RedirectStandardOutput = true;
                pinfo.RedirectStandardError  = true;

                ProcessWrapper pw = Runtime.ProcessService.StartProcess(pinfo, outwr, outwr, null);
                pw.WaitForOutput();
                output = outwr.ToString();

                return(pw.ExitCode);
            }
            finally
            {
                if (outwr != null)
                {
                    outwr.Dispose();
                }
            }
        }
示例#17
0
 public abstract void Eval(ExecutionEnvironment env);
示例#18
0
 public abstract TurtValue Eval(ExecutionEnvironment env);
        public void GetDebugInputs_GivenMockEnvironment_ShouldAddDebugInputItems()
        {
            //---------------Set up test pack-------------------
            const string response = "{\"Location\": \"Paris\",\"Time\": \"May 29, 2013 - 09:00 AM EDT / 2013.05.29 1300 UTC\"," +
                                    "\"Wind\": \"from the NW (320 degrees) at 10 MPH (9 KT) (direction variable):0\"," +
                                    "\"Visibility\": \"greater than 7 mile(s):0\"," +
                                    "\"Temperature\": \"59 F (15 C)\"," +
                                    "\"DewPoint\": \"41 F (5 C)\"," +
                                    "\"RelativeHumidity\": \"51%\"," +
                                    "\"Pressure\": \"29.65 in. Hg (1004 hPa)\"," +
                                    "\"Status\": \"Success\"" +
                                    "}";
            var environment = new ExecutionEnvironment();

            environment.Assign("[[City]]", "PMB", 0);
            environment.Assign("[[CountryName]]", "South Africa", 0);
            environment.Assign("[[Post]]", "Some data", 0);
            var dsfWebPostActivity = new TestDsfWebPostActivity
            {
                Headers = new List <INameValue> {
                    new NameValue("Header 1", "[[City]]")
                },
                QueryString = "http://www.testing.com/[[CountryName]]",
                PostData    = "This is post:[[Post]]"
            };
            var serviceOutputs = new List <IServiceOutputMapping> {
                new ServiceOutputMapping("Location", "[[weather().Location]]", "weather"), new ServiceOutputMapping("Time", "[[weather().Time]]", "weather"), new ServiceOutputMapping("Wind", "[[weather().Wind]]", "weather"), new ServiceOutputMapping("Visibility", "[[Visibility]]", "")
            };

            dsfWebPostActivity.Outputs = serviceOutputs;
            var serviceXml = XmlResource.Fetch("WebService");
            var service    = new WebService(serviceXml)
            {
                RequestResponse = response
            };

            dsfWebPostActivity.OutputDescription = service.GetOutputDescription();
            dsfWebPostActivity.ResponseFromWeb   = response;
            var dataObjectMock = new Mock <IDSFDataObject>();

            dataObjectMock.Setup(o => o.Environment).Returns(environment);
            dataObjectMock.Setup(o => o.EsbChannel).Returns(new Mock <IEsbChannel>().Object);
            dsfWebPostActivity.ResourceID = InArgument <Guid> .FromValue(Guid.Empty);

            var cat = new Mock <IResourceCatalog>();
            var src = new WebSource {
                Address = "www.example.com"
            };

            cat.Setup(a => a.GetResource <WebSource>(It.IsAny <Guid>(), It.IsAny <Guid>())).Returns(src);
            dsfWebPostActivity.ResourceCatalog = cat.Object;
            //---------------Assert Precondition----------------
            Assert.IsNotNull(environment);
            Assert.IsNotNull(dsfWebPostActivity);
            //---------------Execute Test ----------------------
            var debugInputs = dsfWebPostActivity.GetDebugInputs(environment, 0);

            //---------------Test Result -----------------------
            Assert.IsNotNull(debugInputs);
            Assert.AreEqual(4, debugInputs.Count);
        }
        protected override void ExecuteTool(IDSFDataObject dataObject, int update)
        {
            var allErrors = new ErrorResultTO();

            InitializeDebug(dataObject);
            if (Result == null)
            {
                Result = string.Empty;
            }
            var toresultfields = Result.Split(',');
            var fromFields     = InFields.Split(',');
            var fromResultFieldresultfields = ResultFields.Split(',');

            try
            {
                PreExecution(dataObject, fromFields, update);
                if (String.IsNullOrEmpty(InFields))
                {
                    throw new Exception(string.Format(ErrorResource.Invalid, "In fields"));
                }
                if (String.IsNullOrEmpty(ResultFields))
                {
                    throw new Exception(string.Format(ErrorResource.Invalid, "from fields"));
                }
                if (toresultfields.Any(a => !ExecutionEnvironment.IsValidRecordSetIndex(a)))
                {
                    throw new Exception(string.Format(ErrorResource.Invalid, "result"));
                }
                if (fromFields.Any(a => !ExecutionEnvironment.IsValidRecordSetIndex(a)))
                {
                    throw new Exception(string.Format(ErrorResource.Invalid, "from"));
                }
                if (fromResultFieldresultfields.Any(a => !ExecutionEnvironment.IsValidRecordSetIndex(a)))
                {
                    throw new Exception(string.Format(ErrorResource.Invalid, "selected fields"));
                }
                if (toresultfields.Any(ExecutionEnvironment.IsScalar))
                {
                    throw new Exception(string.Format(ErrorResource.ScalarsNotAllowed, "'Result'"));
                }
                dataObject.Environment.AssignUnique(fromFields, fromResultFieldresultfields, toresultfields, update);
            }
            catch (Exception e)
            {
                Dev2Logger.Error("DSFUnique", e);
                allErrors.AddError(e.Message);
            }
            finally
            {
                PostExecute(dataObject, toresultfields, allErrors.HasErrors(), update);
                // Handle Errors
                var hasErrors = allErrors.HasErrors();
                if (hasErrors)
                {
                    DisplayAndWriteError("DsfUniqueActivity", allErrors);
                    foreach (var error in allErrors.FetchErrors())
                    {
                        dataObject.Environment.AddError(error);
                    }
                }

                if (dataObject.IsDebugMode())
                {
                    DispatchDebugState(dataObject, StateType.Before, update);
                    DispatchDebugState(dataObject, StateType.After, update);
                }
            }
        }
示例#21
0
        protected void RunTest(VirtualMachineTest test)
        {
            TestContext.WriteLine($"Running {test.GetType().FullName}");

            VirtualMachine       machine     = new VirtualMachine(_stateProvider, _storageProvider, _blockhashProvider, _specProvider, _logManager);
            ExecutionEnvironment environment = new ExecutionEnvironment();

            environment.Value            = test.Execution.Value;
            environment.CallDepth        = 0;
            environment.Sender           = test.Execution.Caller;
            environment.ExecutingAccount = test.Execution.Address;


            BlockHeader header = new BlockHeader(
                Keccak.OfAnEmptyString,
                Keccak.OfAnEmptySequenceRlp,
                test.Environment.CurrentCoinbase,
                test.Environment.CurrentDifficulty,
                test.Environment.CurrentNumber,
                (long)test.Environment.CurrentGasLimit,
                test.Environment.CurrentTimestamp, Bytes.Empty);

            environment.CurrentBlock = header;

            environment.GasPrice   = test.Execution.GasPrice;
            environment.InputData  = test.Execution.Data;
            environment.CodeInfo   = new CodeInfo(test.Execution.Code);
            environment.Originator = test.Execution.Origin;

            foreach (KeyValuePair <Address, AccountState> accountState in test.Pre)
            {
                foreach (KeyValuePair <UInt256, byte[]> storageItem in accountState.Value.Storage)
                {
                    _storageProvider.Set(new StorageCell(accountState.Key, storageItem.Key), storageItem.Value);
                    if (accountState.Key.Equals(test.Execution.Address))
                    {
                        _storageProvider.Set(new StorageCell(accountState.Key, storageItem.Key), storageItem.Value);
                    }
                }

                _stateProvider.UpdateCode(accountState.Value.Code);

                _stateProvider.CreateAccount(accountState.Key, accountState.Value.Balance);
                Keccak codeHash = _stateProvider.UpdateCode(accountState.Value.Code);
                _stateProvider.UpdateCodeHash(accountState.Key, codeHash, Olympic.Instance);
                for (int i = 0; i < accountState.Value.Nonce; i++)
                {
                    _stateProvider.IncrementNonce(accountState.Key);
                }
            }

            EvmState state = new EvmState((long)test.Execution.Gas, environment, ExecutionType.Transaction, false, true, false);

            _storageProvider.Commit();
            _stateProvider.Commit(Olympic.Instance);

            TransactionSubstate substate = machine.Run(state, NullTxTracer.Instance);

            if (test.Out == null)
            {
                Assert.NotNull(substate.Error);
                return;
            }

            Assert.True(Bytes.AreEqual(test.Out, substate.Output),
                        $"Exp: {test.Out.ToHexString(true)} != Actual: {substate.Output.ToHexString(true)}");
            Assert.AreEqual((long)test.Gas, state.GasAvailable, "gas available");
            foreach (KeyValuePair <Address, AccountState> accountState in test.Post)
            {
                bool    accountExists = _stateProvider.AccountExists(accountState.Key);
                UInt256 balance       = accountExists ? _stateProvider.GetBalance(accountState.Key) : 0;
                UInt256 nonce         = accountExists ? _stateProvider.GetNonce(accountState.Key) : 0;
                Assert.AreEqual(accountState.Value.Balance, balance, $"{accountState.Key} Balance");
                Assert.AreEqual(accountState.Value.Nonce, nonce, $"{accountState.Key} Nonce");

                // TODO: not testing properly 0 balance accounts
                if (accountExists)
                {
                    byte[] code = _stateProvider.GetCode(accountState.Key);
                    Assert.AreEqual(accountState.Value.Code, code, $"{accountState.Key} Code");
                }

                foreach (KeyValuePair <UInt256, byte[]> storageItem in accountState.Value.Storage)
                {
                    byte[] value = _storageProvider.Get(new StorageCell(accountState.Key, storageItem.Key));
                    Assert.True(Bytes.AreEqual(storageItem.Value, value),
                                $"Storage[{accountState.Key}_{storageItem.Key}] Exp: {storageItem.Value.ToHexString(true)} != Actual: {value.ToHexString(true)}");
                }
            }
        }
        public static BuildResult Compile(ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor)
        {
            var compilerParameters = (CSharpCompilerParameters)configuration.CompilationParameters ?? new CSharpCompilerParameters();
            var projectParameters  = (CSharpProjectParameters)configuration.ProjectParameters ?? new CSharpProjectParameters();

            FilePath outputName       = configuration.CompiledOutputName;
            string   responseFileName = Path.GetTempFileName();

            //make sure that the output file is writable
            if (File.Exists(outputName))
            {
                bool isWriteable = false;
                int  count       = 0;
                do
                {
                    try {
                        outputName.MakeWritable();
                        using (var stream = File.OpenWrite(outputName)) {
                            isWriteable = true;
                        }
                    } catch (Exception) {
                        Thread.Sleep(20);
                    }
                } while (count++ < 5 && !isWriteable);
                if (!isWriteable)
                {
                    MessageService.ShowError(string.Format(GettextCatalog.GetString("Can't lock file: {0}."), outputName));
                    return(null);
                }
            }

            //get the runtime
            TargetRuntime runtime = MonoDevelop.Core.Runtime.SystemAssemblyService.DefaultRuntime;
            DotNetProject project = configuration.ParentItem as DotNetProject;

            if (project != null)
            {
                runtime = project.TargetRuntime;
            }

            //get the compiler name
            string compilerName;

            try {
                compilerName = GetCompilerName(runtime, configuration.TargetFramework);
            } catch (Exception e) {
                string message = "Could not obtain a C# compiler";
                monitor.ReportError(message, e);
                return(null);
            }

            var sb = new StringBuilder();

            HashSet <string> alreadyAddedReference = new HashSet <string> ();

            var monoRuntime = runtime as MonoTargetRuntime;

            if (!compilerParameters.NoStdLib && (monoRuntime == null || monoRuntime.HasMultitargetingMcs))
            {
                string corlib = project.AssemblyContext.GetAssemblyFullName("mscorlib", project.TargetFramework);
                if (corlib != null)
                {
                    corlib = project.AssemblyContext.GetAssemblyLocation(corlib, project.TargetFramework);
                }
                if (corlib == null)
                {
                    var br = new BuildResult();
                    br.AddError(string.Format("Could not find mscorlib for framework {0}", project.TargetFramework.Id));
                    return(br);
                }
                AppendQuoted(sb, "/r:", corlib);
                sb.AppendLine("-nostdlib");
            }

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

            sb.AppendFormat("\"/out:{0}\"", outputName);
            sb.AppendLine();

            foreach (ProjectReference lib in projectItems.GetAll <ProjectReference> ())
            {
                if (lib.ReferenceType == ReferenceType.Project && !(lib.OwnerProject.ParentSolution.FindProjectByName(lib.Reference) is DotNetProject))
                {
                    continue;
                }
                string refPrefix = string.IsNullOrEmpty(lib.Aliases) ? "" : lib.Aliases + "=";
                foreach (string fileName in lib.GetReferencedFileNames(configSelector))
                {
                    switch (lib.ReferenceType)
                    {
                    case ReferenceType.Package:
                        SystemPackage pkg = lib.Package;
                        if (pkg == null)
                        {
                            string msg = string.Format(GettextCatalog.GetString("{0} could not be found or is invalid."), lib.Reference);
                            monitor.ReportWarning(msg);
                            continue;
                        }

                        if (alreadyAddedReference.Add(fileName))
                        {
                            AppendQuoted(sb, "/r:", refPrefix + fileName);
                        }

                        if (pkg.GacRoot != null && !gacRoots.Contains(pkg.GacRoot))
                        {
                            gacRoots.Add(pkg.GacRoot);
                        }
                        if (!string.IsNullOrEmpty(pkg.Requires))
                        {
                            foreach (string requiredPackage in pkg.Requires.Split(' '))
                            {
                                SystemPackage rpkg = runtime.AssemblyContext.GetPackage(requiredPackage);
                                if (rpkg == null)
                                {
                                    continue;
                                }
                                foreach (SystemAssembly assembly in rpkg.Assemblies)
                                {
                                    if (alreadyAddedReference.Add(assembly.Location))
                                    {
                                        AppendQuoted(sb, "/r:", assembly.Location);
                                    }
                                }
                            }
                        }
                        break;

                    default:
                        if (alreadyAddedReference.Add(fileName))
                        {
                            AppendQuoted(sb, "/r:", refPrefix + fileName);
                        }
                        break;
                    }
                }
            }

            string sysCore = project.AssemblyContext.GetAssemblyFullName("System.Core", project.TargetFramework);

            if (sysCore != null)
            {
                sysCore = project.AssemblyContext.GetAssemblyLocation(sysCore, project.TargetFramework);
                if (sysCore != null && !alreadyAddedReference.Contains(sysCore))
                {
                    AppendQuoted(sb, "/r:", sysCore);
                }
            }

            sb.AppendLine("/nologo");
            sb.Append("/warn:"); sb.Append(compilerParameters.WarningLevel.ToString());
            sb.AppendLine();

            if (configuration.SignAssembly)
            {
                if (File.Exists(configuration.AssemblyKeyFile))
                {
                    AppendQuoted(sb, "/keyfile:", configuration.AssemblyKeyFile);
                }
            }

            if (configuration.DebugMode)
            {
//				sb.AppendLine ("/debug:+");
                sb.AppendLine("/debug:full");
            }

            switch (compilerParameters.LangVersion)
            {
            case LangVersion.Default:
                break;

            case LangVersion.ISO_1:
                sb.AppendLine("/langversion:ISO-1");
                break;

            case LangVersion.ISO_2:
                sb.AppendLine("/langversion:ISO-2");
                break;

            default:
                string message = "Invalid LangVersion enum value '" + compilerParameters.LangVersion.ToString() + "'";
                monitor.ReportError(message, null);
                LoggingService.LogError(message);
                return(null);
            }

            // mcs default is + but others might not be
            if (compilerParameters.Optimize)
            {
                sb.AppendLine("/optimize+");
            }
            else
            {
                sb.AppendLine("/optimize-");
            }

            bool hasWin32Res = !string.IsNullOrEmpty(projectParameters.Win32Resource) && File.Exists(projectParameters.Win32Resource);

            if (hasWin32Res)
            {
                AppendQuoted(sb, "/win32res:", projectParameters.Win32Resource);
            }

            if (!string.IsNullOrEmpty(projectParameters.Win32Icon) && File.Exists(projectParameters.Win32Icon))
            {
                if (hasWin32Res)
                {
                    monitor.ReportWarning("Both Win32 icon and Win32 resource cannot be specified. Ignoring the icon.");
                }
                else
                {
                    AppendQuoted(sb, "/win32icon:", projectParameters.Win32Icon);
                }
            }

            if (projectParameters.CodePage != 0)
            {
                sb.AppendLine("/codepage:" + projectParameters.CodePage);
            }
            else if (runtime is MonoTargetRuntime)
            {
                sb.AppendLine("/codepage:utf8");
            }

            if (compilerParameters.UnsafeCode)
            {
                sb.AppendLine("-unsafe");
            }
            if (compilerParameters.NoStdLib)
            {
                sb.AppendLine("-nostdlib");
            }

            if (!string.IsNullOrEmpty(compilerParameters.PlatformTarget) && compilerParameters.PlatformTarget.ToLower() != "anycpu")
            {
                //HACK: to ignore the platform flag for Mono <= 2.4, because gmcs didn't support it
                if (runtime.RuntimeId == "Mono" && runtime.AssemblyContext.GetAssemblyLocation("Mono.Debugger.Soft", null) == null)
                {
                    LoggingService.LogWarning("Mono runtime '" + runtime.DisplayName +
                                              "' appears to be too old to support the 'platform' C# compiler flag.");
                }
                else
                {
                    sb.AppendLine("/platform:" + compilerParameters.PlatformTarget);
                }
            }

            if (compilerParameters.TreatWarningsAsErrors)
            {
                sb.AppendLine("-warnaserror");
                if (!string.IsNullOrEmpty(compilerParameters.WarningsNotAsErrors))
                {
                    sb.AppendLine("-warnaserror-:" + compilerParameters.WarningsNotAsErrors);
                }
            }

            if (compilerParameters.DefineSymbols.Length > 0)
            {
                string define_str = string.Join(";", compilerParameters.DefineSymbols.Split(new char [] { ',', ' ', ';' }, StringSplitOptions.RemoveEmptyEntries));
                if (define_str.Length > 0)
                {
                    AppendQuoted(sb, "/define:", define_str);
                    sb.AppendLine();
                }
            }

            CompileTarget ctarget = configuration.CompileTarget;

            if (!string.IsNullOrEmpty(projectParameters.MainClass))
            {
                sb.AppendLine("/main:" + projectParameters.MainClass);
                // mcs does not allow providing a Main class when compiling a dll
                // As a workaround, we compile as WinExe (although the output will still
                // have a .dll extension).
                if (ctarget == CompileTarget.Library)
                {
                    ctarget = CompileTarget.WinExe;
                }
            }

            switch (ctarget)
            {
            case CompileTarget.Exe:
                sb.AppendLine("/t:exe");
                break;

            case CompileTarget.WinExe:
                sb.AppendLine("/t:winexe");
                break;

            case CompileTarget.Library:
                sb.AppendLine("/t:library");
                break;
            }

            foreach (ProjectFile finfo in projectItems.GetAll <ProjectFile> ())
            {
                if (finfo.Subtype == Subtype.Directory)
                {
                    continue;
                }

                switch (finfo.BuildAction)
                {
                case "Compile":
                    AppendQuoted(sb, "", finfo.Name);
                    break;

                case "EmbeddedResource":
                    string fname = finfo.Name;
                    if (string.Compare(Path.GetExtension(fname), ".resx", true) == 0)
                    {
                        fname = Path.ChangeExtension(fname, ".resources");
                    }
                    sb.Append('"'); sb.Append("/res:");
                    sb.Append(fname); sb.Append(','); sb.Append(finfo.ResourceId);
                    sb.Append('"'); sb.AppendLine();
                    break;

                default:
                    continue;
                }
            }
            if (compilerParameters.GenerateXmlDocumentation)
            {
                AppendQuoted(sb, "/doc:", Path.ChangeExtension(outputName, ".xml"));
            }

            if (!string.IsNullOrEmpty(compilerParameters.AdditionalArguments))
            {
                sb.AppendLine(compilerParameters.AdditionalArguments);
            }

            if (!string.IsNullOrEmpty(compilerParameters.NoWarnings))
            {
                AppendQuoted(sb, "/nowarn:", compilerParameters.NoWarnings);
            }

            if (runtime.RuntimeId == "MS.NET")
            {
                sb.AppendLine("/fullpaths");
                sb.AppendLine("/utf8output");
            }

            string output = "";
            string error  = "";

            File.WriteAllText(responseFileName, sb.ToString());



            monitor.Log.WriteLine(compilerName + " /noconfig " + sb.ToString().Replace('\n', ' '));

            string workingDir = ".";

            if (configuration.ParentItem != null)
            {
                workingDir = configuration.ParentItem.BaseDirectory;
                if (workingDir == null)
                {
                    // Dummy projects created for single files have no filename
                    // and so no BaseDirectory.
                    // This is a workaround for a bug in
                    // ProcessStartInfo.WorkingDirectory - not able to handle null
                    workingDir = ".";
                }
            }

            LoggingService.LogInfo(compilerName + " " + sb.ToString());

            ExecutionEnvironment envVars = runtime.GetToolsExecutionEnvironment(project.TargetFramework);
            string cargs = "/noconfig @\"" + responseFileName + "\"";

            int exitCode = DoCompilation(compilerName, cargs, workingDir, envVars, gacRoots, ref output, ref error);

            BuildResult result = ParseOutput(output, error);

            if (result.CompilerOutput.Trim().Length != 0)
            {
                monitor.Log.WriteLine(result.CompilerOutput);
            }

            //if compiler crashes, output entire error string
            if (result.ErrorCount == 0 && exitCode != 0)
            {
                try {
                    monitor.Log.Write(File.ReadAllText(error));
                } catch (IOException) {
                }
                result.AddError("The compiler appears to have crashed. Check the build output pad for details.");
                LoggingService.LogError("C# compiler crashed. Response file '{0}', stdout file '{1}', stderr file '{2}'",
                                        responseFileName, output, error);
            }
            else
            {
                FileService.DeleteFile(responseFileName);
                FileService.DeleteFile(output);
                FileService.DeleteFile(error);
            }
            return(result);
        }
示例#23
0
        private (IEnumerable <NameValue> head, string query, string data) ConfigureHttp(IDSFDataObject dataObject, int update)
        {
            var head  = Headers.Select(a => new NameValue(ExecutionEnvironment.WarewolfEvalResultToString(dataObject.Environment.Eval(a.Name, update)), ExecutionEnvironment.WarewolfEvalResultToString(dataObject.Environment.Eval(a.Value, update))));
            var query = ExecutionEnvironment.WarewolfEvalResultToString(dataObject.Environment.Eval(QueryString, update));

            return(head, query, null);
        }
示例#24
0
 public override void Eval(ExecutionEnvironment env)
 {
     env.PenUp();
 }
示例#25
0
        public void Execute(ExecutionEnvironment env)
        {
            var intValue = env.Symbols.Get(_symbolName).IntegerValue;

            env.PushNumber(intValue);
        }
示例#26
0
 public IEnumerable <IGrouping <string, TItems> > Exports <TItems>(IPackage package, ExecutionEnvironment environment = null) where TItems : IExportItem
 {
     return(_providers.SelectMany(x => x.Items <TItems>(package, environment)));
 }
        public void DsfWebDeleteActivity_Delete_WithValidWebResponse_ShouldSetVariables()
        {
            //------------Setup for test--------------------------
            const string response = "{\"Location\": \"Paris\",\"Time\": \"May 29, 2013 - 09:00 AM EDT / 2013.05.29 1300 UTC\"," +
                                    "\"Wind\": \"from the NW (320 degrees) at 10 MPH (9 KT) (direction variable):0\"," +
                                    "\"Visibility\": \"greater than 7 mile(s):0\"," +
                                    "\"Temperature\": \"59 F (15 C)\"," +
                                    "\"DewPoint\": \"41 F (5 C)\"," +
                                    "\"RelativeHumidity\": \"51%\"," +
                                    "\"Pressure\": \"29.65 in. Hg (1004 hPa)\"," +
                                    "\"Status\": \"Success\"" +
                                    "}";
            var environment = new ExecutionEnvironment();

            environment.Assign("[[City]]", "PMB", 0);
            environment.Assign("[[CountryName]]", "South Africa", 0);
            var dsfWebDeleteActivity = CreateTestDeleteActivity();
            var serviceInputs        = new List <IServiceInput> {
                new ServiceInput("CityName", "[[City]]"), new ServiceInput("Country", "[[CountryName]]")
            };
            var serviceOutputs = new List <IServiceOutputMapping> {
                new ServiceOutputMapping("Location", "[[weather().Location]]", "weather"), new ServiceOutputMapping("Time", "[[weather().Time]]", "weather"), new ServiceOutputMapping("Wind", "[[weather().Wind]]", "weather"), new ServiceOutputMapping("Visibility", "[[Visibility]]", "")
            };

            dsfWebDeleteActivity.Inputs  = serviceInputs;
            dsfWebDeleteActivity.Outputs = serviceOutputs;
            var serviceXml = XmlResource.Fetch("WebService");
            var service    = new WebService(serviceXml)
            {
                RequestResponse = response
            };

            dsfWebDeleteActivity.OutputDescription = service.GetOutputDescription();
            dsfWebDeleteActivity.ResponseFromWeb   = response;
            dsfWebDeleteActivity.ResourceCatalog   = new Mock <IResourceCatalog>().Object;
            var dataObjectMock = new Mock <IDSFDataObject>();

            dataObjectMock.Setup(o => o.Environment).Returns(environment);
            dataObjectMock.Setup(o => o.EsbChannel).Returns(new Mock <IEsbChannel>().Object);
            dsfWebDeleteActivity.ResourceID = InArgument <Guid> .FromValue(Guid.Empty);

            dsfWebDeleteActivity.QueryString = "";
            //dsfWebPostActivity.PostData = "";
            dsfWebDeleteActivity.SourceId = Guid.Empty;
            dsfWebDeleteActivity.Headers  = new List <INameValue>();
            //------------Execute Test---------------------------
            dsfWebDeleteActivity.Execute(dataObjectMock.Object, 0);
            //------------Assert Results-------------------------
            Assert.IsNotNull(dsfWebDeleteActivity.OutputDescription);
            Assert.AreEqual("greater than 7 mile(s):0", ExecutionEnvironment.WarewolfEvalResultToString(environment.Eval("[[Visibility]]", 0)));
            Assert.AreEqual("Paris", ExecutionEnvironment.WarewolfEvalResultToString(environment.Eval("[[weather().Location]]", 0)));
            Assert.AreEqual("May 29, 2013 - 09:00 AM EDT / 2013.05.29 1300 UTC", ExecutionEnvironment.WarewolfEvalResultToString(environment.Eval("[[weather().Time]]", 0)));
            Assert.AreEqual("from the NW (320 degrees) at 10 MPH (9 KT) (direction variable):0", ExecutionEnvironment.WarewolfEvalResultToString(environment.Eval("[[weather().Wind]]", 0)));
        }
示例#28
0
        /// <summary>
        /// Common CreateDelegate worker. NOTE: If the method signature is not compatible, this method returns null rather than throwing an ArgumentException.
        /// This is needed to support the api overloads that have a "throwOnBindFailure" parameter.
        /// </summary>
        internal Delegate CreateDelegateNoThrowOnBindFailure(RuntimeTypeInfo runtimeDelegateType, Object target, bool allowClosed)
        {
            Debug.Assert(runtimeDelegateType.IsDelegate);

            ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment;
            MethodInfo           invokeMethod         = runtimeDelegateType.GetInvokeMethod();

            // Make sure the return type is assignment-compatible.
            if (!IsAssignableFrom(executionEnvironment, invokeMethod.ReturnParameter.ParameterType, this.ReturnParameter.ParameterType))
            {
                return(null);
            }

            IList <ParameterInfo>       delegateParameters          = invokeMethod.GetParametersNoCopy();
            IList <ParameterInfo>       targetParameters            = this.GetParametersNoCopy();
            IEnumerator <ParameterInfo> delegateParameterEnumerator = delegateParameters.GetEnumerator();
            IEnumerator <ParameterInfo> targetParameterEnumerator   = targetParameters.GetEnumerator();

            bool isStatic = this.IsStatic;
            bool isOpen;

            if (isStatic)
            {
                if (delegateParameters.Count == targetParameters.Count)
                {
                    // Open static: This is the "typical" case of calling a static method.
                    isOpen = true;
                    if (target != null)
                    {
                        return(null);
                    }
                }
                else
                {
                    // Closed static: This is the "weird" v2.0 case where the delegate is closed over the target method's first parameter.
                    //   (it make some kinda sense if you think of extension methods.)
                    if (!allowClosed)
                    {
                        return(null);
                    }
                    isOpen = false;
                    if (!targetParameterEnumerator.MoveNext())
                    {
                        return(null);
                    }
                    if (target != null && !IsAssignableFrom(executionEnvironment, targetParameterEnumerator.Current.ParameterType, target.GetType()))
                    {
                        return(null);
                    }
                }
            }
            else
            {
                if (delegateParameters.Count == targetParameters.Count)
                {
                    // Closed instance: This is the "typical" case of invoking an instance method.
                    isOpen = false;
                    if (!allowClosed)
                    {
                        return(null);
                    }
                    if (target != null && !IsAssignableFrom(executionEnvironment, this.DeclaringType, target.GetType()))
                    {
                        return(null);
                    }
                }
                else
                {
                    // Open instance: This is the "weird" v2.0 case where the delegate has a leading extra parameter that's assignable to the target method's
                    // declaring type.
                    if (!delegateParameterEnumerator.MoveNext())
                    {
                        return(null);
                    }
                    isOpen = true;
                    if (!IsAssignableFrom(executionEnvironment, this.DeclaringType, delegateParameterEnumerator.Current.ParameterType))
                    {
                        return(null);
                    }
                    if (target != null)
                    {
                        return(null);
                    }
                }
            }

            // Verify that the parameters that the delegate and method have in common are assignment-compatible.
            while (delegateParameterEnumerator.MoveNext())
            {
                if (!targetParameterEnumerator.MoveNext())
                {
                    return(null);
                }
                if (!IsAssignableFrom(executionEnvironment, targetParameterEnumerator.Current.ParameterType, delegateParameterEnumerator.Current.ParameterType))
                {
                    return(null);
                }
            }
            if (targetParameterEnumerator.MoveNext())
            {
                return(null);
            }

            return(CreateDelegateWithoutSignatureValidation(runtimeDelegateType, target, isStatic: isStatic, isOpen: isOpen));
        }
        public void DsfWebDeleteActivity_Execute_WithValidXmlEscaped_ShouldSetVariables()
        {
            //------------Setup for test--------------------------
            const string response = "<CurrentWeather>" +
                                    "<Location>&lt;Paris&gt;</Location>" +
                                    "<Time>May 29, 2013 - 09:00 AM EDT / 2013.05.29 1300 UTC</Time>" +
                                    "<Wind>from the NW (320 degrees) at 10 MPH (9 KT) (direction variable):0</Wind>" +
                                    "<Visibility>&lt;greater than 7 mile(s):0&gt;</Visibility>" +
                                    "<Temperature> 59 F (15 C)</Temperature>" +
                                    "<DewPoint> 41 F (5 C)</DewPoint>" +
                                    "<RelativeHumidity> 51%</RelativeHumidity>" +
                                    "<Pressure> 29.65 in. Hg (1004 hPa)</Pressure>" +
                                    "<Status>Success</Status>" +
                                    "</CurrentWeather>";
            var environment = new ExecutionEnvironment();

            environment.Assign("[[City]]", "PMB", 0);
            environment.Assign("[[CountryName]]", "South Africa", 0);
            var dsfWebDeleteActivity = CreateTestDeleteActivity();
            var serviceInputs        = new List <IServiceInput> {
                new ServiceInput("CityName", "[[City]]"), new ServiceInput("Country", "[[CountryName]]")
            };
            var serviceOutputs = new List <IServiceOutputMapping>
            {
                new ServiceOutputMapping("Location", "[[weather().Location]]", "weather")
                , new ServiceOutputMapping("Time", "[[weather().Time]]", "weather")
                , new ServiceOutputMapping("Wind", "[[weather().Wind]]", "weather")
                , new ServiceOutputMapping("Visibility", "[[Visibility]]", "")
            };

            dsfWebDeleteActivity.Inputs  = serviceInputs;
            dsfWebDeleteActivity.Outputs = serviceOutputs;
            var serviceXml = XmlResource.Fetch("WebService");
            var service    = new WebService(serviceXml)
            {
                RequestResponse = response
            };

            dsfWebDeleteActivity.OutputDescription = service.GetOutputDescription();
            dsfWebDeleteActivity.ResponseFromWeb   = response;
            var dataObjectMock = new Mock <IDSFDataObject>();

            dataObjectMock.Setup(o => o.Environment).Returns(environment);
            dataObjectMock.Setup(o => o.EsbChannel).Returns(new Mock <IEsbChannel>().Object);
            dsfWebDeleteActivity.ResourceID = InArgument <Guid> .FromValue(Guid.Empty);

            dsfWebDeleteActivity.QueryString = "";
            //dsfWebPostActivity.PostData = "";
            dsfWebDeleteActivity.SourceId = Guid.Empty;
            dsfWebDeleteActivity.Headers  = new List <INameValue>();
            //------------Execute Test---------------------------
            dsfWebDeleteActivity.Execute(dataObjectMock.Object, 0);
            //------------Assert Results-------------------------
            Assert.IsNotNull(dsfWebDeleteActivity.OutputDescription);
            var visibility = ExecutionEnvironment.WarewolfEvalResultToString(environment.Eval("[[Visibility]]", 0));

            Assert.AreEqual("<greater than 7 mile(s):0>", visibility);
            var location = ExecutionEnvironment.WarewolfEvalResultToString(environment.Eval("[[weather().Location]]", 0));

            Assert.AreEqual("<Paris>", location);
            var time = ExecutionEnvironment.WarewolfEvalResultToString(environment.Eval("[[weather().Time]]", 0));

            Assert.AreEqual("May 29, 2013 - 09:00 AM EDT / 2013.05.29 1300 UTC", time);
            var wind = ExecutionEnvironment.WarewolfEvalResultToString(environment.Eval("[[weather().Wind]]", 0));

            Assert.AreEqual("from the NW (320 degrees) at 10 MPH (9 KT) (direction variable):0", wind);
        }
        private void AddSingleDebugOutputItem(IExecutionEnvironment environment, int innerCount, IAssignValue assignValue, int update)
        {
            const string VariableLabelText = "";
            const string NewFieldLabelText = "";
            var          debugItem         = new DebugItem();

            try
            {
                if (!DataListUtil.IsEvaluated(assignValue.Value))
                {
                    var evalResult = environment.Eval(assignValue.Name, update);
                    AddDebugItem(new DebugItemStaticDataParams("", innerCount.ToString(CultureInfo.InvariantCulture)), debugItem);
                    if (evalResult.IsWarewolfAtomResult)
                    {
                        var scalarResult = evalResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomResult;
                        if (scalarResult != null)
                        {
                            AddDebugItem(new DebugItemWarewolfAtomResult(ExecutionEnvironment.WarewolfAtomToString(scalarResult.Item), assignValue.Value, environment.EvalToExpression(assignValue.Name, update), "", VariableLabelText, NewFieldLabelText, "="), debugItem);
                        }
                    }
                    else if (evalResult.IsWarewolfAtomListresult)
                    {
                        var recSetResult = evalResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomListresult;
                        if (recSetResult != null)
                        {
                            AddDebugItem(new DebugItemWarewolfAtomListResult(recSetResult, "", "", environment.EvalToExpression(assignValue.Name, update), VariableLabelText, NewFieldLabelText, "="), debugItem);
                        }
                    }
                }
                else if (DataListUtil.IsEvaluated(assignValue.Value))
                {
                    var evalResult = environment.Eval(assignValue.Name, update);
                    AddDebugItem(new DebugItemStaticDataParams("", innerCount.ToString(CultureInfo.InvariantCulture)), debugItem);
                    if (evalResult.IsWarewolfAtomResult)
                    {
                        var scalarResult = evalResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomResult;
                        if (scalarResult != null)
                        {
                            AddDebugItem(new DebugItemWarewolfAtomResult(ExecutionEnvironment.WarewolfAtomToString(scalarResult.Item), "", environment.EvalToExpression(assignValue.Name, update), "", VariableLabelText, NewFieldLabelText, "="), debugItem);
                        }
                    }
                    var evalResult2 = environment.Eval(assignValue.Value, update);
                    if (evalResult.IsWarewolfAtomListresult)
                    {
                        var recSetResult = evalResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomListresult;
                        if (recSetResult != null)
                        {
                            // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                            if (DataListUtil.GetRecordsetIndexType(assignValue.Name) == enRecordsetIndexType.Blank)
                            {
                                AddDebugItem(new DebugItemWarewolfAtomListResult(recSetResult, evalResult2, "", assignValue.Name, VariableLabelText, NewFieldLabelText, "="), debugItem);
                            }
                            else
                            {
                                AddDebugItem(new DebugItemWarewolfAtomListResult(recSetResult, environment.EvalToExpression(assignValue.Value, update), "", assignValue.Name, VariableLabelText, NewFieldLabelText, "="), debugItem);
                            }
                        }
                    }
                }
            }
            catch (NullValueInVariableException)
            {
                AddDebugItem(new DebugItemWarewolfAtomResult("", assignValue.Value, "", environment.EvalToExpression(assignValue.Name, update), VariableLabelText, NewFieldLabelText, "="), debugItem);
            }
            _debugOutputs.Add(debugItem);
        }
        public void DsfWebDeleteActivity_ExecutionImpl_ResponseManager_PushResponseIntoEnvironment_GivenJsonResponse_MappedToRecodSet_ShouldSucess()
        {
            //-----------------------Arrange-------------------------
            const string json                  = "{\"Messanger\":\"jSon response from the request\"}";
            var          response              = Convert.ToBase64String(json.ToBytesArray());
            const string mappingFrom           = "mapFrom";
            const string recordSet             = "recset";
            const string mapTo                 = "mapTo";
            const string variableNameMappingTo = "[[recset().mapTo]]";

            var environment = new ExecutionEnvironment();

            var mockEsbChannel           = new Mock <IEsbChannel>();
            var mockDSFDataObject        = new Mock <IDSFDataObject>();
            var mockExecutionEnvironment = new Mock <IExecutionEnvironment>();

            var errorResultTO = new ErrorResultTO();

            using (var service = new WebService(XmlResource.Fetch("WebService"))
            {
                RequestResponse = response
            })
            {
                mockDSFDataObject.Setup(o => o.Environment).Returns(environment);
                mockDSFDataObject.Setup(o => o.EsbChannel).Returns(new Mock <IEsbChannel>().Object);

                var dsfWebGetActivity = new TestDsfWebDeleteActivity
                {
                    OutputDescription = service.GetOutputDescription(),
                    ResourceID        = InArgument <Guid> .FromValue(Guid.Empty),
                    QueryString       = "test Query",
                    Headers           = new List <INameValue>(),
                    ResponseFromWeb   = response,
                    IsObject          = false,
                    Outputs           = new List <IServiceOutputMapping>
                    {
                        {
                            new ServiceOutputMapping
                            {
                                MappedFrom    = mappingFrom,
                                MappedTo      = mapTo,
                                RecordSetName = recordSet
                            }
                        }
                    }
                };
                //-----------------------Act-----------------------------
                dsfWebGetActivity.TestExecutionImpl(mockEsbChannel.Object, mockDSFDataObject.Object, "Test Inputs", "Test Outputs", out errorResultTO, 0);
                //-----------------------Assert--------------------------
                Assert.IsFalse(errorResultTO.HasErrors());

                //assert first DataSourceShapes
                var resourceManager   = dsfWebGetActivity.ResponseManager;
                var outputDescription = resourceManager.OutputDescription;
                var dataShapes        = outputDescription.DataSourceShapes;
                var paths             = dataShapes.First().Paths;
                Assert.IsNotNull(outputDescription);
                Assert.AreEqual("Messanger", paths.First().ActualPath);
                Assert.AreEqual("Messanger", paths.First().DisplayPath);
                Assert.AreEqual(variableNameMappingTo, paths.First().OutputExpression);
                Assert.AreEqual("jSon response from the request", paths.First().SampleData);

                //assert execution environment
                var envirVariable = environment.Eval(variableNameMappingTo, 0);
                var resultItem    = (envirVariable as CommonFunctions.WarewolfEvalResult.WarewolfAtomListresult).Item;
                Assert.IsNotNull(envirVariable);
                if (resultItem.First() is DataStorage.WarewolfAtom.DataString firstItem)
                {
                    Assert.AreEqual("jSon response from the request", firstItem.Item);
                }
                else
                {
                    Assert.Fail("expected jSon response from the request");
                }
            }
        }
        private static async Task <PipelinedDocumentQueryExecutionContext> CreateHelperAsync(
            ExecutionEnvironment executionEnvironment,
            CosmosQueryClient queryClient,
            QueryInfo queryInfo,
            int initialPageSize,
            string requestContinuation,
            Func <string, Task <IDocumentQueryExecutionComponent> > createOrderByQueryExecutionContext,
            Func <string, Task <IDocumentQueryExecutionComponent> > createParallelQueryExecutionContext)
        {
            Func <string, Task <IDocumentQueryExecutionComponent> > createComponentFunc;

            if (queryInfo.HasOrderBy)
            {
                createComponentFunc = createOrderByQueryExecutionContext;
            }
            else
            {
                createComponentFunc = createParallelQueryExecutionContext;
            }

            if (queryInfo.HasAggregates && !queryInfo.HasGroupBy)
            {
                Func <string, Task <IDocumentQueryExecutionComponent> > createSourceCallback = createComponentFunc;
                createComponentFunc = async(continuationToken) =>
                {
                    return(await AggregateDocumentQueryExecutionComponent.CreateAsync(
                               executionEnvironment,
                               queryClient,
                               queryInfo.Aggregates,
                               queryInfo.GroupByAliasToAggregateType,
                               queryInfo.GroupByAliases,
                               queryInfo.HasSelectValue,
                               continuationToken,
                               createSourceCallback));
                };
            }

            if (queryInfo.HasDistinct)
            {
                Func <string, Task <IDocumentQueryExecutionComponent> > createSourceCallback = createComponentFunc;
                createComponentFunc = async(continuationToken) =>
                {
                    return(await DistinctDocumentQueryExecutionComponent.CreateAsync(
                               queryClient,
                               continuationToken,
                               createSourceCallback,
                               queryInfo.DistinctType));
                };
            }

            if (queryInfo.HasGroupBy)
            {
                Func <string, Task <IDocumentQueryExecutionComponent> > createSourceCallback = createComponentFunc;
                createComponentFunc = async(continuationToken) =>
                {
                    return(await GroupByDocumentQueryExecutionComponent.CreateAsync(
                               queryClient,
                               continuationToken,
                               createSourceCallback,
                               queryInfo.GroupByAliasToAggregateType,
                               queryInfo.GroupByAliases,
                               queryInfo.HasSelectValue));
                };
            }

            if (queryInfo.HasOffset)
            {
                Func <string, Task <IDocumentQueryExecutionComponent> > createSourceCallback = createComponentFunc;
                createComponentFunc = async(continuationToken) =>
                {
                    return(await SkipDocumentQueryExecutionComponent.CreateAsync(
                               queryInfo.Offset.Value,
                               continuationToken,
                               createSourceCallback));
                };
            }

            if (queryInfo.HasLimit)
            {
                Func <string, Task <IDocumentQueryExecutionComponent> > createSourceCallback = createComponentFunc;
                createComponentFunc = async(continuationToken) =>
                {
                    return(await TakeDocumentQueryExecutionComponent.CreateLimitDocumentQueryExecutionComponentAsync(
                               queryClient,
                               queryInfo.Limit.Value,
                               continuationToken,
                               createSourceCallback));
                };
            }

            if (queryInfo.HasTop)
            {
                Func <string, Task <IDocumentQueryExecutionComponent> > createSourceCallback = createComponentFunc;
                createComponentFunc = async(continuationToken) =>
                {
                    return(await TakeDocumentQueryExecutionComponent.CreateTopDocumentQueryExecutionComponentAsync(
                               queryClient,
                               queryInfo.Top.Value,
                               continuationToken,
                               createSourceCallback));
                };
            }

            return(new PipelinedDocumentQueryExecutionContext(
                       await createComponentFunc(requestContinuation), initialPageSize));
        }
示例#33
0
 public abstract void Execute(ExecutionEnvironment executionEnvironment);
示例#34
0
		/// <summary>
		/// Initializes this DualityApp. Should be called before performing any operations withing Duality.
		/// </summary>
		/// <param name="context">The <see cref="ExecutionContext"/> in which Duality runs.</param>
		/// <param name="args">
		/// Command line arguments to run this DualityApp with. 
		/// Usually these are just the ones from the host application, passed on.
		/// </param>
		public static void Init(ExecutionEnvironment env = ExecutionEnvironment.Unknown, ExecutionContext context = ExecutionContext.Unknown, string[] args = null)
		{
			if (initialized) return;

			// Set main thread
			mainThread = Thread.CurrentThread;

			// Process command line options
			if (args != null)
			{
				int logArgIndex = args.IndexOfFirst("logfile");
				if (logArgIndex != -1 && logArgIndex + 1 < args.Length) logArgIndex++;
				else logArgIndex = -1;

				// Enter debug mode
				if (args.Contains(CmdArgDebug)) System.Diagnostics.Debugger.Launch();
				// Run from editor
				if (args.Contains(CmdArgEditor)) runFromEditor = true;
				// Set logfile path
				if (logArgIndex != -1)
				{
					logfilePath = args[logArgIndex];
					if (string.IsNullOrWhiteSpace(Path.GetExtension(logfilePath)))
						logfilePath += ".txt";
				}
			}

			environment = env;
			execContext = context;

			// Initialize Logfile
			try
			{
				logfile = new StreamWriter(logfilePath);
				logfile.AutoFlush = true;
				logfileOutput = new TextWriterLogOutput(logfile);
				Log.Game.AddOutput(logfileOutput);
				Log.Core.AddOutput(logfileOutput);
				Log.Editor.AddOutput(logfileOutput);
			}
			catch (Exception e)
			{
				Log.Core.WriteWarning("Text Logfile unavailable: {0}", Log.Exception(e));
			}

			// Assure Duality is properly terminated in any case and register additional AppDomain events
			AppDomain.CurrentDomain.ProcessExit			+= CurrentDomain_ProcessExit;
			AppDomain.CurrentDomain.UnhandledException	+= CurrentDomain_UnhandledException;
			AppDomain.CurrentDomain.AssemblyResolve		+= CurrentDomain_AssemblyResolve;
			AppDomain.CurrentDomain.AssemblyLoad		+= CurrentDomain_AssemblyLoad;

			sound = new SoundDevice();
			LoadPlugins();
			LoadAppData();
			LoadUserData();
			
			// Determine available and default graphics modes
			int[] aaLevels = new int[] { 0, 2, 4, 6, 8, 16 };
			foreach (int samplecount in aaLevels)
			{
				GraphicsMode mode = new GraphicsMode(32, 24, 0, samplecount, new OpenTK.Graphics.ColorFormat(0), 2, false);
				if (!availModes.Contains(mode)) availModes.Add(mode);
			}
			int highestAALevel = MathF.RoundToInt(MathF.Log(MathF.Max(availModes.Max(m => m.Samples), 1.0f), 2.0f));
			int targetAALevel = highestAALevel;
			if (appData.MultisampleBackBuffer)
			{
				switch (userData.AntialiasingQuality)
				{
					case AAQuality.High:	targetAALevel = highestAALevel;		break;
					case AAQuality.Medium:	targetAALevel = highestAALevel / 2; break;
					case AAQuality.Low:		targetAALevel = highestAALevel / 4; break;
					case AAQuality.Off:		targetAALevel = 0;					break;
				}
			}
			else
			{
				targetAALevel = 0;
			}
			int targetSampleCount = MathF.RoundToInt(MathF.Pow(2.0f, targetAALevel));
			defaultMode = availModes.LastOrDefault(m => m.Samples <= targetSampleCount) ?? availModes.Last();

			// Initial changed event
			OnAppDataChanged();
			OnUserDataChanged();

			Formatter.InitDefaultMethod();
			joysticks.AddGlobalDevices();
			gamepads.AddGlobalDevices();

			Log.Core.Write(
				"DualityApp initialized" + Environment.NewLine +
				"Debug Mode: {0}" + Environment.NewLine +
				"Command line arguments: {1}" + Environment.NewLine +
				"Is64BitProcess: {2}",
				System.Diagnostics.Debugger.IsAttached,
				args != null ? args.ToString(", ") : "null",
				Environment.Is64BitProcess);

			initialized = true;
			InitPlugins();
		}
示例#35
0
        static void Main(string[] args)
        {
            var appData = ExecutionEnvironment.GetApplicationMetadata();

            Log.Info(appData);

            _consoleOptions = new ConsoleOptions(args);

            if (_consoleOptions.ShowHelp)
            {
                Console.WriteLine("Options:");
                _consoleOptions.OptionSet.WriteOptionDescriptions(Console.Out);
                return;
            }

            CapturePi.DoMatMagic("CreateCapture");

            var noCaptureGrabs = new[] { Mode.simple, Mode.pantiltjoy, Mode.ipReport };
            var i2cRequired    = new[] { Mode.pantiltface, Mode.pantiltjoy, Mode.pantiltcolour, Mode.pantiltmultimode };

            ICaptureGrab capture = null;

            if (!noCaptureGrabs.Contains(_consoleOptions.Mode))
            {
                var config = CaptureConfig.Parse(_consoleOptions.CaptureConfig);
                capture = BuildCaptureGrabber(config);
                Log.Info($"Requested capture {capture.RequestedConfig}");
            }

            IPanTiltMechanism panTiltMech = null;
            IScreen           screen      = null;

            if (i2cRequired.Contains(_consoleOptions.Mode))
            {
                var pwmDeviceFactory = new Pca9685DeviceFactory();
                var pwmDevice        = pwmDeviceFactory.GetDevice(_consoleOptions.UseFakeDevice);
                panTiltMech = new PanTiltMechanism(pwmDevice);
                screen      = new ConsoleScreen();
                screen.Clear();
            }
            else
            {
                Log.Info("Pan Tilt is not required");
            }

            IRunner runner;

            Log.Info(_consoleOptions);
            switch (_consoleOptions.Mode)
            {
            case Mode.noop:
                var noopRunner = new NoopRunner(capture);
                noopRunner.ReportFramesPerSecond = true;
                runner = noopRunner;
                break;

            case Mode.simple: runner = new SimpleCv();
                break;

            case Mode.colourdetect:
                var colorDetector = new ColorDetectRunner(capture);
                if (_consoleOptions.HasColourSettings)
                {
                    colorDetector.Settings = _consoleOptions.ColourSettings;
                }
                runner = colorDetector;
                break;

            case Mode.haar:
                var relativePath    = $@"haarcascades{Path.DirectorySeparatorChar}haarcascade_frontalface_default.xml";
                var cascadeFilename = Path.Combine(appData.ExeFolder, relativePath);
                var cascadeContent  = File.ReadAllText(cascadeFilename);
                runner = new CascadeRunner(capture, cascadeContent);
                break;

            case Mode.servosort:
                runner = new ServoSorter(capture, _consoleOptions);
                break;

            case Mode.pantiltjoy:
                var joyController = new JoystickPanTiltController(panTiltMech);
                runner = new TimerRunner(joyController, screen);
                break;

            case Mode.pantiltface:
                var controllerF = new FaceTrackingPanTiltController(panTiltMech, capture.RequestedConfig);
                runner = new CameraBasedPanTiltRunner(panTiltMech, capture, controllerF, screen);
                break;

            case Mode.pantiltmultimode:
                var cameraHubProxy = new CameraHubProxy();
                if (!_consoleOptions.DisableTransmit)
                {
                    cameraHubProxy.Connect();
                }
                var remoteScreen = new RemoteConsoleScreen(cameraHubProxy);
                //var imageTransmitter = new BsonPostImageTransmitter();
                var imageTransmitter    = new BsonPostJpegTransmitter();
                var periodicImageSender = new RemoteImageSender(imageTransmitter, cameraHubProxy);

                remoteScreen.Enabled        = !_consoleOptions.DisableTransmit;
                periodicImageSender.Enabled = !_consoleOptions.DisableTransmit;

                cameraHubProxy.SettingsChanged += (sender, s) =>
                {
                    remoteScreen.Enabled        = s.EnableConsoleTransmit;
                    periodicImageSender.Enabled = s.EnableImageTransmit;
                };

                var controllerMultimode = new MultimodePanTiltController(
                    panTiltMech
                    , capture.RequestedConfig
                    , remoteScreen
                    , cameraHubProxy
                    , periodicImageSender);

                var cameraBasedRunner = new CameraBasedPanTiltRunner(panTiltMech, capture, controllerMultimode, screen);
                runner = cameraBasedRunner;

                cameraHubProxy.UpdateCapture += (s, e) =>
                {
                    remoteScreen.WriteLine($"Changing capture settings to {e}");
                    var newGrabber = BuildCaptureGrabber(e);
                    cameraBasedRunner.UpdateCaptureGrabber(newGrabber);
                };
                break;

            case Mode.pantiltcolour:
                var controllerC = new ColourTrackingPanTiltController(panTiltMech, capture.RequestedConfig);
                if (_consoleOptions.HasColourSettings)
                {
                    controllerC.Settings = _consoleOptions.ColourSettings;
                }
                else
                {
                    throw KrakenException.Create("Colour settings not found");
                }
                runner = new CameraBasedPanTiltRunner(panTiltMech, capture, controllerC, screen);
                break;

            case Mode.ipReport:
                var hub = new CameraHubProxy();
                runner = new IpReporter(hub);
                break;

            default:
                throw KrakenException.Create("Option mode {0} needs wiring up", _consoleOptions.Mode);
            }

            runner.Run();
        }
示例#36
0
 private void font(ExecutionEnvironment env, FontSpec prevFont, Color defaultColor, Action<FontSpec> setFont)
 {
     using (var fontDlg = new FontDialog())
     {
         if (prevFont != null)
             fontDlg.Font = prevFont.Font;
         if (fontDlg.ShowDialog() == DialogResult.OK)
         {
             setFont(new FontSpec(fontDlg.Font, defaultColor));
             env.IfType((HexagonyEnv e) => { e.UpdateWatch(); });
         }
     }
 }
示例#37
0
        public override List <DebugItem> GetDebugInputs(IExecutionEnvironment env, int update)
        {
            if (env == null)
            {
                return(new List <DebugItem>());
            }
            base.GetDebugInputs(env, update);

            var    head         = Headers.Select(a => new NameValue(ExecutionEnvironment.WarewolfEvalResultToString(env.Eval(a.Name, update)), ExecutionEnvironment.WarewolfEvalResultToString(env.Eval(a.Value, update)))).Where(a => !(String.IsNullOrEmpty(a.Name) && String.IsNullOrEmpty(a.Value)));
            var    query        = ExecutionEnvironment.WarewolfEvalResultToString(env.Eval(QueryString, update));
            var    url          = ResourceCatalog.GetResource <WebSource>(Guid.Empty, SourceId);
            string headerString = string.Join(" ", head.Select(a => a.Name + " : " + a.Value));

            DebugItem debugItem = new DebugItem();

            AddDebugItem(new DebugItemStaticDataParams("", "URL"), debugItem);
            AddDebugItem(new DebugEvalResult(url.Address, "", env, update), debugItem);
            _debugInputs.Add(debugItem);
            debugItem = new DebugItem();
            AddDebugItem(new DebugItemStaticDataParams("", "Query String"), debugItem);
            AddDebugItem(new DebugEvalResult(query, "", env, update), debugItem);
            _debugInputs.Add(debugItem);
            debugItem = new DebugItem();
            AddDebugItem(new DebugItemStaticDataParams("", "Headers"), debugItem);
            AddDebugItem(new DebugEvalResult(headerString, "", env, update), debugItem);
            _debugInputs.Add(debugItem);

            return(_debugInputs);
        }
示例#38
0
        protected override void ExecuteTool(IDSFDataObject dataObject, int update)
        {
            _indexCounter = 1;

            ErrorResultTO        allErrors = new ErrorResultTO();
            var                  env       = dataObject.Environment;
            WarewolfListIterator iter      = new WarewolfListIterator();

            InitializeDebug(dataObject);
            try
            {
                var sourceString = SourceString ?? "";
                if (dataObject.IsDebugMode())
                {
                    AddDebugInputItem(new DebugEvalResult(sourceString, "String to Split", env, update));
                    AddDebugInputItem(new DebugItemStaticDataParams(ReverseOrder ? "Backward" : "Forward", "Process Direction"));
                    AddDebugInputItem(new DebugItemStaticDataParams(SkipBlankRows ? "Yes" : "No", "Skip blank rows"));
                    AddDebug(ResultsCollection, dataObject.Environment, update);
                }
                var res = new WarewolfIterator(env.Eval(sourceString, update));
                iter.AddVariableToIterateOn(res);
                IDictionary <string, int> positions = new Dictionary <string, int>();
                CleanArguments(ResultsCollection);
                ResultsCollection.ToList().ForEach(a =>
                {
                    if (!positions.ContainsKey(a.OutputVariable))
                    {
                        if (update == 0)
                        {
                            positions.Add(a.OutputVariable, 1);
                        }
                        else
                        {
                            positions.Add(a.OutputVariable, update);
                        }
                    }
                    IsSingleValueRule.ApplyIsSingleValueRule(a.OutputVariable, allErrors);
                });
                bool singleInnerIteration = ArePureScalarTargets(ResultsCollection);
                var  resultsEnumerator    = ResultsCollection.GetEnumerator();
                var  debugDictionary      = new List <string>();
                while (res.HasMoreData())
                {
                    const int OpCnt = 0;

                    var item = res.GetNextValue(); // item is the thing we split on
                    if (!string.IsNullOrEmpty(item))
                    {
                        string val       = item;
                        var    blankRows = new List <int>();
                        if (SkipBlankRows)
                        {
                            var strings         = val.Split(new[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                            var newSourceString = string.Join(Environment.NewLine, strings);
                            val = newSourceString;
                        }
                        else
                        {
                            var strings = val.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                            for (int blankRow = 0; blankRow < strings.Length; blankRow++)
                            {
                                if (String.IsNullOrEmpty(strings[blankRow]))
                                {
                                    blankRows.Add(blankRow);
                                }
                            }
                        }

                        ErrorResultTO  errors;
                        IDev2Tokenizer tokenizer = CreateSplitPattern(ref val, ResultsCollection, env, out errors, update);
                        allErrors.MergeErrors(errors);

                        if (!allErrors.HasErrors())
                        {
                            if (tokenizer != null)
                            {
                                int pos = 0;
                                int end = ResultsCollection.Count - 1;

                                // track used tokens so we can adjust flushing ;)
                                while (tokenizer.HasMoreOps())
                                {
                                    var currentval = resultsEnumerator.MoveNext();
                                    if (!currentval)
                                    {
                                        if (singleInnerIteration)
                                        {
                                            break;
                                        }
                                        resultsEnumerator.Reset();
                                        resultsEnumerator.MoveNext();
                                    }
                                    string tmp = tokenizer.NextToken();

                                    if (tmp.StartsWith(Environment.NewLine) && !SkipBlankRows)
                                    {
                                        resultsEnumerator.Reset();
                                        while (resultsEnumerator.MoveNext())
                                        {
                                            var tovar = resultsEnumerator.Current.OutputVariable;
                                            if (!String.IsNullOrEmpty(tovar))
                                            {
                                                var assignToVar = ExecutionEnvironment.ConvertToIndex(tovar, positions[tovar]);
                                                env.AssignWithFrame(new AssignValue(assignToVar, ""), update);
                                                positions[tovar] = positions[tovar] + 1;
                                            }
                                        }
                                        resultsEnumerator.Reset();
                                        resultsEnumerator.MoveNext();
                                    }
                                    if (blankRows.Contains(OpCnt) && blankRows.Count != 0)
                                    {
                                        tmp = tmp.Replace(Environment.NewLine, "");
                                        while (pos != end + 1)
                                        {
                                            pos++;
                                        }
                                    }
                                    var outputVar = resultsEnumerator.Current.OutputVariable;

                                    if (!String.IsNullOrEmpty(outputVar))
                                    {
                                        var assignVar = ExecutionEnvironment.ConvertToIndex(outputVar, positions[outputVar]);
                                        if (ExecutionEnvironment.IsRecordsetIdentifier(assignVar))
                                        {
                                            env.AssignWithFrame(new AssignValue(assignVar, tmp), update);
                                        }
                                        else if (ExecutionEnvironment.IsScalar(assignVar) && positions[outputVar] == 1)
                                        {
                                            env.AssignWithFrame(new AssignValue(assignVar, tmp), update);
                                        }
                                        else
                                        {
                                            env.AssignWithFrame(new AssignValue(assignVar, tmp), update);
                                        }
                                        positions[outputVar] = positions[outputVar] + 1;
                                    }
                                    if (dataObject.IsDebugMode())
                                    {
                                        var debugItem   = new DebugItem();
                                        var outputVarTo = resultsEnumerator.Current.OutputVariable;
                                        AddDebugItem(new DebugEvalResult(outputVarTo, "", env, update), debugItem);
                                        if (!debugDictionary.Contains(outputVarTo))
                                        {
                                            debugDictionary.Add(outputVarTo);
                                        }
                                    }
                                    if (pos == end)
                                    {
                                    }
                                    else
                                    {
                                        pos++;
                                    }
                                }
                            }
                        }
                    }
                    env.CommitAssign();
                    if (singleInnerIteration)
                    {
                        break;
                    }
                }

                if (dataObject.IsDebugMode())
                {
                    var outputIndex = 1;
                    foreach (var varDebug in debugDictionary)
                    {
                        var debugItem = new DebugItem();
                        AddDebugItem(new DebugItemStaticDataParams("", outputIndex.ToString(CultureInfo.InvariantCulture)), debugItem);
                        var dataSplitUsesStarForOutput = varDebug.Replace("().", "(*).");
                        AddDebugItem(new DebugEvalResult(dataSplitUsesStarForOutput, "", env, update), debugItem);
                        _debugOutputs.Add(debugItem);
                        outputIndex++;
                    }
                }
            }
            catch (Exception e)
            {
                Dev2Logger.Log.Error("DSFDataSplit", e);
                allErrors.AddError(e.Message);
            }
            finally
            {
                // Handle Errors
                var hasErrors = allErrors.HasErrors();
                if (hasErrors)
                {
                    DisplayAndWriteError("DsfDataSplitActivity", allErrors);
                    var errorString = allErrors.MakeDisplayReady();
                    dataObject.Environment.AddError(errorString);
                }

                if (dataObject.IsDebugMode())
                {
                    DispatchDebugState(dataObject, StateType.Before, update);
                    DispatchDebugState(dataObject, StateType.After, update);
                }
            }
        }
示例#39
0
        protected override void ExecuteTool(IDSFDataObject dataObject, int update)
        {
            IDev2ReplaceOperation replaceOperation = Dev2OperationsFactory.CreateReplaceOperation();
            ErrorResultTO         errors;
            ErrorResultTO         allErrors = new ErrorResultTO();

            int replacementCount = 0;
            int replacementTotal = 0;

            InitializeDebug(dataObject);
            try
            {
                IList <string> toSearch = FieldsToSearch.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var s in toSearch)
                {
                    if (dataObject.IsDebugMode())
                    {
                        AddDebugInputItem(new DebugEvalResult(s, "In Field(s)", dataObject.Environment, update));
                        if (Find != null)
                        {
                            AddDebugInputItem(new DebugEvalResult(Find, "Find", dataObject.Environment, update));
                        }
                        if (ReplaceWith != null)
                        {
                            AddDebugInputItem(new DebugEvalResult(ReplaceWith, "Replace With", dataObject.Environment, update));
                        }
                    }
                }
                IWarewolfListIterator iteratorCollection = new WarewolfListIterator();

                var finRes = dataObject.Environment.Eval(Find, update);
                if (ExecutionEnvironment.IsNothing(finRes))
                {
                    if (!string.IsNullOrEmpty(Result))
                    {
                        dataObject.Environment.Assign(Result, replacementTotal.ToString(CultureInfo.InvariantCulture), update);
                    }
                }
                else
                {
                    var itrFind = new WarewolfIterator(dataObject.Environment.Eval(Find, update));
                    iteratorCollection.AddVariableToIterateOn(itrFind);

                    var itrReplace = new WarewolfIterator(dataObject.Environment.Eval(ReplaceWith, update));
                    iteratorCollection.AddVariableToIterateOn(itrReplace);
                    var rule   = new IsSingleValueRule(() => Result);
                    var single = rule.Check();
                    if (single != null)
                    {
                        allErrors.AddError(single.Message);
                    }
                    else
                    {
                        while (iteratorCollection.HasMoreData())
                        {
                            // now process each field for entire evaluated Where expression....
                            var findValue        = iteratorCollection.FetchNextValue(itrFind);
                            var replaceWithValue = iteratorCollection.FetchNextValue(itrReplace);
                            foreach (string s in toSearch)
                            {
                                if (!DataListUtil.IsEvaluated(s))
                                {
                                    allErrors.AddError("Please insert only variables into Fields To Search");
                                    return;
                                }
                                if (!string.IsNullOrEmpty(findValue))
                                {
                                    dataObject.Environment.ApplyUpdate(s, a => DataASTMutable.WarewolfAtom.NewDataString(replaceOperation.Replace(a.ToString(), findValue, replaceWithValue, CaseMatch, out errors, ref replacementCount)), update);
                                }

                                replacementTotal += replacementCount;
                                if (dataObject.IsDebugMode() && !allErrors.HasErrors())
                                {
                                    if (!string.IsNullOrEmpty(Result))
                                    {
                                        if (replacementCount > 0)
                                        {
                                            AddDebugOutputItem(new DebugEvalResult(s, "", dataObject.Environment, update));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(Result))
                    {
                        dataObject.Environment.Assign(Result, replacementTotal.ToString(CultureInfo.InvariantCulture), update);
                    }
                }
                if (dataObject.IsDebugMode() && !allErrors.HasErrors())
                {
                    if (!string.IsNullOrEmpty(Result))
                    {
                        AddDebugOutputItem(new DebugEvalResult(Result, "", dataObject.Environment, update));
                    }
                }
                // now push the result to the server
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch (Exception ex)
            {
                Dev2Logger.Log.Error("DSFReplace", ex);
                allErrors.AddError(ex.Message);
            }
            finally
            {
                if (allErrors.HasErrors())
                {
                    if (dataObject.IsDebugMode())
                    {
                        AddDebugOutputItem(new DebugItemStaticDataParams("", Result, ""));
                    }
                    DisplayAndWriteError("DsfReplaceActivity", allErrors);
                    var errorString = allErrors.MakeDisplayReady();
                    dataObject.Environment.AddError(errorString);
                    dataObject.Environment.Assign(Result, null, update);
                }

                if (dataObject.IsDebugMode())
                {
                    DispatchDebugState(dataObject, StateType.Before, update);
                    DispatchDebugState(dataObject, StateType.After, update);
                }
            }
        }
示例#40
0
        public void RunTests(IEnumerable<TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle)
        {
            IMessageLogger log = frameworkHandle;

            log.Version();

            HandlePoorVisualStudioImplementationDetails(runContext, frameworkHandle);

            var assemblyGroups = tests.GroupBy(tc => tc.Source);

            foreach (var assemblyGroup in assemblyGroups)
            {
                var assemblyPath = assemblyGroup.Key;

                try
                {
                    if (AssemblyDirectoryContainsFixie(assemblyPath))
                    {
                        log.Info("Processing " + assemblyPath);

                        var methodGroups = assemblyGroup.Select(x => new MethodGroup(x.FullyQualifiedName)).ToArray();

                        var listener = new VisualStudioListener(frameworkHandle, assemblyPath);

                        using (var environment = new ExecutionEnvironment(assemblyPath))
                        {
                            environment.RunMethods(new Options(), listener, methodGroups);
                        }
                    }
                    else
                    {
                        log.Info("Skipping " + assemblyPath + " because it is not a test assembly.");
                    }
                }
                catch (Exception exception)
                {
                    log.Error(exception);
                }
            }
        }
示例#41
0
        public Result OnStartup(UIControlledApplication application)
        {
            try
            {
                //TAF load english_us TODO add a way to localize
                res = Resource_en_us.ResourceManager;
                // Create new ribbon panel
                RibbonPanel ribbonPanel = application.CreateRibbonPanel(res.GetString("App_Description"));

                //Create a push button in the ribbon panel
                var pushButton = ribbonPanel.AddItem(new PushButtonData("Dynamo",
                                                                        res.GetString("App_Name"), m_AssemblyName,
                                                                        "Dynamo.Applications.DynamoRevit")) as
                                 PushButton;

                Bitmap dynamoIcon = Resources.logo_square_32x32;


                BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                    dynamoIcon.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());

                pushButton.LargeImage = bitmapSource;
                pushButton.Image      = bitmapSource;

                IdlePromise.RegisterIdle(application);

                Updater = new DynamoUpdater(application.ActiveAddInId, application.ControlledApplication);
                if (!UpdaterRegistry.IsUpdaterRegistered(Updater.GetUpdaterId()))
                {
                    UpdaterRegistry.RegisterUpdater(Updater);
                }

                var SpatialFieldFilter           = new ElementClassFilter(typeof(SpatialFieldManager));
                var familyFilter                 = new ElementClassFilter(typeof(FamilyInstance));
                var refPointFilter               = new ElementCategoryFilter(BuiltInCategory.OST_ReferencePoints);
                var modelCurveFilter             = new ElementClassFilter(typeof(CurveElement));
                var sunFilter                    = new ElementClassFilter(typeof(SunAndShadowSettings));
                IList <ElementFilter> filterList = new List <ElementFilter>();

                filterList.Add(SpatialFieldFilter);
                filterList.Add(familyFilter);
                filterList.Add(modelCurveFilter);
                filterList.Add(refPointFilter);
                filterList.Add(sunFilter);

                ElementFilter filter = new LogicalOrFilter(filterList);

                UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeAny());
                UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion());
                UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition());

                env = new ExecutionEnvironment();

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(Result.Failed);
            }
        }
示例#42
0
        public async Task ExecuteAsync(string invokedExecutableName, string[] parameters, ExecutionEnvironment env)
        {
            Log.Debug("Execute: ", ExecutableName, " ", parameters.ToJson(inline: true));
            Output.PipeTo(env.Output);
            Error.PipeTo(env.Error);
            env.Input.PipeTo(Input);

            this.invokedExecutableName = invokedExecutableName;
            this.parameters            = parameters.ToList();
            this.state = new ExecutionState();
            this.env   = env;

            ResetInternalState();

            if (UseOptions)
            {
                parseOptions();
            }

            // need help ?
            if (printHelp)
            {
                printOptions();
                return;
            }
            // execute the command
            else
            {
                await ExecuteInternalAsync();
            }

            StackTraceElement element = new StackTraceElement {
                Executable = ExecutableName,
                Parameters = parameters,
                State      = state
            };

            env.StackTrace.Add(element);
        }
示例#43
0
        private void AddScalarValueResult(IExecutionEnvironment environment, IAssignValue assignValue, int update, DebugItem debugItem, CommonFunctions.WarewolfEvalResult oldValueResult, CommonFunctions.WarewolfEvalResult newValueResult)
        {
            var scalarResult = oldValueResult as CommonFunctions.WarewolfEvalResult.WarewolfAtomResult;

            if (newValueResult is CommonFunctions.WarewolfEvalResult.WarewolfAtomResult valueResult && scalarResult != null)
            {
                AddDebugItem(new DebugItemWarewolfAtomResult(ExecutionEnvironment.WarewolfAtomToString(scalarResult.Item), ExecutionEnvironment.WarewolfAtomToString(valueResult.Item), assignValue.Name, environment.EvalToExpression(assignValue.Value, update), VariableLabelText, NewFieldLabelText, "="), debugItem);
            }
        }
示例#44
0
 static AssemblyResult Execute(string assemblyPath, Options options, Listener listener)
 {
     using (var environment = new ExecutionEnvironment(assemblyPath))
         return environment.RunAssembly(options, listener);
 }
示例#45
0
        protected override void ExecutionImpl(IEsbChannel esbChannel, IDSFDataObject dataObject, string inputs, string outputs, out ErrorResultTO tmpErrors, int update)
        {
            tmpErrors = new ErrorResultTO();
            IEnumerable <NameValue> head = null;

            if (Headers != null)
            {
                head = Headers.Select(a => new NameValue(ExecutionEnvironment.WarewolfEvalResultToString(dataObject.Environment.Eval(a.Name, update)), ExecutionEnvironment.WarewolfEvalResultToString(dataObject.Environment.Eval(a.Value, update))));
            }
            var query = "";

            if (QueryString != null)
            {
                query = ExecutionEnvironment.WarewolfEvalResultToString(dataObject.Environment.Eval(QueryString, update));
            }
            var putData = "";

            if (PutData != null)
            {
                putData = ExecutionEnvironment.WarewolfEvalResultToString(dataObject.Environment.Eval(PutData, update));
            }

            var url = ResourceCatalog.GetResource <WebSource>(Guid.Empty, SourceId);
            var webRequestResult = PerformWebPostRequest(head, query, url, putData);

            ResponseManager = new ResponseManager {
                OutputDescription = OutputDescription, Outputs = Outputs, IsObject = IsObject, ObjectName = ObjectName
            };
            ResponseManager.PushResponseIntoEnvironment(webRequestResult, update, dataObject);
        }