示例#1
0
 /// <summary>
 /// Instantiates a new event as a copy of the event provided.
 /// </summary>
 /// <param name="ev">The event to copy for this new instance.</param>
 public Event(IEvent ev)
 {
     _context = ev.Context;
     _message = ev.Message;
     _object  = ev.Object;
     _params  = new Dictionary <string, string>(ev.Params);
 }
 /// <summary>
 /// Determines if the event specifies the behaviour by name.
 /// </summary>
 /// <param name="ev">The event to consult.</param>
 /// <param name="context">The context to consult.</param>
 /// <returns>
 /// Returns true if true if `ev.Message` is the same as `this.Message`
 ///  </returns>
 /// <remarks>
 /// The intent is to override for bespoke conditions.
 /// </remarks>
 public virtual bool Condition(IEvent ev, IProcessContext context)
 {
     // check the base condition
     // and then either there are no roles specified
     // or the user is in any of the roles defined
     return(this.RespondsTo == "*" || ev.Message == this.RespondsTo);
 }
示例#3
0
 /// <summary>
 /// Instantiates a new event bound  to a context.
 /// </summary>
 /// <param name="context">The context to which the event is bound.</param>
 /// <param name="message">The simple message the event represents.</param>
 /// <param name="obj">An object being carried by the event.</param>
 /// <param name="parameters">The parameters of the event.</param>
 public Event(IProcessContext context, string message, IData obj, IDictionary <string, string> parameters)
 {
     _context = context;
     _message = message;
     _object  = obj;
     _params  = (parameters == null) ? new Dictionary <string, string>() : new Dictionary <string, string>(parameters);
 }
        /// <summary>
        /// The action to perform when the `Condition(IEvent)` is met.
        /// </summary>
        /// <param name="ev">The event to consult.</param>
        /// <param name="context">The context upon which to perform any action.</param>
        public override void Action(IEvent ev, IProcessContext context)
        {
            DataCollection <IEvent> events = context.ControlState["eventTrace"] as DataCollection <IEvent> ?? new DataCollection <IEvent>();

            events.Add(ev);
            context.ControlState["eventTrace"] = events;
        }
        public BaseState(IProcessContext context, ILogger logger)
        {
            this.context             = context;
            context.CurrentStateName = typeof(T).FullName;

            logger.Log($"In state {context.CurrentStateName}");
        }
示例#6
0
        public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
        {
            if (value == null || !CanInterpret(schema))
            {
                return value;
            }

            if (!(value is string val))
            {
                throw new ArgumentException($"{value.GetType()} is not supported type string.");
            }

            if (_aggregateXrefs)
            {
                AddUidLinkSource(context.UidLinkSources, new LinkSourceInfo
                {
                    Target = val,
                    SourceFile = context.OriginalFileAndType.File
                });
            }

            if (_resolveXrefs)
            {
                // TODO: add resolved xref to the object if needed
                var xref = context.BuildContext.GetXrefSpec(val);
                if (xref == null)
                {
                    Logger.LogWarning($"Unable to find file with uid \"{val}\".", WarningCodes.Build.UidNotFound);
                }
            }

            return value;
        }
