Пример #1
0
 public OperationFilterContext(MethodInfo method, JsonSchemaResolver schemaResolver, JsonSchemaGenerator schemaGenerator, OperationAttribute operation)
 {
     Method          = method;
     SchemaResolver  = schemaResolver;
     SchemaGenerator = schemaGenerator;
     Operation       = operation;
 }
Пример #2
0
        static void Populate(Dictionary <string, OperationBase> _operations)
        {
            _operations.Clear();

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            for (int i = 0; i < assemblies.Length; i++)
            {
                Type[] loadedTypes = assemblies[i].GetTypes();
                for (int j = 0; j < loadedTypes.Length; j++)
                {
                    OperationAttribute operationAttribute = (OperationAttribute)Attribute.GetCustomAttribute(loadedTypes[j], typeof(OperationAttribute));
                    if (operationAttribute == null)
                    {
                        continue;
                    }

                    if (!ExtendsFrom(loadedTypes[j].BaseType, typeof(OperationBase)))
                    {
                        continue;
                    }

                    _operations.Add(operationAttribute.OperationKey, (OperationBase)Activator.CreateInstance(loadedTypes[j]));
                }
            }
        }
 public override void OnActionExecuted(ActionExecutedContext filterContext)
 {
     #region 记录操作日志
     var c = filterContext.Controller as Controllers.BaseController;
     if (c == null)
     {
         return;
     }
     //忽略列表和浏览查询
     if (filterContext.ActionDescriptor.DisplayName.Contains("Get", StringComparison.OrdinalIgnoreCase))
     {
         return;
     }
     //忽略登录退出
     if (filterContext.ActionDescriptor.DisplayName.Contains("Account", StringComparison.OrdinalIgnoreCase))
     {
         return;
     }
     //忽略主页
     if (filterContext.ActionDescriptor.DisplayName.Contains("Home", StringComparison.OrdinalIgnoreCase))
     {
         return;
     }
     //忽略显示
     if (filterContext.ActionDescriptor.DisplayName.Contains("Index", StringComparison.OrdinalIgnoreCase))
     {
         return;
     }
     if (c != null)
     {
         var operationalLog = new OperationalLog
         {
             Id              = Guid.NewGuid(),
             Controller      = filterContext.ActionDescriptor.RouteValues["Controller"],
             Action          = filterContext.ActionDescriptor.RouteValues["Action"],
             OperationalIp   = c.Ip,
             UserManagerId   = c.UserManager.Id,
             OperationalTime = DateTime.Now
         };
         if (filterContext.ActionDescriptor.EndpointMetadata.Any(d => d.GetType() == typeof(OperationAttribute)))
         {
             //实例化这个特性
             OperationAttribute Operation = (OperationAttribute)filterContext.ActionDescriptor.EndpointMetadata.Where(d => d.GetType() == typeof(OperationAttribute)).FirstOrDefault();
             if (Operation.IgnoreLog)
             {
                 return;
             }
             else
             {
                 operationalLog.OperationalName = Operation.OperationName;
             }
         }
         if (filterContext.Exception != null)
         {
             operationalLog.OperationalState = 2;
         }
         new SqlServerHelper().Insert(operationalLog);
     }
     #endregion
 }
Пример #4
0
        private void AddOperationImage(Type type)
        {
            OperationAttribute attribute = (OperationAttribute)Attribute.GetCustomAttribute(type, typeof(OperationAttribute));

            if (attribute?.IconResourceName != null && !batchImageList.Images.ContainsKey(type.FullName))
            {
                batchImageList.Images.Add(type.FullName, attribute.GetIcon(type.Assembly));
            }
        }
