Beispiel #1
0
        public static ActionAttribute GetAction(XElement element)
        {
            var action = new ActionAttribute(element.TryGetAttribute("name"), element.GetAttributeOrValue("content"));
            var expr   = element.TryGetAttribute("isDefault");

            if (expr != null)
            {
                action.IsDefault = bool.Parse(expr);
            }

            expr = element.TryGetAttribute("isCancel");
            if (expr != null)
            {
                action.IsCancel = bool.Parse(expr);
            }

            action.Parameter    = element.TryGetAttribute("parameter");
            action.IsEnabled    = element.TryGetAttribute("enabled");
            action.Icon         = element.TryGetAttribute("icon");
            action.Validates    = element.TryGetAttribute("validates");
            action.ClosesDialog = element.TryGetAttribute("closesDialog");
            action.IsReset      = element.TryGetAttribute("resets");

            return(action);
        }
Beispiel #2
0
        internal void InitHandlers()
        {
            Type             type      = Type;
            ServiceAttribute attribute = type.GetCustomAttribute <ServiceAttribute>(false);

            Name = (attribute?.Name ?? type.Name);
            string url = "/" + Name + "/";

            foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
            {
                if (string.Compare("Equals", method.Name, true) == 0 ||
                    string.Compare("GetHashCode", method.Name, true) == 0 ||
                    string.Compare("GetType", method.Name, true) == 0 ||
                    string.Compare("ToString", method.Name, true) == 0 || method.Name.IndexOf("set_") >= 0 ||
                    method.Name.IndexOf("get_") >= 0)
                {
                    continue;
                }
                ActionAttribute aa        = method.GetCustomAttribute <ActionAttribute>(false);
                var             actionUrl = url + (aa == null ? method.Name : aa.Name);
                var             handler   = mHandlers.Values.FirstOrDefault(c => c.Url == actionUrl);
                if (handler != null)
                {
                    throw new ENException($"{type.Name}.{method.Name} action already exists, can add ActionAttribute on the method");
                }
                else
                {
                    handler                = new ActionHandlerProxy(method);
                    handler.Url            = actionUrl;
                    mHandlers[method.Name] = handler;
                }
            }
        }
Beispiel #3
0
        public Bitmap GenerateIcon(Type actionType)
        {
            var actionAtt = ActionAttribute.ExtractFrom(actionType);

            if (actionAtt == null)
            {
                return(null);
            }
            if (!string.IsNullOrWhiteSpace(actionAtt.IconForeground))
            {
                if (!string.IsNullOrWhiteSpace(actionAtt.IconBackground))
                {
                    return(IconResourceHelper.CombinedBitmapFromURIs(actionAtt.IconBackground, actionAtt.IconForeground));
                }
                else
                {
                    return(IconResourceHelper.BitmapFromURI(actionAtt.IconForeground));
                }
            }
            else if (!string.IsNullOrWhiteSpace(actionAtt.IconBackground))
            {
                return(IconResourceHelper.BitmapFromURI(actionAtt.IconBackground));
            }
            else
            {
                return(null);
            }
        }
Beispiel #4
0
        public ActionDescription(MethodInfo m)
            : base(m)
        {
            this.MethodInfo = m;
            this.Parameters = m.GetParameters();

            ActionAttribute attr = m.GetMyAttribute <ActionAttribute>(false);                   // ?? new ActionAttribute();

            if (attr == null)
            {
                attr = s_actionHelper.Instance.CreateDefaultActionAttribute();
            }

            this.Attr = attr;


            if (m.IsTaskMethod())
            {
                this.HasReturn = m.GetTaskMethodResultType() != null;
            }
            else
            {
                this.HasReturn = m.ReturnType != ReflectionHelper.VoidType;
            }
        }