示例#7
0
        // The iterator generated for this should be
        //		ThreadLocal and therefore safe to use
        //		in this manner on a singleton, would be
        //		nice to fonfirm this.
        // At some point this will need to move to being
        // and injected strategy.
        private IEnumerable <string> _possibleTemplates(IProcessContext context)
        {
            string area    = context.Params["area"];
            string concern = context.Params["concern"];
            string action  = String.Format("{0}.xslt", context.Params["action"]);

            // area/concern/action
            yield return(Path.Combine(area, concern, action));

            // area/concern/default
            yield return(Path.Combine(area, concern, "default.xslt"));

            // area/action
            yield return(Path.Combine(area, action));

            // area/default
            yield return(Path.Combine(area, "default.xslt"));

            // concern/action
            yield return(Path.Combine(concern, action));

            // concern/default
            yield return(Path.Combine(concern, "default.xslt"));

            // action
            yield return(action);

            // default
            yield return("default.xslt");
        }
        /// <summary>
        /// Locates possible templates of the specified extension.
        /// </summary>
        /// <param name="ctx">The context to consult.</param>
        /// <param name="extension">The file extension of templates to look for.</param>
        /// <returns>Returns an enumerable of template names.</returns>
        /// <remarks>
        /// The locations checked are produced by the following series of yields:-
        /// <code>
        ///	//area/concern/action
        ///	yield return Path.Combine(area, concern, action);
        ///	yield return Path.Combine(area, concern, "default.ext");
        ///	// area/action
        ///	yield return Path.Combine(area, action);
        ///	yield return Path.Combine(area, "default.ext");
        ///	// concern/action
        ///	yield return Path.Combine(concern, action);
        ///	yield return Path.Combine(concern, "default.ext");
        ///	// action
        ///	yield return action;
        ///	yield return "default.xslt"; 
        /// </code>
        /// Where ".ext" referes to the extension specified.
        /// </remarks>
        protected virtual IEnumerable<string> GetPossibleTemplates(IProcessContext ctx, string extension)
        {
            // The iterator generated for this should be
            //		ThreadLocal and therefore safe to use
            //		in this manner on a singleton, would be
            //		nice to fonfirm this.
            // At some point this will need to move to being
            //		and injected strategy, perhaps some ordered expression
            //		of patterns that can be specified as config for the behaviour.
            string area = ctx.Params["area"];
            string concern = ctx.Params["concern"];
            string action = String.Format("{0}.{1}", ctx.Params["action"], extension);
            string defaultName = String.Format("default.{0}", extension);

            // area/concern/action
            yield return Path.Combine(area, concern, action);
            // area/concern/default
            yield return Path.Combine(area, concern, defaultName);
            // area/action
            yield return Path.Combine(area, action);
            // area/default
            yield return Path.Combine(area, defaultName);
            // concern/action
            yield return Path.Combine(concern, action);
            // concern/default
            yield return Path.Combine(concern, defaultName);
            // action
            yield return action;
            // default
            yield return defaultName;
        }
示例#9
0
        public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
        {
            if (value == null || !CanInterpret(schema))
            {
                return(value);
            }

            var uid = JsonPointer.GetChild(value, "uid") as string;

            if (uid == null)
            {
                // schema validation threw error when uid is required, so here when uid is null, it must be optional, which is allowed
                return(value);
            }

            if (string.IsNullOrEmpty(uid))
            {
                Logger.LogWarning($"Invalid xrefProperties for /{path}: empty uid is not allowed.");
                return(value);
            }

            var xrefSpec = new XRefSpec
            {
                Uid = uid
            };

            var parts = schema.XrefProperties ?? new List <string> {
                "name", "fullName"
            };
            var root = context.GetModel <object>();

            foreach (var part in parts.Distinct())
            {
                var jsonPointer = new JsonPointer(path + "/" + part);
                var property    = jsonPointer.GetValue(root);
                if (property != null)
                {
                    if (property is string str)
                    {
                        xrefSpec[part] = str;
                    }
                    else
                    {
                        Logger.LogWarning($"Type {property.GetType()} from {jsonPointer} is not supported as the value of xref spec.");
                    }
                }
            }

            if (IsInternalXrefSpec(schema))
            {
                context.Uids.Add(new UidDefinition(uid, context.OriginalFileAndType.FullPath, path: path + "/uid"));
                xrefSpec.Href = ((RelativePath)context.OriginalFileAndType.File).GetPathFromWorkingFolder().UrlEncode().ToString();
                context.XRefSpecs.Add(xrefSpec);
            }
            else
            {
                context.ExternalXRefSpecs.Add(xrefSpec);
            }
            return(value);
        }
示例#10
0
 public override void Action(IEvent ev, IProcessContext context)
 {
     if (_action != null)
     {
         _action(ev, context);
     }
 }
示例#11
0
        public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
        {
            if (value == null || !CanInterpret(schema))
            {
                return(value);
            }

            if (!(value is string val))
            {
                throw new ArgumentException($"{value.GetType()} is not supported type string.");
            }

            var filePath = val;
            var relPath  = RelativePath.TryParse(val);

            if (relPath != null)
            {
                var currentFile = (RelativePath)context.OriginalFileAndType.File;
                filePath = currentFile + relPath;
            }

            context.SetOriginalContentFile(path, new FileAndType(context.OriginalFileAndType.BaseDir, filePath, DocumentType.Article));

            return(EnvironmentContext.FileAbstractLayer.ReadAllText(filePath));
        }
示例#12
0
        private bool TryGetTagParameter(string tagName, IProcessContext context, out string pattern)
        {
            JArray args = null;

            if (context.Host?.BuildParameters?.TagParameters?.TryGetValue(tagName, out args) == true)
            {
                if (args?.Count != 1)
                {
                    Logger.LogWarning($"Invalid tagParameters config: tag {tagName} interpreter only supports one parameter, {tagName} interpreter will be ignored.", code: WarningCodes.Build.InvalidTagParametersConfig);
                }
                else
                {
                    pattern = args[0].Value <string>();
                    if (pattern == null)
                    {
                        Logger.LogWarning($"Invalid tagParameters config: tag {tagName} interpreter only supports parameter in string type, {tagName} interpreter will be ignored.", code: WarningCodes.Build.InvalidTagParametersConfig);
                        return(false);
                    }
                    return(true);
                }
            }

            // Less-strict check here without log warning, considering the time gap between schema update and docfx.json update
            pattern = null;
            return(false);
        }
