Example #1
0
        public DynamicCommand(ScriptRuntime scriptRuntime, IScriptSource source)
        {
            Source = source;

            Name = source.Name;

            var scriptEngine = scriptRuntime.GetEngineByFileExtension(source.LanguageExtension);
            var scriptScope  = scriptEngine.CreateScope();

            var scriptSource = scriptEngine.CreateScriptSourceFromString(source.GetScriptCode(), SourceCodeKind.File);
            var compiledCode = scriptSource.Compile();

            compiledCode.Execute(scriptScope);

            Action <TAppSession, TRequestInfo> dynamicMethod;

            if (!scriptScope.TryGetVariable <Action <TAppSession, TRequestInfo> >("execute", out dynamicMethod))
            {
                throw new Exception("Failed to find a command execution method in source: " + source.Tag);
            }

            CompiledTime = DateTime.Now;

            m_DynamicExecuteCommand = dynamicMethod;
        }
        private static void SetBaristaV2Flags(IScriptSource source, BrewRequest request, BrewResponse response)
        {
            if (String.IsNullOrWhiteSpace(request.Bootstrapper))
            {
                source.Flags["bootstrapperPath"] = ConfigurationManager.AppSettings.GetValue("Barista_v2_Bootstrapper", "./../lib/BaristaBootstrapper_v1.js");
            }
            else
            {
                source.Flags["bootstrapperPath"] = request.Bootstrapper;
            }

            var dcs = new DataContractSerializer(typeof(BrewRequest));

            source.Flags["request_xml"]  = BaristaHelper.SerializeXml(request);
            source.Flags["response_xml"] = BaristaHelper.SerializeXml(response);
            source.Flags["request"]      = JsonConvert.SerializeObject(request);
            source.Flags["response"]     = JsonConvert.SerializeObject(response);

            source.Flags["environment"] = JsonConvert.SerializeObject(new {
                baristaWebServiceBinFolder = SPUtility.GetVersionedGenericSetupPath(@"WebServices\Barista\bin", SPUtility.CompatibilityLevel15),
                baristaAssembly            = BaristaHelper.GetAssemblyPath(typeof(Barista.Library.BaristaGlobal)) + "\\Barista.Core.dll",
                baristaSharePointAssembly  = BaristaHelper.GetAssemblyPath(typeof(Barista.SharePoint.Library.BaristaSharePointGlobal)) + "\\Barista.SharePoint.Core.dll",
                sharePointAssembly         = BaristaHelper.GetAssemblyPath(typeof(Microsoft.SharePoint.SPContext)) + "\\Microsoft.SharePoint.dll"
            });
        }
Example #3
0
        public override ExecutionResult Execute(IScriptSource scriptSource, IEnumerable <string> args = null)
        {
            try
            {
                if (args != null)
                {
                    InternalEngine.SetGlobalValue("args", InternalEngine.EnumerableToArray(args));
                }

                InternalEngine.Execute(new ScriptSourceProxy(scriptSource));
                return(new ExecutionResult
                {
                    Success = true
                });
            }
            catch (JavaScriptException ex)
            {
                return(new ExecutionResult
                {
                    Success = false,
                    ExecutionException = new ExecutionException(ex)
                    {
                        LineNumber = ex.LineNumber
                    }
                });
            }
            catch (Exception ex)
            {
                return(new ExecutionResult
                {
                    Success = false,
                    ExecutionException = new ExecutionException(ex)
                });
            }
        }
 public int GetLineSource(int line, out IScriptSource source)
 {
     foreach (var item in _lineSrcMap)
     {
         if (line >= item.First && line <= item.Last)
         {
             source = item.Source;
             return (line - item.First) + item.Offset;
         }
     }
     source = _source;
     return line;
 }