Beispiel #5
0
        public ActionResult Create([Bind(Include = "PerfilID,PerfilDescripcion,PerfilInicial,PerfilOwerRequerido,ControladoraID,AccionID,RolID")] Perfil perfil)
        {
            if (ModelState.IsValid)
            {
                //db.Entry(perfil.Perfil_Rol).State = EntityState.Unchanged;
                //perfil.Perfil_Rol = null;

                string controladoraNombreFull = db.Controladoras.Where(i => i.ControladoraID == perfil.ControladoraID).Single().ControladoraNombreFull;
                CustomAssemblyHelper helper   = new CustomAssemblyHelper();
                var syscontroller             = helper.GetTypesAssemblyInstancia <Controller>(controladoraNombreFull);

                //Recupero todas las acciones de la controladorapor REFLECTION
                var             accionescontroladora = helper.GetControllerActions(syscontroller);
                var             nombreAccion         = db.Acciones.Where(r => r.AccionID == perfil.AccionID).Single().AccionNombre;
                var             action          = accionescontroladora.Where(r => r.Name == nombreAccion).Single();
                var             accionAtributos = helper.GetTypeAttributes <ActionAttribute>(action);
                ActionAttribute accionatributo  = (ActionAttribute)accionAtributos.FirstOrDefault();
                var             nombreRol       = db.Roles.Where(r => r.Id == perfil.RolID).Single().Name;

                var controladoraDesc = db.Controladoras.Where(i => i.ControladoraID == perfil.ControladoraID).Single().ControladoraDescripcion;
                //var accionDesc = db.Acciones.Where(i => i.AccionID == perfil.AccionID).Single().AccionDescripcion;
                perfil.PerfilDescripcion = controladoraDesc + " - " + accionatributo.AccionDescripcion + " - " + nombreRol;

                db.Perfiles.Add(perfil);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.AccionID       = new SelectList(db.Acciones, "AccionID", "AccionNombre", perfil.AccionID);
            ViewBag.ControladoraID = new SelectList(db.Controladoras, "ControladoraID", "ControladoraNombre", perfil.ControladoraID);
            //ViewBag.RolID = new SelectList(db.Roles, "Id", "Name", perfil.RolID);
            ViewBag.RolID = new SelectList(db.Roles, "Id", "Name", perfil.RolID);
            return(View(perfil));
        }
Beispiel #6
0
        private ActionAttribute GetActionAttribute(MethodInfo method)
        {
            ActionAttribute actionAttribute = (ActionAttribute)
                                              method.GetCustomAttribute(typeof(ActionAttribute));

            return(actionAttribute);
        }
        ///// <summary>
        ///// Constructor.  Call this from the default constructor of all subclasses, passing in the required information.
        ///// </summary>
        ///// <param name="commandName">The command name of the action that this component invokes</param>
        ///// <param name="name">The name of this component.  Keep it simple, single words are best.</param>
        ///// <param name="nickname">The abbreviation of this component.  Keep it short, 1-5 characters are best</param>
        ///// <param name="description">The description of this component.  Be succinct but clear.  You can supply whole sentances.</param>
        ///// <param name="category">The category of this component.  Controls which tab components will end up in.</param>
        ///// <param name="subCategory">The subcategory for this component.  Controls which group the component will be in.</param>
        //protected NewtBaseComponent(string commandName, string name, string nickname, string description,
        //    string subCategory, string category = CategoryName)
        //  : base()
        //{
        //    CommandName = commandName;
        //    Host.EnsureInitialisation();
        //    ActionType = Core.Instance.Actions.GetActionDefinition(CommandName);
        //    Name = name;
        //    NickName = nickname;
        //    Description = description;
        //    Category = category;
        //    SubCategory = subCategory;
        //    PostConstructor();
        //}

        /// <summary>
        /// Constructor.  Call this from the default constructor of all subclasses, passing in the required information.
        /// </summary>
        /// <param name="commandName">The command name of the action that this component invokes</param>
        /// <param name="name">The name of this component.  Keep it simple, single words are best.</param>
        /// <param name="nickname">The abbreviation of this component.  Keep it short, 1-5 characters are best</param>
        /// <param name="category">The category of this component.  Controls which tab components will end up in.</param>
        /// <param name="subCategory">The subcategory for this component.  Controls which group the component will be in.</param>
        protected SalamanderBaseComponent(string commandName, string name, string nickname,
                                          string subCategory, GH_Exposure exposure = GH_Exposure.primary, string category = CategoryName)
            : base()
        {
            CommandName = commandName;
            Host.EnsureInitialisation(true);
            ActionType = Core.Instance.Actions.GetActionDefinition(CommandName);
            if (ActionType == null)
            {
                throw new Exception("Command '" + CommandName + "' has not been found.  The plugin that contains it may not have been successfully loaded.");
            }
            var attributes = ActionAttribute.ExtractFrom(ActionType);

            Name        = name;
            NickName    = nickname;
            Description = attributes.Description.CapitaliseFirst();
            Category    = category;
            SubCategory = subCategory;
            _Exposure   = exposure;
            if (attributes.PreviewLayerType != null)
            {
                PreviewLayer = Activator.CreateInstance(attributes.PreviewLayerType) as DisplayLayer;
            }
            PostConstructor();
        }
Beispiel #8
0
		public ActionDescription(MethodInfo m, ActionAttribute atrr) : base(m)
		{
			this.MethodInfo = m;
			this.Attr = atrr;
			this.Parameters = m.GetParameters();
			this.HasReturn = m.ReturnType != ReflectionHelper.VoidType;
		}
 public ActionDescription(MethodInfo m, ActionAttribute atrr)
     : base(m)
 {
     this.MethodInfo = m;
     this.Attr       = atrr;
     this.Parameters = m.GetParameters();
     this.HasReturn  = m.ReturnType != ReflectionHelper.VoidType;
 }
        public static bool Init()
        {
            //We will search our assemblies for Quests by reflection so
            //it is not neccessary anymore to register new quests with the
            //server, it is done automatically!
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                // Walk through each type in the assembly
                foreach (Type type in assembly.GetTypes())
                {
                    // Pick up a class
                    if (type.IsClass != true)
                    {
                        continue;
                    }

                    if (typeof(IBehaviourAction).IsAssignableFrom(type))
                    {
                        ActionAttribute attr = GetActionAttribute(type);
                        if (attr != null)
                        {
                            if (log.IsInfoEnabled)
                            {
                                log.Info("Registering BehaviourAction: " + type.FullName);
                            }
                            RegisterBehaviourAction(attr.ActionType, type);
                        }
                    }

                    if (typeof(IBehaviourTrigger).IsAssignableFrom(type))
                    {
                        TriggerAttribute attr = getTriggerAttribute(type);
                        if (attr != null)
                        {
                            if (log.IsInfoEnabled)
                            {
                                log.Info("Registering BehaviourTrigger: " + type.FullName);
                            }
                            RegisterBehaviourTrigger(attr.TriggerType, type);
                        }
                    }

                    if (typeof(IBehaviourRequirement).IsAssignableFrom(type))
                    {
                        RequirementAttribute attr = getRequirementAttribute(type);
                        if (attr != null)
                        {
                            if (log.IsInfoEnabled)
                            {
                                log.Info("Registering BehaviourRequirement: " + type.FullName);
                            }
                            RegisterBehaviourRequirement(attr.RequirementType, type);
                        }
                    }
                }
            }
            return(true);
        }
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     if (value is IAction)
     {
         var att = ActionAttribute.ExtractFrom((IAction)value);
         return(att.IconForeground);
     }
     return(null);
 }