Пример #5
0
        public static Operation CreateOperationObject(MemberInfo method)
        {
            Operation op = new Operation();

            OperationAttribute operationAttrib = method.GetCustomAttribute <OperationAttribute>();

            if (operationAttrib == null)
            {
                throw new Exception(string.Format("The custom operation '{0}', doesn't contain the OperationAttribute.", method.Name));
            }

            op.Verb                 = operationAttrib.Verb.ToString();
            op.Static               = operationAttrib.Static;
            op.Path                 = operationAttrib.Path;
            op.Response             = new Response();
            op.Response.ContentType = operationAttrib.ResponseContentType;
            op.Response.Type        = operationAttrib.ResponseType;

            if (!string.IsNullOrEmpty(operationAttrib.ErrorResponseType))
            {
                op.ErrorResponse      = new ErrorResponse();
                op.ErrorResponse.Type = operationAttrib.ErrorResponseType;
                if (!string.IsNullOrEmpty(operationAttrib.ErrorResponseProperties))
                {
                    string[] errorProperties = operationAttrib.ErrorResponseProperties.Split(';');
                    op.ErrorResponse.Properties = new Dictionary <string, string>();
                    foreach (string errorProperty in errorProperties)
                    {
                        if (!string.IsNullOrEmpty(errorProperty))
                        {
                            string[] splitProperty = errorProperty.Split(':');
                            if (splitProperty.Length == 2)
                            {
                                op.ErrorResponse.Properties.Add(splitProperty[0], splitProperty[1]);
                            }
                        }
                    }
                }
            }

            foreach (ParamAttribute paramAttribute in method.GetCustomAttributes <ParamAttribute>())
            {
                if (op.Parameters == null)
                {
                    op.Parameters = new Dictionary <string, VSPlugin.Parameters>();
                }
                op.Parameters.Add(paramAttribute.Name, new VSPlugin.Parameters()
                {
                    Kind     = paramAttribute.Kind.ToStringAPS(),
                    Required = paramAttribute.Required,
                    Type     = Utility.ConvertType2APSType(paramAttribute.Type)
                });
            }

            return(op);
        }
        private Message GenerateMessage(MethodInfo method, OperationAttribute operationAttribute, ISchemaRepository schemaRepository)
        {
            var message = new Message
            {
                Payload = _schemaGenerator.GenerateSchema(operationAttribute.MessagePayloadType, schemaRepository),
                // todo: all the other properties... message has a lot!
            };

            return(message);
        }
        private Operation GenerateOperation(TypeInfo asyncApiTypeInfo, OperationAttribute operationAttribute, IEnumerable <MethodInfo> methods, SchemaRepository schemaRepository, MessageRepository messageRepository)
        {
            if (!methods.Any())
            {
                return(null);
            }

            var operation = new Operation
            {
                OperationId = operationAttribute.OperationId ?? asyncApiTypeInfo.FullName + $".{operationAttribute.Type}",
                Summary     = operationAttribute.Summary,
                Description = operationAttribute.Description,
                Message     = GenerateReferenceOfMessage(methods.SelectMany(method => (MessageAttribute[])method.GetCustomAttributes(typeof(MessageAttribute), true)).ToArray(), schemaRepository, messageRepository)
            };

            return(operation);
        }
Пример #8
0
        /// <summary>
        /// 加载 Roslim 插件。
        /// </summary>
        /// <param name="scriptFiles">Roslim 插件列表。</param>
        /// <returns>加载的插件数目。</returns>
        private int LoadScriptPlugins(string[] scriptFiles)
        {
            int count = 0;

            foreach (string file in scriptFiles)
            {
                try
                {
                    _logger.LogDebug($"Loading plugin: {file}");

                    var(meta, pluginAssembly) = _roslimGenerator.Generate(file);
                    Type exportedType = pluginAssembly.GetExportedTypes()
                                        .First(type => Attribute.GetCustomAttribute(type, typeof(OperationAttribute)) is not null);

                    string pluginName = pluginAssembly.FullName;

                    _logger.LogDebug($"Parsing components in plugin: {pluginName}");

                    OperationAttribute operationAttribute =
                        Attribute.GetCustomAttribute(exportedType, typeof(OperationAttribute))
                        as OperationAttribute;

                    RoslimMeta pluginMeta = new(
                        meta["name"] !.ToObject <string>(),
                        meta["description"] !.ToObject <string>(),
                        meta["author"] !.ToObject <string>());

                    OperationCollection.Add(new(operationAttribute, pluginMeta, exportedType));

                    MetaCollection.Add((pluginMeta, pluginAssembly));

                    _logger.LogDebug($"Operation {operationAttribute.Name} loaded.");
                    _logger.LogDebug($"Plugin {pluginName} loaded.");

                    count++;
                }
                catch (Exception e)
                {
                    _logger.LogWarning(e, $"在加载插件 {file} 时发生错误。将跳过该插件的加载。");
                }
            }

            return(count);
        }
Пример #9
0
        private void BatchContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                addOperationToolStripMenuItem.DropDownItems.Clear();
                BindableTreeNode batchNode      = ClientUtility.GetContextMenuTreeviewNode(batchTreeView, sender);
                Type             batchType      = batchNode.DataSource.GetType();
                List <Type>      operationTypes = CoreUtility.GetInterfaceImplementorsWithAttribute(typeof(IOperation), typeof(OperationAttribute));

                foreach (Type operationType in operationTypes)
                {
                    OperationAttribute operationAttribute            = (OperationAttribute)Attribute.GetCustomAttribute(operationType, typeof(OperationAttribute));
                    ToolStripMenuItem  addOperationToolStripMenuItem = new ToolStripMenuItem()
                    {
                        ImageScaling = ToolStripItemImageScaling.None,
                        Tag          = operationType
                    };
                    addOperationToolStripMenuItem.Click      += AddOperationToolStripMenuItem_Click;
                    addOperationToolStripMenuItem.Text        = operationAttribute.DisplayName;
                    addOperationToolStripMenuItem.ToolTipText = operationAttribute.Description;
                    addOperationToolStripMenuItem.Image       = operationAttribute.GetIcon(operationType.Assembly);
                    this.addOperationToolStripMenuItem.DropDownItems.Add(addOperationToolStripMenuItem);
                }

                // sort by name
                ArrayList menuItems = new ArrayList(this.addOperationToolStripMenuItem.DropDownItems);
                menuItems.Sort(new ToolStripItemComparer());
                addOperationToolStripMenuItem.DropDownItems.Clear();

                foreach (ToolStripItem menuItem in menuItems)
                {
                    addOperationToolStripMenuItem.DropDownItems.Add(menuItem);
                }

                addOperationToolStripMenuItem.Enabled = addOperationToolStripMenuItem.DropDownItems.Count > 0;
            }
            catch (Exception ex)
            {
                ApplicationState.Default.RaiseNotification(new NotificationEventArgs(NotificationType.Error, ex.Message, ex));
            }
        }