Example #5
0
        public override ExecutionResult <TReturn> Evaluate <TReturn>(IScriptSource scriptSource, IEnumerable <string> args = null)
        {
            try
            {
                if (args != null)
                {
                    InternalEngine.SetGlobalValue("args", InternalEngine.EnumerableToArray(args));
                }

                TReturn val;
                if (typeof(TReturn).IsArray)
                {
                    val = EvaluateArray <TReturn>(scriptSource);
                }
                else if (typeof(IEnumerable).IsAssignableFrom(typeof(TReturn)) && typeof(TReturn) != typeof(string))
                {
                    val = EvaluateEnumerable <TReturn>(scriptSource);
                }
                else
                {
                    val = InternalEngine.Evaluate <TReturn>(scriptSource.GetReader().ReadToEnd());
                }

                return(new ExecutionResult <TReturn>
                {
                    Value = val,
                    Success = true
                });
            }
            catch (JavaScriptException ex)
            {
                return(new ExecutionResult <TReturn>
                {
                    Success = false,
                    ExecutionException = new ExecutionException(ex)
                    {
                        LineNumber = ex.LineNumber
                    }
                });
            }
            catch (Exception ex)
            {
                return(new ExecutionResult <TReturn>
                {
                    Success = false,
                    ExecutionException = new ExecutionException(ex)
                });
            }
        }
Example #6
0
        private TReturn EvaluateEnumerable <TReturn>(IScriptSource scriptSource)
        {
            if (!typeof(IEnumerable).IsAssignableFrom(typeof(TReturn)))
            {
                return(default(TReturn));
            }

            var castMethod   = typeof(Enumerable).GetMethod("Cast");
            var toListMethod = typeof(Enumerable).GetMethod("ToList");

            var returnType = typeof(TReturn);
            var obj        = InternalEngine.Evaluate <ArrayInstance>(scriptSource.GetReader().ReadToEnd()).ElementValues.ToArray();

            var targetType = returnType.GetGenericArguments()[0];
            var cast       = castMethod.MakeGenericMethod(targetType).Invoke(null, new object[] { obj });

            return((TReturn)toListMethod.MakeGenericMethod(targetType).Invoke(null, new[] { cast }));
        }
Example #7
0
        public object Evaluate(IScriptSource script)
        {
            using (var x = script.GetReader())
            {
                var code = x.ReadToEnd();

                var bootstrapperPath = String.Empty;
                if (script.Flags.ContainsKey("bootstrapperPath"))
                {
                    bootstrapperPath = script.Flags["bootstrapperPath"];
                }

                var evaluateTask = Task.Run <object>(() => ExecuteAsync(bootstrapperPath, code, script.Path, script.Flags));
                evaluateTask.Wait();

                return(evaluateTask.Result);
            }
        }
Example #8
0
        public static Task ProcessScript(IScriptSource scriptSource, Func <ISerialPortComm> serialCommFactory)
        {
            return(new Task(async() =>
            {
                try
                {
                    Log.Information("Processing the script.");

                    scriptSource.Backup();
                    var script = scriptSource.GetContent();
                    var commands = await script.Evaluate();

                    using (var serialComm = serialCommFactory())
                    {
                        var state = InitStateMachineBuilder(serialComm, commands)
                                    .BuildStateMachine();

                        serialComm.OnNewMessage += (message) =>
                        {
                            state = state.Handle(message);
                        };

                        serialComm.Open();

                        while (state != null)
                        {
                            Thread.Sleep(100);
                        }
                    }

                    Log.Information("Script processing done.");
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error encountered while processing the script.");
                }
            }));
        }
Example #9
0
 public object Eval(IScriptSource source)
 {
     AddSource(source);
     return Eval(source.ReadAll(), source.Path);
 }
Example #10
0
 public void Exec(IScriptSource source)
 {
     AddSource(source);
     Exec(source.ReadAll(), source.Path);
 }
Example #11
0
 public ScriptSourceProxy(IScriptSource source)
 {
     _source = source;
 }
Example #12
0
 public abstract ExecutionResult <TReturn> Evaluate <TReturn>(IScriptSource scriptSource, IEnumerable <string> args = null);
Example #13
0
 public Updater(IScriptSource <ITextScriptTarget> scriptSource, ITextScriptTarget scriptTarget, Options options)
 {
     this.scriptSource = scriptSource;
     this.scriptTarget = scriptTarget;
     this.options      = options;
 }