Beispiel #12
0
        public static void GetActionLabel(MethodInfo method, ActionAttribute actionAttribute, out CompoundTerm startActionLabel, out CompoundTerm /*?*/ finishActionLabel)
        {
            // TODO: extend this so that explict start/finish names may be given.
            // Currently, this implements only part of the specification. We need
            // to support named parameters and explicit start/finish names.
            if (!string.IsNullOrEmpty(actionAttribute.Name) && !string.IsNullOrEmpty(actionAttribute.Start))
            {
                throw new ModelProgramUserException("can't have positional argument name " + actionAttribute.Name + " and start action property " +
                                                    actionAttribute.Start + " specified in the same [Action] attribute.");
            }

            if (string.IsNullOrEmpty(actionAttribute.Start) != string.IsNullOrEmpty(actionAttribute.Finish))
            {
                if (!string.IsNullOrEmpty(actionAttribute.Start))
                {
                    throw new ModelProgramUserException("can't have start property " + actionAttribute.Start +
                                                        " in [Action] attribute without matching Finish property");
                }
                else
                {
                    throw new ModelProgramUserException("can't have finish property " + actionAttribute.Finish +
                                                        " in [Action] attribute without matching Start property");
                }
            }


            bool isAtomic = ReflectionHelper.HasNoOutputs(method) && string.IsNullOrEmpty(actionAttribute.Finish);

            // if method has outputs and you want to provide individual parameters, you must use Start/Finish
            if (!isAtomic && !string.IsNullOrEmpty(actionAttribute.Name) &&
                actionAttribute.Name.Contains("("))
            {
                throw new ModelProgramUserException("must provide explict Start/Finish properties for nonvoid action method " + actionAttribute.Name);
            }

            string baseName          = string.IsNullOrEmpty(actionAttribute.Name) ? method.Name : actionAttribute.Name;
            string startActionString = (!string.IsNullOrEmpty(actionAttribute.Start) ?
                                        actionAttribute.Start :
                                        (isAtomic ? baseName : (baseName + "_Start")));

            string[] inputParameterNames = GetInputParameterNames(method);
            startActionLabel = GetActionTerm(startActionString, inputParameterNames, true, Set <string> .EmptySet);


            if (!isAtomic)
            {
                string finishActionString = (!string.IsNullOrEmpty(actionAttribute.Finish) ?
                                             actionAttribute.Finish : baseName + "_Finish");

                Set <string> optionalArguments = new Set <string>(inputParameterNames);
                finishActionLabel = GetActionTerm(finishActionString, GetOutputParameterNames(method), false, optionalArguments);
            }
            else
            {
                finishActionLabel = null;
            }
        }
        public ActionEntry DeSerialize(string content)
        {
            var type   = Type.GetType(content);
            var action = Activator.CreateInstance(type) as IAction;

            return(new ActionEntry()
            {
                Action = action,
                Meta = ActionAttribute.GetActionMeta(type)
            });
        }
		public ActionDescription(MethodInfo m, ActionAttribute atrr)
			: base(m)
		{
			this.MethodInfo = m;
			this.Attr = atrr;
			this.Parameters = m.GetParameters();

			if( m.IsTaskMethod() )
				this.HasReturn = m.GetTaskMethodResultType() != null;
			else
				this.HasReturn = m.ReturnType != ReflectionHelper.VoidType;
		}
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        BadWordsListControlExtender extender = new BadWordsListControlExtender();
        extender.Init(UniGrid);

        ActionAttribute addNewBadWord = new ActionAttribute(0, "BadWords_List.NewItemCaption",
            URLHelper.AddParameterToUrl(UIContextHelper.GetElementUrl("CMS.BadWords", "Administration.BadWords.New"), "displaytitle", "false"));
        addNewBadWord.Apply(this);

        UniGrid.ZeroRowsText = GetString("general.nodatafound");
    }