Пример #10
0
 protected OperationInfo(MethodInfo methodInfo, OperationAttribute operationAttribute)
 {
     MethodInfo         = methodInfo;
     OperationAttribute = operationAttribute;
 }
Пример #11
0
 public OperationFilterContext(MethodInfo method, ISchemaRepository schemaRepository, OperationAttribute operation)
 {
     Method           = method;
     SchemaRepository = schemaRepository;
     Operation        = operation;
 }
Пример #12
0
        /// <summary>
        /// 获取查询字段
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        internal static string Select(this AttrBaseResult model)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("SELECT ");
            foreach (var prop in model.GetType().GetProperties())
            {
                //如果字段标记非查询属性,则直接跳过
                if (prop.IsDefined(typeof(NonSelectAttribute), true))
                {
                    continue;
                }
                //若该属性没有标记字段,则直接使用该字段
                if (prop.GetCustomAttributes(true).Length == 0)
                {
                    builder.Append($"{prop.Name},");
                    continue;
                }
                //是否使用函数
                if (prop.IsDefined(typeof(NonAggregateFuncFieldAttribute), true))
                {
                    NonAggregateFuncFieldAttribute funcFieldAttribute = prop.GetCustomAttributes(typeof(NonAggregateFuncFieldAttribute), true)[0] as NonAggregateFuncFieldAttribute;
                    builder.Append($"{funcFieldAttribute.GetNonAggregateFuncField()} AS ");
                    builder.Append($"{prop.Name},");
                    continue;
                }
                //是否使用聚合函数
                if (prop.IsDefined(typeof(AggregateFuncFieldAttribute), true))
                {
                    AggregateFuncFieldAttribute funcFieldAttribute = prop.GetCustomAttributes(typeof(AggregateFuncFieldAttribute), true)[0] as AggregateFuncFieldAttribute;
                    builder.Append($"{funcFieldAttribute.GetAggregateFuncField()} AS ");
                    builder.Append($"{prop.Name},");
                    continue;
                }
                //是否使用运算符操作
                if (prop.IsDefined(typeof(OperationAttribute), true))
                {
                    OperationAttribute operation = prop.GetCustomAttributes(typeof(OperationAttribute), true)[0] as OperationAttribute;
                    builder.Append($"{operation.GetExpression()} AS {prop.Name},");
                    continue;
                }
                //表别名.字段名 AS 字段别名
                if (prop.IsDefined(typeof(TableByNameAttribute), true))
                {
                    TableByNameAttribute byName = prop.GetCustomAttributes(typeof(TableByNameAttribute), true)[0] as TableByNameAttribute;
                    builder.Append($"{byName.GetName()}.");
                }
                if (prop.IsDefined(typeof(DbFieldNameAttribute), true))
                {
                    DbFieldNameAttribute fieldName = prop.GetCustomAttributes(typeof(DbFieldNameAttribute), true)[0] as DbFieldNameAttribute;
                    builder.Append($"{fieldName.GetDbFieldName()} AS ");
                    builder.Append($"{prop.Name},");
                }
                else
                {
                    builder.Append($"{prop.Name},");
                }
            }
            //移除最后一个逗号
            builder.Remove(builder.Length - 1, 1);
            builder.Append(" ");
            return(builder.ToString());
        }
Пример #13
0
 public StackOperation(RealNumber value, BinaryOperation operation)
 {
     Value     = value;
     Operation = operation;
     attribute = OperationAttribute.Get(operation);
 }
Пример #14
0
 public QueryInfo(MethodInfo methodInfo, OperationAttribute attribute)
     : base(methodInfo, attribute)
 {
 }
Пример #15
0
 public CommandInfo(MethodInfo methodInfo, OperationAttribute attribute)
     : base(methodInfo, attribute)
 {
 }