示例#13
0
 /// <summary>
 /// Fires a sequence of configured messages configured in a given frame.
 /// </summary>
 /// <param name="self">The prototype behaviour being acted upon.</param>
 /// <param name="ctx">The context to fire the messages on.</param>
 /// <param name="frame">The frame within the behaviours config to obtain messages from.</param>
 public static void FireSequenceFromConfig(this IPrototypedBehaviour self, IProcessContext ctx, string frame)
 {
     foreach (string slot in self.Configuration.GetSlots(frame))
     {
         ctx.Fire(slot, self.Configuration.GetMap(frame, slot));
     }
 }
    public void Handle(IProcessContext context, string line)
    {
        // first word on the line is the command, all other words are arguments.
        // split the string properly

        // then find the corrext command handler and invoke it.
        // take the result and add it to the `IProcessContext`
    }
 /// <summary>
 /// The action to perform when the `Condition(IEvent)` is met.
 /// </summary>
 /// <param name="ev">The event to consult.</param>
 /// <param name="context">The context upon which to perform any action.</param>
 public override void Action(IEvent ev, IProcessContext context)
 {
     // GM.150624: Consider changing this to act on ("config","flag")
     foreach (string name in this.Configuration.GetNames("config", "set"))
     {
         context.Flags.Add(name);
     }
 }
示例#16
0
        public TestList(IProcessContext processContext)
        {
            if (processContext == null)
            {
                throw new ArgumentNullException("processContext");
            }

            ProcessContext = processContext;
        }
示例#17
0
        public TestList(IProcessContext processContext)
        {
            if (processContext == null)
            {
                throw new ArgumentNullException("processContext");
            }

            ProcessContext = processContext;
        }
示例#18
0
		public ProcessVM(int pid, string title, Machine machine, CLRTypeAttachInfo type, string fullPath, IProcessContext context) {
			this.fullPath = fullPath;
			this.pid = pid;
			this.title = title;
			this.machine = machine;
			this.clrVersion = type.Version;
			this.type = type;
			this.context = context;
		}
示例#19
0
		public ProcessVM(int pid, string title, Machine machine, CLRTypeAttachInfo type, string fullPath, IProcessContext context) {
			FullPath = fullPath;
			PID = pid;
			Title = title;
			Machine = machine;
			CLRVersion = type.Version;
			CLRTypeInfo = type;
			Context = context;
		}
示例#20
0
        public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
        {
            if (value == null || !CanInterpret(schema))
            {
                return(value);
            }

            if (!(value is string val))
            {
                throw new ArgumentException($"{value.GetType()} is not supported type string.");
            }

            if (!Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out Uri uri))
            {
                var message = $"{val} is not a valid href";
                Logger.LogError(message, code: ErrorCodes.Build.InvalidHref);
                throw new DocumentException(message);
            }

            // "/" is also considered as absolute to us
            if (uri.IsAbsoluteUri || val.StartsWith("/", StringComparison.Ordinal))
            {
                return(Helper.RemoveHostName(val, _siteHostName));
            }

            // sample value: a/b/c?hello
            var filePath  = UriUtility.GetPath(val);
            var fragments = UriUtility.GetQueryStringAndFragment(val);
            var relPath   = RelativePath.TryParse(filePath);

            if (relPath != null)
            {
                var originalFile = context.GetOriginalContentFile(path);
                var currentFile  = (RelativePath)originalFile.File;
                relPath = (currentFile + relPath.UrlDecode()).GetPathFromWorkingFolder();
                if (_exportFileLink)
                {
                    (context.FileLinkSources).AddFileLinkSource(new LinkSourceInfo
                    {
                        Target     = relPath,
                        Anchor     = UriUtility.GetFragment(val),
                        SourceFile = originalFile.File
                    });
                }

                if (_updateValue && context.BuildContext != null)
                {
                    var resolved = (RelativePath)context.BuildContext.GetFilePath(relPath);
                    if (resolved != null)
                    {
                        val = resolved.MakeRelativeTo(((RelativePath)context.FileAndType.File).GetPathFromWorkingFolder()).UrlEncode() + fragments;
                    }
                }
            }

            return(val);
        }