Beispiel #16
0
        private ActionDescription CreatePageActionDescription(ControllerDescription controller, MethodInfo m)
        {
            ActionAttribute actionAttr = m.GetMyAttribute <ActionAttribute>();

            if (actionAttr == null)
            {
                actionAttr = new ActionAttribute();                             // 不指定就采用默认实例
            }
            return(new ActionDescription(m, actionAttr)
            {
                PageController = controller
            });
        }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        BadWordsListControlExtender extender = new BadWordsListControlExtender();

        extender.Init(UniGrid);

        ActionAttribute addNewBadWord = new ActionAttribute(0, "BadWords_List.NewItemCaption",
                                                            URLHelper.AddParameterToUrl(UIContextHelper.GetElementUrl("CMS.BadWords", "Administration.BadWords.New"), "displaytitle", "false"));

        addNewBadWord.Apply(this);

        UniGrid.ZeroRowsText = GetString("general.nodatafound");
    }
Beispiel #18
0
        private void OnRegister(ControllerAttribute attribute, Type type, object controller)
        {
            foreach (Type itype in attribute.Types)
            {
                if (!itype.IsInterface)
                {
                    continue;
                }
                if (type.GetInterface(itype.Name) == null)
                {
                    continue;
                }
                string url = "/" + (attribute.Name ?? itype.Name) + "/";
                foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                {
                    try
                    {
                        if (string.Compare("Equals", method.Name, true) == 0 ||
                            string.Compare("GetHashCode", method.Name, true) == 0 ||
                            string.Compare("GetType", method.Name, true) == 0 ||
                            string.Compare("ToString", method.Name, true) == 0 || method.Name.IndexOf("set_") >= 0 ||
                            method.Name.IndexOf("get_") >= 0)
                        {
                            continue;
                        }
                        ActionAttribute aa        = method.GetCustomAttribute <ActionAttribute>(false);
                        var             actionUrl = url + (aa == null ? method.Name : aa.Name);
                        if (mActionHadlers.TryGetValue(actionUrl, out ActionHandler handler))
                        {
                            Server.Log(EventArgs.LogType.Warring, $"{itype.Name}->{type.Name}.{method.Name} action already exists, can add ActionAttribute on the method");
                        }
                        else
                        {
                            handler = new ActionHandler(type, method, controller);
                            handler.SingleInstance    = attribute.SingleInstance;
                            handler.Interface         = itype;
                            mActionHadlers[actionUrl] = handler;

                            Server.Log(EventArgs.LogType.Info, $"Register {itype.Name}->{type.Name}@{method.Name} to {actionUrl}");
                        }
                    }
                    catch (Exception e_)
                    {
                        Server.Log(EventArgs.LogType.Error, $"Register {itype.Name}->{type.Name}@{method.Name} action error {e_.Message}@{e_.StackTrace}");
                    }
                }
            }
        }