Example #14
0
 public int GetLineSource(int line, out IScriptSource source)
 {
     source = this;
     return line;
 }
Example #15
0
 public Task <ExecutionResult <TReturn> > EvaluateAsync <TReturn>(IScriptSource scriptSource, IEnumerable <string> args = null)
 {
     return(Task.Factory.StartNew(() => Evaluate <TReturn>(scriptSource, args)));
 }
 public LineSource(IScriptSource source, int offset)
 {
     _Source = source;
     First = -1;
     Last = -1;
     Offset = offset;
 }
Example #17
0
 public ScriptBlock AppendScript(IScriptSource script)
 {
     var newScripts = _scripts.ToList();
     newScripts.Add(script);
     return new ScriptBlock(newScripts);
 }
            static void Process(IScriptSource source, StringBuilder sb, List<LineSource> map, int level, ref int count, string includeArg)
            {
                var chunk = new LineSource(source);
                var localCount = 0;

                var indent = (string)null;
                var lines = source.AsEnumerableLines();

                foreach (var line in lines)
                {
                    /// Append lines that don't start with <see cref="IncLex"/>.
                    ///
                    if (line.Length < IncLexMinLen ||
                        !line.StartsWith(IncLex))
                    {
                        sb.AppendLine(line);
                        Add(chunk, ref count, ref localCount);
                        continue;
                    }
                    /// Get the argument portion of the include statement.
                    /// If none can be found, just append the line.
                    var argEnd = line.IndexOfAny(new[] { '>', '"' }, IncLexLen + 1);
                    if (argEnd < IncLexLen)
                    {
                        sb.AppendLine(line);
                        Add(chunk, ref count, ref localCount);
                        continue;
                    }
                    var arg = line.Substring(IncLexLen + 1, argEnd - IncLexLen - 1);
                    /// Get the argument delimiter, either an angle-bracket or
                    /// a double-quote. An angle-bracket is an embedded file,
                    /// a double-quote is a regular file or possibly a uri in
                    /// the future.
                    var c = line[IncLexLen];

                    switch (c)
                    {
                    case '<':
                        /// Embedded Path.
                        indent = indent ?? new String(' ', level);
                        sb.AppendLine(String.Format("{0}// <{1}> include BEGIN", indent, arg));
                        Add(chunk, ref count, ref localCount);

                        map.Add(chunk);

                        var efileSrc = new ScriptEmbedded(arg);
                        Process(efileSrc, sb, map, level + 1, ref count, arg);

                        // New chunk of source.
                        chunk = new LineSource(source, localCount);

                        break;
                    case '"':
                        /// TODO: Preprocess Include File Path.
                        throw new NotImplementedException();
                    default:
                        sb.AppendLine(line);
                        Add(chunk, ref count, ref localCount);
                        break;
                    }
                }
                if (level > 0)
                {
                    indent = new String(' ', level - 1);
                    sb.AppendLine(String.Format("{0}// <{1}> include END", indent, includeArg));
                    Add(chunk, ref count, ref localCount);
                }
                map.Add(chunk);
            }
Example #19
0
 public Task <ExecutionResult> ExecuteAsync(IScriptSource scriptSource, IEnumerable <string> args = null)
 {
     return(Task.Factory.StartNew(() => Execute(scriptSource, args)));
 }
 public static IScriptSource Preprocess(IScriptSource source)
 {
     return new JsPreprocSource(source);
 }
 public LineSource(IScriptSource source)
     : this(source, 0)
 {
 }
Example #22
0
 void AddSource(IScriptSource source)
 {
     _sourceByName.Add(source.Path, source);
 }
Example #23
0
 public ScriptSourceProxy(IScriptSource source)
 {
     _source = source;
 }
Example #24
0
 public abstract ExecutionResult Execute(IScriptSource scriptSource, IEnumerable <string> args = null);
 public JsPreprocSource(IScriptSource source)
 {
     _source = source;
 }