示例#21
0
文件: Helper.cs 项目: z784916/docfx-1
        public static void SetOriginalContentFile(this IProcessContext context, string path, FileAndType file)
        {
            if (!context.PathProperties.TryGetValue(path, out var properties))
            {
                properties = context.PathProperties[path] = new Dictionary <string, object>();
            }

            properties[ContentOriginalFileKeyName] = file;
        }
示例#22
0
        public object Process(object raw, BaseSchema schema, IProcessContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            return(InterpretCore(raw, schema, string.Empty, context));
        }
示例#23
0
 public ProcessVM(int pid, string title, Machine machine, CLRTypeAttachInfo type, string fullPath, IProcessContext context)
 {
     this.FullPath    = fullPath;
     this.PID         = pid;
     this.Title       = title;
     this.Machine     = machine;
     this.CLRVersion  = type.Version;
     this.CLRTypeInfo = type;
     this.Context     = context;
 }
示例#24
0
 public ProcessVM(int pid, string title, Machine machine, CLRTypeAttachInfo type, string fullPath, IProcessContext context)
 {
     this.fullPath   = fullPath;
     this.pid        = pid;
     this.title      = title;
     this.machine    = machine;
     this.clrVersion = type.Version;
     this.type       = type;
     this.context    = context;
 }
 public void SearchForCustomerDK(string userDk, int logOrgId, VolarisReservation reservation)
 {
     Context = new VolarisContextSolverCustomerDkWinForms
     {
         LogOrId     = logOrgId,
         UserDK      = userDk,
         OnCompleted = OnSearchCustomerDkCompleted
     };
     Context.Resolve(reservation);
 }
示例#26
0
        private static string MarkupCore(string content, IProcessContext context)
        {
            var host = context.Host;
            var mr   = host.Markup(content, (FileAndType)context.Properties.ContentOriginalFile);

            ((Dictionary <string, List <LinkSourceInfo> >)context.Properties.FileLinkSources).Merge(mr.FileLinkSources);
            ((Dictionary <string, List <LinkSourceInfo> >)context.Properties.UidLinkSources).Merge(mr.UidLinkSources);
            ((HashSet <string>)context.Properties.Dependency).UnionWith(mr.Dependency);
            return(mr.Html);
        }
 public void SetUp()
 {
     grinderContextMock = TestUtils.CreateContextMock();
     datapoolManagerMock = new Mock<IDatapoolManager>();
     processContext = TestUtils.CreateProcessContext(null, null, datapoolManagerMock.Object, grinderContextMock.Object);
     loggerMock = TestUtils.CreateLoggerMock();
     grinderContextMock.Setup(c => c.GetLogger(It.IsAny<Type>())).Returns(loggerMock.Object);
     worker = new CsScriptWorker { GrinderContext = grinderContextMock.Object, ProcessContext = processContext, DatapoolManager = datapoolManagerMock.Object };
     CSScript.Evaluator.Reset();
 }
示例#28
0
        private static string MarkupCore(MarkdownDocument document, IProcessContext context, string path)
        {
            var host = context.Host;

            var mr = context.MarkdigMarkdownService.Render(document);

            (context.FileLinkSources).Merge(mr.FileLinkSources);
            (context.UidLinkSources).Merge(mr.UidLinkSources);
            (context.Dependency).UnionWith(mr.Dependency);
            return(mr.Html);
        }
示例#29
0
 public void MakePayment(VolarisReservation reservation)
 {
     Context = null;
     Context = new VolarisContextSolverReservationPaymentWinForms()
     {
         OnWebServiceCallCompleted = OnWebServiceCallCompleted,
         OnWebServiceCallStart     = OnWebServiceCallStart,
         OnPaymentCompleted        = OnPaymentCompleted
     };
     Context.Resolve(reservation);
 }
示例#30
0
        private static string MarkupCore(string content, IProcessContext context, string path)
        {
            var host = context.Host;

            var mr = host.Markup(content, context.GetOriginalContentFile(path));

            (context.FileLinkSources).Merge(mr.FileLinkSources);
            (context.UidLinkSources).Merge(mr.UidLinkSources);
            (context.Dependency).UnionWith(mr.Dependency);
            return(mr.Html);
        }