Beispiel #19
0
 private static bool FighterHasTargetableAttributes(Fighter fighterCandidate, ActionAttribute attackingAttribute)
 {
     if (HasFlag(ActionAttribute.Rock, attackingAttribute) && HasFlag(FighterAttribute.Paper, fighterCandidate.FighterData.fighterAttributes))
     {
         return(false);
     }
     if (HasFlag(ActionAttribute.Paper, attackingAttribute) && HasFlag(FighterAttribute.Scissors, fighterCandidate.FighterData.fighterAttributes))
     {
         return(false);
     }
     if (HasFlag(ActionAttribute.Scissors, attackingAttribute) && HasFlag(FighterAttribute.Rock, fighterCandidate.FighterData.fighterAttributes))
     {
         return(false);
     }
     return(true);
 }
Beispiel #20
0
        public ActionDescription(MethodInfo m, ActionAttribute atrr)
            : base(m)
        {
            this.MethodInfo = m;
            this.Attr       = atrr;
            this.Parameters = m.GetParameters();

            if (m.IsTaskMethod())
            {
                this.HasReturn = m.GetTaskMethodResultType() != null;
            }
            else
            {
                this.HasReturn = m.ReturnType != ReflectionHelper.VoidType;
            }
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is IAction)
            {
                var att = ActionAttribute.ExtractFrom((IAction)value);
                return(att.IconBackground);

                /*var uri = new Uri(att.IconBackground);
                 * var src = new BitmapImage();
                 * src.BeginInit();
                 * src.CacheOption = BitmapCacheOption.OnLoad;
                 * src.UriSource = uri;
                 * return src;*/
            }
            return(null);
        }
Beispiel #22
0
        public ActionBinding(ActionAttribute actionAttribute, MemberInfo memberInfo, object target) : base(actionAttribute, memberInfo, target)
        {
            if (memberInfo.MemberType != MemberTypes.Method)
            {
                ThrowCantCreateBindingForMemberTypeException();
            }

            _methodInfo = memberInfo.DeclaringType.GetMethod(memberInfo.Name);

            Group = actionAttribute.Group;

            _button = new Button {
                Text = actionAttribute.TooltipText
            };
            _button.Click += (sender, args) => Invoke();
        }
Beispiel #23
0
        private static string GenerateActions(MethodInfo[] methods)
        {
            string actionsCode = "";

            foreach (MethodInfo method in methods)
            {
                ActionAttribute action = method.GetCustomAttribute <ActionAttribute>();

                if (action != null)
                {
                    actionsCode += GenerateAction(method, action);
                }
            }

            return(actionsCode);
        }
        /// <summary>
        /// Initializes a new instance of the AbstractAction class.
        /// </summary>
        /// <param name="npc"></param>
        /// <param name="actionType"></param>
        /// <param name="p"></param>
        /// <param name="q"></param>
        public AbstractAction(GameNPC npc, eActionType actionType, object p, object q) : this(npc, actionType)
        {
            ActionAttribute attr = BehaviourMgr.GetActionAttribute(GetType());

            // handle parameter P
            object defaultValueP = GetDefaultValue(attr.DefaultValueP);

            this.p = (TypeP)BehaviourUtils.ConvertObject(p, defaultValueP, typeof(TypeP));
            CheckParameter(this.p, attr.IsNullableP, typeof(TypeP));

            // handle parameter Q
            object defaultValueQ = GetDefaultValue(attr.DefaultValueQ);

            this.q = (TypeQ)BehaviourUtils.ConvertObject(q, defaultValueQ, typeof(TypeQ));
            CheckParameter(this.q, attr.IsNullableQ, typeof(TypeQ));
        }