Пример #16
0
        /// <summary>
        /// 加载 DLL 插件。
        /// </summary>
        /// <param name="dllFiles">DLL 插件列表。</param>
        private void LoadDllPlugins(string[] dllFiles)
        {
            foreach (string file in dllFiles)
            {
                try
                {
                    _logger.LogDebug($"Loading plugin: {file}");

                    Assembly pluginAssembly = LoadPlugin(file);
                    Type[]   exportedTypes  = pluginAssembly.GetExportedTypes();

                    string pluginName = pluginAssembly.FullName;

                    _logger.LogDebug($"Parsing meta in plugin: {pluginName}");

                    Type[] metaTypes = exportedTypes.Where(type =>
                                                           Attribute.GetCustomAttribute(type, typeof(RmboxPluginAttribute)) is not null).ToArray();

                    if (metaTypes.Length != 1)
                    {
                        string err = $"插件 {pluginName} 具有的元信息的个数 {metaTypes.Length} 不符合 1 的要求。";
                        _logger.LogError(err);
                        throw new IndexOutOfRangeException(err);
                    }

                    // ReSharper disable once UseNegatedPatternMatching
                    IMeta pluginMeta = Activator.CreateInstance(metaTypes.Single()) as IMeta;
                    if (pluginMeta is null)
                    {
                        string err = $"在加载插件 {pluginName} 的元信息时发生错误。";
                        _logger.LogError(err);
                        throw new ArgumentNullException(nameof(pluginMeta));
                    }

                    _logger.LogDebug($"Meta parsed in: {pluginMeta.Name}");

                    MetaCollection.Add((pluginMeta, pluginAssembly));

                    _logger.LogDebug($"Parsing components in plugin: {pluginMeta.Name}");

                    List <Type> operationTypes = exportedTypes.Where(type =>
                                                                     Attribute.GetCustomAttribute(type, typeof(OperationAttribute)) is not null).ToList();

                    foreach (Type t in operationTypes.Where(type => !type.IsAssignableTo(typeof(IOperation)))
                             .ToArray())
                    {
                        _logger.LogWarning($"检测到错误导出的类型 {t.FullName},将会忽略加载。");
                        operationTypes.Remove(t);
                    }

                    foreach (Type operationType in operationTypes)
                    {
                        OperationAttribute operationAttribute =
                            Attribute.GetCustomAttribute(operationType, typeof(OperationAttribute))
                            as OperationAttribute;

                        OperationCollection.Add((operationAttribute, pluginMeta, operationType));

                        _logger.LogDebug($"Operation {operationAttribute.Name} loaded.");
                    }

                    List <Type> configSectionTypes = exportedTypes.Where(type =>
                                                                         Attribute.GetCustomAttribute(type, typeof(ConfigSectionAttribute)) is not null).ToList();

                    foreach (Type t in configSectionTypes.Where(type => !type.IsSubclassOf(typeof(ConfigSectionBase)))
                             .ToArray())
                    {
                        _logger.LogWarning($"检测到错误导出的类型 {t.FullName},将会忽略加载。");
                        configSectionTypes.Remove(t);
                    }

                    foreach (Type configSectionType in configSectionTypes)
                    {
                        var configSectionAttribute =
                            Attribute.GetCustomAttribute(configSectionType, typeof(ConfigSectionAttribute))
                            as ConfigSectionAttribute;

                        ConfigSectionCollection.Add((configSectionAttribute, configSectionType));

                        _logger.LogDebug($"Config section {configSectionAttribute.Id} loaded.");
                    }

                    List <Type> formatterTypes = exportedTypes.Where(type =>
                                                                     Attribute.GetCustomAttribute(type, typeof(FormatterAttribute)) is not null).ToList();

                    foreach (Type t in formatterTypes.Where(type => !type.IsAssignableTo(typeof(IFormatter)))
                             .ToArray())
                    {
                        _logger.LogWarning($"检测到错误导出的类型 {t.FullName},将会忽略加载。");
                        formatterTypes.Remove(t);
                    }

                    foreach (Type formatterType in formatterTypes)
                    {
                        FormatterAttribute formatterAttribute =
                            Attribute.GetCustomAttribute(formatterType, typeof(FormatterAttribute))
                            as FormatterAttribute;

                        FormatterCollection.Add((formatterAttribute, formatterType));

                        _logger.LogDebug($"Formatter {formatterType.FullName} loaded.");
                    }

                    _logger.LogDebug($"Plugin {pluginMeta.Name} loaded.");
                }
                catch (Exception e)
                {
                    _logger.LogWarning(e, $"在加载插件 {file} 时发生错误。将跳过该插件的加载。");
                }
            }
        }
Пример #17
0
 public NotAllowedOperation(MethodInfo methodInfo, OperationAttribute operationAttribute)
     : base(methodInfo, operationAttribute)
 {
 }