示例#31
0
        public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
        {
            if (value == null || !CanInterpret(schema))
            {
                return(value);
            }

            if (!(value is string val))
            {
                throw new ArgumentException($"{value.GetType()} is not supported type string.");
            }

            if (!Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out Uri uri))
            {
                throw new DocumentException($"{val} is not a valid href");
            }

            // "/" is also considered as absolute to us
            if (uri.IsAbsoluteUri || val.StartsWith("/"))
            {
                return(value);
            }

            // sample value: a/b/c?hello
            var filePath  = UriUtility.GetPath(val);
            var fragments = UriUtility.GetQueryStringAndFragment(val);
            var relPath   = RelativePath.TryParse(filePath);

            if (relPath != null)
            {
                var currentFile = (RelativePath)context.Model.OriginalFileAndType.File;
                relPath = (currentFile + relPath.UrlDecode()).GetPathFromWorkingFolder();
                if (_exportFileLink)
                {
                    ((Dictionary <string, List <LinkSourceInfo> >)context.Properties.FileLinkSources).AddFileLinkSource(new LinkSourceInfo
                    {
                        Target     = relPath,
                        Anchor     = UriUtility.GetFragment(val),
                        SourceFile = context.Model.OriginalFileAndType.File
                    });
                }

                if (_updateValue && context.BuildContext != null)
                {
                    var resolved = (RelativePath)context.BuildContext.GetFilePath(relPath);
                    if (resolved != null)
                    {
                        val = resolved.MakeRelativeTo(((RelativePath)context.Model.File).GetPathFromWorkingFolder()).UrlEncode() + fragments;
                    }
                }
            }

            return(val);
        }
示例#32
0
        private object Interpret(object value, BaseSchema schema, string path, IProcessContext context)
        {
            var val = value;

            foreach (var i in _interpreters.Where(s => s.CanInterpret(schema)))
            {
                val = i.Interpret(schema, val, context, path);
            }

            return(val);
        }
示例#33
0
        public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
        {
            if (value == null || !CanInterpret(schema))
            {
                return(value);
            }

            var uid = JsonPointer.GetChild(value, "uid") as string;

            if (string.IsNullOrEmpty(uid))
            {
                Logger.LogWarning($"Invalid xrefProperties for {path}: uid is not defined.");
                return(value);
            }

            var xrefSpec = new XRefSpec
            {
                Uid = uid
            };

            var parts = schema.XrefProperties ?? new List <string> {
                "name", "fullName"
            };
            var root = context.Model.Content;

            foreach (var part in parts.Distinct())
            {
                var jsonPointer = new JsonPointer(path + "/" + part);
                var property    = jsonPointer.GetValue(root);
                if (property != null)
                {
                    if (property is string str)
                    {
                        xrefSpec[part] = str;
                    }
                    else
                    {
                        Logger.LogWarning($"Type {property.GetType()} from {jsonPointer} is not supported as the value of xref spec.");
                    }
                }
            }

            if (IsInternalXrefSpec(schema))
            {
                context.Properties.Uids.Add(new UidDefinition(uid, context.Model.LocalPathFromRoot, path: path + "/uid"));
                xrefSpec.Href = ((RelativePath)context.Model.Key).UrlEncode().ToString();
                context.Properties.XRefSpecs.Add(xrefSpec);
            }
            else
            {
                context.Properties.ExternalXRefSpecs.Add(xrefSpec);
            }
            return(value);
        }
示例#34
0
 public void SetUp()
 {
     grinderContextMock  = TestUtils.CreateContextMock();
     datapoolManagerMock = new Mock <IDatapoolManager>();
     processContext      = TestUtils.CreateProcessContext(null, null, datapoolManagerMock.Object, grinderContextMock.Object);
     loggerMock          = TestUtils.CreateLoggerMock();
     grinderContextMock.Setup(c => c.GetLogger(It.IsAny <Type>())).Returns(loggerMock.Object);
     worker = new CsScriptWorker {
         GrinderContext = grinderContextMock.Object, ProcessContext = processContext, DatapoolManager = datapoolManagerMock.Object
     };
     CSScript.Evaluator.Reset();
 }
示例#35
0
        public void CreateReservation(VolarisReservation reservation)
        {
            Context = new VolarisContextSolverReservationWinForms()
            {
                OnWebServiceCallStart         = OnWebServiceCallStart,
                OnWebServiceCallCompleted     = OnWebServiceCallCompleted,
                OnReservationCreatedCompleted = OnReservationCreatedCompleted
            };


            Context.Resolve(reservation);
        }
 /// <summary>
 /// Fires a sequence of configured messages configured in a given frame.
 /// </summary>
 /// <param name="self">The prototype behaviour being acted upon.</param>
 /// <param name="ctx">The context to fire the messages on.</param>
 /// <param name="frame">The frame within the behaviours config to obtain messages from.</param>
 public static void FireSequenceFromConfig(this IPrototypedBehaviour self, IProcessContext ctx, string frame)
 {
     foreach (string slot in self.Configuration.GetSlots(frame)) {
         ctx.Fire(slot, self.Configuration.GetMap(frame, slot));
     }
 }