Beispiel #25
0
        private async Task HandleMessage(string content)
        {
            using (SentrySdk.Init(configuration.GetSection("Sentry:DSN").Value))
            {
                var request = JsonConvert.DeserializeObject <FiltroRelatorioDto>(content);
                try
                {
                    _logger.LogInformation($"[ INFO ] Messaged received: {content}");

                    if (!content.Equals("null"))
                    {
                        MethodInfo[] methods = typeof(WorkerSGPController).GetMethods();

                        foreach (MethodInfo method in methods)
                        {
                            ActionAttribute actionAttribute = GetActionAttribute(method);
                            if (actionAttribute != null && actionAttribute.Name == request.Action)
                            {
                                _logger.LogInformation($"[ INFO ] Invoking action: {request.Action}");

                                var serviceProvider = _scopeFactory.CreateScope().ServiceProvider;

                                var controller = serviceProvider.GetRequiredService <WorkerSGPController>();
                                var useCase    = serviceProvider.GetRequiredService(actionAttribute.TipoCasoDeUso);

                                await method.InvokeAsync(controller, new object[] { request, useCase });

                                _logger.LogInformation($"[ INFO ] Action terminated: {request.Action}");
                                return;
                            }
                        }

                        _logger.LogInformation($"[ INFO ] Method not found to action: {request.Action}");
                    }
                }
                catch (NegocioException ex)
                {
                    NotificarUsuarioRelatorioComErro(request, ex.Message);
                    SentrySdk.CaptureException(ex);
                }
                catch (Exception ex)
                {
                    NotificarUsuarioRelatorioComErro(request, "Erro não identificado, por favor tente novamente.");
                    SentrySdk.CaptureException(ex);
                }
            }
        }
Beispiel #26
0
        public static ActionAttribute GetAction(XElement element)
        {
            var action = new ActionAttribute(element.TryGetAttribute("name"), element.GetAttributeOrValue("content"))
            {
                IsDefault    = BoolOrText(element.TryGetAttribute("isDefault")),
                IsCancel     = BoolOrText(element.TryGetAttribute("isCancel")),
                Parameter    = element.TryGetAttribute("parameter"),
                IsEnabled    = BoolOrText(element.TryGetAttribute("enabled")),
                IsLoading    = BoolOrText(element.TryGetAttribute("isLoading")),
                Icon         = element.TryGetAttribute("icon"),
                Validates    = BoolOrText(element.TryGetAttribute("validates")),
                ClosesDialog = BoolOrText(element.TryGetAttribute("closesDialog")),
                IsReset      = BoolOrText(element.TryGetAttribute("resets") ?? element.TryGetAttribute("isReset")),
                IsPrimary    = BoolOrText(element.TryGetAttribute("isPrimary"))
            };

            return(action);
        }
Beispiel #27
0
        protected virtual void InitMenu()
        {
            this.menuItems = new Dictionary <string, MenuItem>();
            var attrs = ActionAttribute.GetActions(this.DataContext.GetDataType(), ActionTarget.FormMenu);

            if (attrs != null)
            {
                foreach (var attr in attrs)
                {
                    this.addMenuAction(new Types.Action(attr, this.DataContext));
                }

                foreach (var item in this.menuItems.Values)
                {
                    this.addMenuItem(null, item);
                }
            }
        }
Beispiel #28
0
        public override void Revocation()
        {
            Attribute attr = this.LogContent.GetLastAttribute;

            if (attr != null)
            {
                //获取Attr开始撤销动作
                ModifyAttribute ma = attr as ModifyAttribute;
                ActionAttribute aa = attr as ActionAttribute;
                if (ma != null)
                {
                    this.Revocation(ma);
                }
                if (aa != null)
                {
                    this.Revocation(aa);
                }
            }
        }
        private static void CreateActionsElement(Project project, XmlElement projectElement)
        {
            XmlDocument doc = projectElement.OwnerDocument;

            XmlAttribute att;
            XmlElement   actionsElement = AppendNewXmlElement(projectElement, "actions", "");

            foreach (BaseAction action in project.Actions)
            {
                XmlElement actionElement = AppendNewXmlElement(actionsElement, "action", "");
                att = doc.CreateAttribute("typename");
                // Get the attribute name
                object[]        customAttributes = action.GetType().GetCustomAttributes(typeof(ActionAttribute), false);
                ActionAttribute actionAttribute  = (ActionAttribute)customAttributes[0];
                att.Value = actionAttribute.OwnerType.FullName;
                actionElement.Attributes.Append(att);
                actionElement.InnerXml = action.SaveToXml();
            }
        }
Beispiel #30
0
    static public ActionAttribute operator +(ActionAttribute a, ActionAttribute b)
    {
        ActionAttribute unitAttribute = new ActionAttribute();

        unitAttribute.m_damage         = a.m_damage + b.m_damage;
        unitAttribute.m_damageAdd      = a.m_damageAdd + b.m_damageAdd;
        unitAttribute.m_damageMultiply = a.m_damageMultiply + b.m_damageMultiply;

        unitAttribute.m_attackSpeed         = a.m_attackSpeed + b.m_attackSpeed;
        unitAttribute.m_attackSpeedAdd      = a.m_attackSpeedAdd + b.m_attackSpeedAdd;
        unitAttribute.m_attackSpeedMultiply = a.m_attackSpeedMultiply + b.m_attackSpeedMultiply;

        unitAttribute.m_moveSpeed         = a.m_moveSpeed + b.m_moveSpeed;
        unitAttribute.m_moveSpeedAdd      = a.m_moveSpeedAdd + b.m_moveSpeedAdd;
        unitAttribute.m_moveSpeedMultiply = a.m_moveSpeedMultiply + b.m_moveSpeedMultiply;

        unitAttribute.m_hp         = a.m_hp + b.m_hp;
        unitAttribute.m_hpAdd      = a.m_hpAdd + b.m_hpAdd;
        unitAttribute.m_hpMultiple = a.m_hpMultiple + b.m_hpMultiple;
        return(unitAttribute);
    }
        public virtual void RenderAction(DTInspectorNode node, ActionAttribute action, System.Object editorObject, System.Object targetObject)
        {
            switch (action.Action)
            {
            case ActionAttribute.ActionEnum.ShowInfo:
                EditorGUILayout.HelpBox(action.ActionData as string, MessageType.Info);
                return;

            case ActionAttribute.ActionEnum.ShowWarning:
                EditorGUILayout.HelpBox(action.ActionData as string, MessageType.Warning);
                return;

            case ActionAttribute.ActionEnum.ShowError:
                EditorGUILayout.HelpBox(action.ActionData as string, MessageType.Error);
                return;

            case ActionAttribute.ActionEnum.Callback:
                action.Callback(editorObject);
                return;
            }
        }
Beispiel #32
0
        private static string GenerateAction(MethodInfo method, ActionAttribute action)
        {
            string actionField = "";

            actionField += "[Action(\"" + action.Name + "\")]\n";
            actionField += GenerateActionValues(method);
            actionField += GenerateLocalization(method);

            actionField += "public void " + method.Name + " (";

            ParameterInfo[] parameters = method.GetParameters().OrderBy(p => p.Position).ToArray();


            string paramsCall = "";

            using (var provider = new CSharpCodeProvider())
            {
                for (int i = 0; i < parameters.Length; i++)
                {
                    ParameterInfo parameter = parameters[i];

                    var    typeRef       = new CodeTypeReference(parameter.ParameterType);
                    string paramTypeName = provider.GetTypeOutput(typeRef);

                    actionField += paramTypeName + " " + parameter.Name;
                    paramsCall  += parameter.Name;

                    if (i + 1 < parameters.Length)
                    {
                        actionField += ", ";
                        paramsCall  += ", ";
                    }
                }
            }

            actionField += ") { _object." + method.Name + "(" + paramsCall + "); }\n\n";

            return(actionField);
        }
Beispiel #33
0
        /// <summary>
        /// Fills method invocation param array with args doing some interpretation for widely used types like JSONDataMaps, Rows etc..
        /// </summary>
        protected virtual void BindParameters(Controller controller, string action, ActionAttribute attrAction, MethodInfo method, WorkContext work, out object[] args)
        {
            var mpars = method.GetParameters();

            args = new object[mpars.Length];

            if (mpars.Length == 0)
            {
                return;
            }

            var requested = work.WholeRequestAsJSONDataMap;

            var strictParamBinding = attrAction.StrictParamBinding;

            //check for complex type
            for (var i = 0; i < mpars.Length; i++)
            {
                var ctp = mpars[i].ParameterType;
                if (ctp == typeof(object) || ctp == typeof(JSONDataMap) || ctp == typeof(Dictionary <string, object>))
                {
                    args[i] = requested;
                    continue;
                }
                if (typeof(TypedRow).IsAssignableFrom(ctp))
                {
                    try
                    {
                        args[i] = JSONReader.ToRow(ctp, requested);
                        continue;
                    }
                    catch (Exception error)
                    {
                        throw new HTTPStatusException(WebConsts.STATUS_400,
                                                      WebConsts.STATUS_400_DESCRIPTION,
                                                      error.ToMessageWithType(),
                                                      error);
                    }
                }
            }

            for (var i = 0; i < args.Length; i++)
            {
                if (args[i] != null)
                {
                    continue;
                }

                var mp = mpars[i];

                var got = requested[mp.Name];

                if (got == null)
                {
                    if (mp.HasDefaultValue)
                    {
                        args[i] = mp.DefaultValue;
                    }
                    continue;
                }

                if (got is byte[])
                {
                    if (mp.ParameterType == typeof(byte[]))
                    {
                        args[i] = got;
                        continue;
                    }
                    if (mp.ParameterType == typeof(Stream) || mp.ParameterType == typeof(MemoryStream))
                    {
                        args[i] = new MemoryStream((byte[])got, false);
                        continue;
                    }
                    if (strictParamBinding)
                    {
                        throw new HTTPStatusException(Web.WebConsts.STATUS_400,
                                                      Web.WebConsts.STATUS_400_DESCRIPTION,
                                                      StringConsts.MVCCONTROLLER_ACTION_PARAM_BINDER_ERROR
                                                      .Args(
                                                          controller.GetType().DisplayNameWithExpandedGenericArgs(),
                                                          strictParamBinding ? "strict" : "relaxed",
                                                          action,
                                                          mp.Name,
                                                          mp.ParameterType.DisplayNameWithExpandedGenericArgs(), "byte[]"));
                    }
                }//got byte[]

                var strVal = got.AsString();
                try
                {
                    args[i] = strVal.AsType(mp.ParameterType, strictParamBinding);
                }
                catch
                {
                    const int MAX_LEN = 30;
                    if (strVal.Length > MAX_LEN)
                    {
                        strVal = strVal.Substring(0, MAX_LEN) + "...";
                    }
                    throw new HTTPStatusException(WebConsts.STATUS_400,
                                                  WebConsts.STATUS_400_DESCRIPTION,
                                                  StringConsts.MVCCONTROLLER_ACTION_PARAM_BINDER_ERROR
                                                  .Args(
                                                      controller.GetType().DisplayNameWithExpandedGenericArgs(),
                                                      strictParamBinding ? "strict" : "relaxed",
                                                      action,
                                                      mp.Name,
                                                      mp.ParameterType.DisplayNameWithExpandedGenericArgs(), strVal));
                }
            }
        }
		private ActionDescription CreatePageActionDescription(ControllerDescription controller, MethodInfo m)
		{
			ActionAttribute actionAttr = m.GetMyAttribute<ActionAttribute>();
			if( actionAttr == null )
				actionAttr = new ActionAttribute();		// 不指定就采用默认实例

			return new ActionDescription(m, actionAttr) { PageController = controller };
		}