public ConversionField(string name, InType intype, Type outtype, string dsitem, string units, double scale, double preOffset, double postOffset)
     : base(name, intype, outtype, dsitem, units)
 {
     this.scale = scale;
     this.preOffset = preOffset;
     this.postOffset = postOffset;
 }
Exemple #2
0
        public static string MangleType(InType type)
        {
            if (type.Name.Namespace != WinEventSchema.Namespace)
            {
                throw new InternalException("Cannot mangle type '{0}'.", type);
            }

            return(type.Name.LocalName switch
            {
                "UnicodeString" => "z",
                "AnsiString" => "s",
                "Int8" => "c",
                "UInt8" => "u",
                "Int16" => "l",
                "UInt16" => "h",
                "Int32" => "d",
                "UInt32" => "q",
                "Int64" => "i",
                "UInt64" => "x",
                "Float" => "f",
                "Double" => "g",
                "Boolean" => "t",
                "Binary" => "b",
                "GUID" => "j",
                "Pointer" => "p",
                "FILETIME" => "m",
                "SYSTEMTIME" => "y",
                "SID" => "k",
                "HexInt32" => "d",
                "HexInt64" => "i",
                "CountedUnicodeString" => "w",
                "CountedAnsiString" => "a",
                "CountedBinary" => "e",
                _ => throw new InternalException("cannot mangle type '{0}'", type),
            });
Exemple #3
0
 public ConversionField(string name, InType intype, Type outtype, string dsitem, string units, double scale, double preOffset, double postOffset)
     : base(name, intype, outtype, dsitem, units)
 {
     this.scale      = scale;
     this.preOffset  = preOffset;
     this.postOffset = postOffset;
 }
        /// <summary>
        /// 保存收入类型
        /// </summary>
        /// <param name="model">收入类型</param>
        /// <returns>主键ID</returns>
        public async Task <int> SaveInTypeAsync(InType model)
        {
            using (IOSysContext db = new IOSysContext())
            {
                //更新
                if (model.ID > 0)
                {
                    db.Entry(model).State = EntityState.Modified;
                }
                //新增
                else
                {
                    await db.InTypes.AddAsync(model);
                }

                await db.SaveChangesAsync();
            }

            //移除缓存
            var key = string.Format(SysConst.Cache.InTypeList_FamilyID, model.FamilyID);

            CacheHelper.Remove(key);

            return(model.ID);
        }
 protected FeedbackField(string name, InType intype, Type outtype, string dsitem, string unitString)
 {
     this.name       = name;
     this.intype     = intype;
     this.outtype    = outtype;
     this.dsitem     = dsitem;
     this.unitString = unitString;
 }
 protected FeedbackField(string name, InType intype, Type outtype, string dsitem, string unitString)
 {
     this.name = name;
     this.intype = intype;
     this.outtype = outtype;
     this.dsitem = dsitem;
     this.unitString = unitString;
 }
 public BoolField(string name, InType intype, Type outtype, string dsitem, string units)
     : base(name, intype, outtype, dsitem, units)
 {
     if (outtype != typeof(bool))
     {
         throw new ArgumentException("BoolField where out type is not a bool");
     }
 }
        public InType GetInType(byte value)
        {
            InType type = inTypeMap.FirstOrDefault(p => p.Value.Value == value).Value;

            if (type == null)
            {
                throw new InternalException("No InType with value '{0}' available.", value);
            }
            return(type);
        }
Exemple #9
0
        /// <summary>
        /// 程序集是否含有指定的特性的方法
        /// </summary>
        public static bool IsHasAttributeClassMethond <T>(this Assembly InputAssembly)
        {
            bool reVal = false;
            Func <System.Object[], bool> IsAtte = o =>
            {
                foreach (System.Attribute a in o)
                {
                    if (a is T)
                    {
                        return(true);
                    }
                }
                return(false);
            };

            try
            {
                Type[] AssemblyTypes = InputAssembly.GetExportedTypes();
                foreach (Type InType in AssemblyTypes)
                {
                    MethodInfo[] MethodInfos = InType.GetMethods();
                    foreach (MethodInfo InMethod in MethodInfos)
                    {
                        if (IsAtte(Attribute.GetCustomAttributes(InMethod)))
                        {
                            reVal = true;
                            goto IsHasAtte;
                        }
                    }
                    if (!reVal)
                    {
                        PropertyInfo[] PropertyInfos = InType.GetProperties();
                        foreach (PropertyInfo InProperty in PropertyInfos)
                        {
                            if (IsAtte(InProperty.GetCustomAttributes(true)))
                            {
                                reVal = true;
                                goto IsHasAtte;
                            }
                        }
                    }
                }

IsHasAtte:
                return(reVal);
            }
            catch (Exception ex)
            {
                ex.ToLog();
                return(false);
            }
        }
Exemple #10
0
        /// <summary>
        /// 删除收入类型
        /// </summary>
        /// <param name="model">收入类型</param>
        public async Task DeleteInTypeAsync(InType model)
        {
            using (IOSysContext db = new IOSysContext())
            {
                db.InTypes.Remove(model);
                await db.SaveChangesAsync();
            }

            //移除缓存
            var key = string.Format(SysConst.Cache.InTypeList_FamilyID, model.FamilyID);

            CacheHelper.Remove(key);
        }
Exemple #11
0
        /// <summary>
        /// 保存收入类型
        /// </summary>
        /// <param name="info">收入类型</param>
        /// <returns>主键ID</returns>
        public async Task <ResultInfo <int> > SaveInTypeAsync(InTypeInfo info)
        {
            //获取原有列表
            var list = await BasicDAL.Inst.QueryInTypeAsync(this.LoginInfo.FamilyID);

            //判断名称是否已被使用
            if (list.Exists(m => m.ID != info.ID && m.Name == info.Name))
            {
                return(new ResultInfo <int>(false, this.Res.Bas.NameExisted, -1));
            }

            //判断默认账户是否存在
            var modelAmountAccount = await BasicDAL.Inst.GetAmountAccountAsync(this.LoginInfo.FamilyID, info.AmountAccountID);

            if (modelAmountAccount == null)
            {
                return(new ResultInfo <int>(false, this.Res.Bas.AmountAccountUnexist, -1));
            }

            //尝试查找原数据
            var model = list.Find(m => m.ID == info.ID);

            //新建
            if (model == null)
            {
                model          = new InType();
                model.FamilyID = this.LoginInfo.FamilyID;
            }

            model.Name            = info.Name;
            model.AmountAccountID = info.AmountAccountID;
            model.IsActive        = info.IsActive;
            model.Remark          = info.Remark;

            //设置创建者/更新者字段值
            this.SetCreateUpdateFields(model);

            //保存到数据库
            await BasicDAL.Inst.SaveInTypeAsync(model);

            return(new ResultInfo <int>(true, Res.Gen.OK, model.ID));
        }
Exemple #12
0
        public static List <T> GetAttributeList <T>(this Assembly InputAssembly) where T : Attribute
        {
            List <T> reVal = new List <T>();

            Type[] AssemblyTypes = InputAssembly.GetExportedTypes();

            foreach (Type InType in AssemblyTypes)
            {
                foreach (MethodInfo InMethod in InType.GetMethods())
                {
                    foreach (Attribute InAttribute in Attribute.GetCustomAttributes(InMethod))
                    {
                        if (InAttribute is T)
                        {
                            reVal.Add((T)InAttribute);
                        }
                    }
                }
            }

            return(reVal);
        }
Exemple #13
0
        private FeedbackField HandleField(XmlReader reader)
        {
            string name        = reader.GetAttribute("name");
            string intype_str  = reader.GetAttribute("intype");
            string outtype_str = reader.GetAttribute("outtype");
            string dsitem      = reader.GetAttribute("dsitem");
            string units       = reader.GetAttribute("units");

            // figure out the in type
            InType intype  = (InType)Enum.Parse(typeof(InType), intype_str.ToUpper(), false);
            Type   outtype = MapType(outtype_str);

            if (!reader.Read())
            {
                throw new InvalidOperationException();
            }

            if (reader.NodeType != XmlNodeType.Element)
            {
                throw new InvalidOperationException();
            }

            FeedbackField field = null;

            string elementName = reader.LocalName;

            if (elementName == "raw")
            {
                field = new RawField(name, intype, outtype, dsitem, units);
            }
            else if (elementName == "bool")
            {
                field = new BoolField(name, intype, outtype, dsitem, units);
            }
            else if (elementName == "conversion")
            {
                double scale = 0, preOffset = 0, postOffset = 0;
                HandleConversion(reader, ref scale, ref preOffset, ref postOffset);
                field = new ConversionField(name, intype, outtype, dsitem, units, scale, preOffset, postOffset);
            }
            else if (elementName == "enum")
            {
                Dictionary <int, object> map = new Dictionary <int, object>();
                object defVal = null;
                if (!outtype.IsEnum)
                {
                    throw new InvalidOperationException("Error in field " + name + ": outtype is not an enum");
                }
                HandleEnumMap(reader, outtype, ref map, ref defVal);
                field = new EnumField(name, intype, outtype, dsitem, units, map, defVal);
            }
            else if (elementName == "intMap")
            {
                Dictionary <int, int> map = new Dictionary <int, int>();
                int defVal = 0;
                // should check if out type is valid
                HandleIntMap(reader, ref map, ref defVal);
                field = new IntField(name, intype, outtype, dsitem, units, map, defVal);
            }
            else if (elementName == "bitmap")
            {
                string[] fields;
                HandleBitmap(reader, out fields);
                field = new BitmapField(name, intype, outtype, dsitem, units, fields);
            }
            else
            {
                throw new InvalidOperationException();
            }

            reader.Read();
            if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "field")
            {
                throw new InvalidOperationException();
            }

            return(field);
        }
 public void AddInType(InType inType)
 {
     inTypeMap.Add(inType.Name, inType);
     InTypes.Add(inType);
 }
 public BoolField(string name, InType intype, Type outtype, string dsitem, string units)
     : base(name, intype, outtype, dsitem, units)
 {
     if (outtype != typeof(bool))
         throw new ArgumentException("BoolField where out type is not a bool");
 }
 public RawField(string name, InType intype, Type outtype, string dsitem, string units)
     : base(name, intype, outtype, dsitem, units)
 {
 }
Exemple #17
0
        private ParameterBase GetParameter(TypeFormat typeFormat, ParameterInfo parameter,
                                           SwaggerWcfParameterAttribute settings, string uriTemplate,
                                           IList <Type> definitionsTypesList)
        {
            string description = settings != null ? settings.Description : null;
            bool   required    = settings != null && settings.Required;
            string name        = parameter.Name;
            DataMemberAttribute dataMemberAttribute = parameter.GetCustomAttribute <DataMemberAttribute>();

            if (dataMemberAttribute != null && !string.IsNullOrEmpty(dataMemberAttribute.Name))
            {
                name = dataMemberAttribute.Name;
            }

            InType inType = GetInType(uriTemplate, parameter.Name);

            if (inType == InType.Path)
            {
                required = true;
            }

            if (!required && !parameter.HasDefaultValue)
            {
                required = true;
            }

            Type paramType = settings == null || settings.ParameterType == null
                ? parameter.ParameterType
                : settings.ParameterType;

            if (paramType.IsGenericType && paramType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                required  = false;
                paramType = paramType.GenericTypeArguments[0];
            }

            if (typeFormat.Type == ParameterType.Object)
            {
                return(new ParameterSchema
                {
                    Name = name,
                    Description = description,
                    In = inType,
                    Required = required,
                    SchemaRef = typeFormat.Format
                });
            }

            if (inType == InType.Body)
            {
                if (typeFormat.Type == ParameterType.Array)
                {
                    Type t = paramType.GetElementType() ?? GetEnumerableType(paramType);
                    ParameterPrimitive arrayParam = new ParameterPrimitive
                    {
                        Name        = name,
                        Description = description,
                        In          = inType,
                        Required    = required,
                        TypeFormat  = typeFormat,
                        Items       = new ParameterItems
                        {
                            Items = new ParameterSchema
                            {
                                SchemaRef = t.FullName
                            }
                        },
                        CollectionFormat = CollectionFormat.Csv
                    };

                    //it's a complex type, so we'll need to map it later
                    if (definitionsTypesList != null && !definitionsTypesList.Contains(t))
                    {
                        definitionsTypesList.Add(t);
                    }

                    return(arrayParam);
                }
                if (typeFormat.IsPrimitiveType)
                {
                    ParameterPrimitive paramPrimitive = new ParameterPrimitive
                    {
                        Name        = name,
                        Description = description,
                        In          = inType,
                        Required    = required,
                        TypeFormat  = typeFormat
                    };
                    return(paramPrimitive);
                }

                //it's a complex type, so we'll need to map it later
                if (definitionsTypesList != null && !definitionsTypesList.Contains(paramType))
                {
                    definitionsTypesList.Add(paramType);
                }
                typeFormat = new TypeFormat(ParameterType.Object,
                                            HttpUtility.HtmlEncode(paramType.FullName));

                return(new ParameterSchema
                {
                    Name = name,
                    Description = description,
                    In = inType,
                    Required = required,
                    SchemaRef = typeFormat.Format
                });
            }

            ParameterPrimitive param = new ParameterPrimitive
            {
                Name        = name,
                Description = description,
                In          = inType,
                Required    = required,
                TypeFormat  = typeFormat
            };

            return(param);
        }
Exemple #18
0
        private ParameterBase GetParameter(TypeFormat typeFormat, ParameterInfo parameter,
                                           SwaggerWcfParameterAttribute settings, string uriTemplate,
                                           IList <Type> definitionsTypesList)
        {
            string description = settings != null ? settings.Description : null;
            bool   required    = settings != null && settings.Required;
            string name        = parameter.Name;

            //Check for set DataContractAttribute to set Name and - Should this check for, and set DataContractAttribute.Namespace as well? /GustafRG
            //DataContractAttribute was not accessible on parameter, but on parameter.ParameterType. /GustafRG
            DataContractAttribute dataContractAttribute = parameter.ParameterType.GetCustomAttribute <DataContractAttribute>();

            if (dataContractAttribute != null)
            {
                if (!string.IsNullOrEmpty(dataContractAttribute.Name))
                {
                    name = dataContractAttribute.Name;
                }
                else
                {
                    name = parameter.ParameterType.Name;
                }
            }

            //Removed this. DataMemberAttribute is not valid on Object, Only on Object Members. Also, it does not seem to be accessible on "parameter" /GustafRG
            //DataMemberAttribute dataMemberAttribute = parameter.ParameterType.GetCustomAttribute<DataMemberAttribute>();

            //         if (dataMemberAttribute != null && !string.IsNullOrEmpty(dataMemberAttribute.Name))
            //             name = dataMemberAttribute.Name;

            InType inType = GetInType(uriTemplate, parameter.Name);

            if (inType == InType.Path)
            {
                required = true;
            }

            if (!required && !parameter.HasDefaultValue)
            {
                required = true;
            }

            Type paramType = parameter.ParameterType;

            if (paramType.IsGenericType && paramType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                required  = false;
                paramType = paramType.GenericTypeArguments[0];
            }

            if (typeFormat.Type == ParameterType.Object)
            {
                return(new ParameterSchema
                {
                    Name = name,
                    Description = description,
                    In = inType,
                    Required = required,
                    SchemaRef = typeFormat.Format
                });
            }

            if (inType == InType.Body)
            {
                if (typeFormat.Type == ParameterType.Array)
                {
                    Type t = paramType.GetElementType() ?? GetEnumerableType(paramType);
                    ParameterPrimitive arrayParam = new ParameterPrimitive
                    {
                        Name        = name,
                        Description = description,
                        In          = inType,
                        Required    = required,
                        TypeFormat  = typeFormat,
                        Items       = new ParameterItems
                        {
                            Items = new ParameterSchema
                            {
                                SchemaRef = t.FullName
                            }
                        },
                        CollectionFormat = CollectionFormat.Csv
                    };

                    //it's a complex type, so we'll need to map it later
                    if (definitionsTypesList != null && !definitionsTypesList.Contains(t))
                    {
                        definitionsTypesList.Add(t);
                    }

                    return(arrayParam);
                }

                //it's a complex type, so we'll need to map it later
                if (definitionsTypesList != null && !definitionsTypesList.Contains(paramType))
                {
                    definitionsTypesList.Add(paramType);
                }
                typeFormat = new TypeFormat(ParameterType.Object,
                                            HttpUtility.HtmlEncode(paramType.FullName));

                return(new ParameterSchema
                {
                    Name = name,
                    Description = description,
                    In = inType,
                    Required = required,
                    SchemaRef = typeFormat.Format
                });
            }

            ParameterPrimitive param = new ParameterPrimitive
            {
                Name        = name,
                Description = description,
                In          = inType,
                Required    = required,
                TypeFormat  = typeFormat
            };

            return(param);
        }
 public IntField(string name, InType intype, Type outtype, string dsitem, string units, Dictionary<int, int> map, int defaultValue)
     : base(name, intype, outtype, dsitem, units)
 {
     this.map = map;
     this.defaultValue = Convert.ChangeType(defaultValue, outtype);
 }
Exemple #20
0
 public IntField(string name, InType intype, Type outtype, string dsitem, string units, Dictionary <int, int> map, int defaultValue)
     : base(name, intype, outtype, dsitem, units)
 {
     this.map          = map;
     this.defaultValue = Convert.ChangeType(defaultValue, outtype);
 }
        public BitmapField(string name, InType intype, Type outtype, string dsitem, string units, string[] fields)
            : base(name, intype, outtype, dsitem, units)
        {
            this.fields = fields;

            // get the type size
            int typeSize = 0;
            switch (intype) {
                case InType.U8:
                case InType.S8:
                    typeSize = 8;
                    break;

                case InType.U16:
                case InType.S16:
                    typeSize = 16;
                    break;

                case InType.U32:
                case InType.S32:
                    typeSize = 32;
                    break;

                default:
                    typeSize = -1;
                    break;
            }

            if (fields.Length > typeSize) {
                throw new InvalidOperationException("more fields specified than the number of bits for " + name);
            }

            if (outtype == typeof(bool[])) {
                boolArray = true;
            }
            else if (outtype == typeof(BitArray)) {
                bitArray = true;
            }
            else {
                // find a default constructor
                ctor = outtype.GetConstructor(Type.EmptyTypes);

                if (ctor == null) {
                    throw new InvalidOperationException("no default constructor for type " + outtype.Name);
                }

                fieldHandles = new FieldInfo[fields.Length];
                for (int i = 0; i < fields.Length; i++) {
                    if (!string.IsNullOrEmpty(fields[i])) {
                        fieldHandles[i] = outtype.GetField(fields[i]);

                        if (fieldHandles[i] == null) {
                            throw new InvalidOperationException("could not find field " + fields[i] + " on type " + outtype.Name);
                        }
                        else if (fieldHandles[i].FieldType != typeof(bool)) {
                            throw new InvalidOperationException("field " + fields[i] + " is not a bool");
                        }
                        else if (fieldHandles[i].IsInitOnly || fieldHandles[i].IsLiteral || fieldHandles[i].IsStatic) {
                            throw new InvalidOperationException("field " + fields[i] + " is read only or static");
                        }
                    }
                }
            }
        }
 public EnumField(string name, InType intype, Type outtype, string dsitem, string units, Dictionary<int, object> map, object defaultValue)
     : base(name, intype, outtype, dsitem, units)
 {
     this.map = map;
     this.defaultValue = defaultValue;
 }
        public BitmapField(string name, InType intype, Type outtype, string dsitem, string units, string[] fields)
            : base(name, intype, outtype, dsitem, units)
        {
            this.fields = fields;

            // get the type size
            int typeSize = 0;

            switch (intype)
            {
            case InType.U8:
            case InType.S8:
                typeSize = 8;
                break;

            case InType.U16:
            case InType.S16:
                typeSize = 16;
                break;

            case InType.U32:
            case InType.S32:
                typeSize = 32;
                break;

            default:
                typeSize = -1;
                break;
            }

            if (fields.Length > typeSize)
            {
                throw new InvalidOperationException("more fields specified than the number of bits for " + name);
            }

            if (outtype == typeof(bool[]))
            {
                boolArray = true;
            }
            else if (outtype == typeof(BitArray))
            {
                bitArray = true;
            }
            else
            {
                // find a default constructor
                ctor = outtype.GetConstructor(Type.EmptyTypes);

                if (ctor == null)
                {
                    throw new InvalidOperationException("no default constructor for type " + outtype.Name);
                }

                fieldHandles = new FieldInfo[fields.Length];
                for (int i = 0; i < fields.Length; i++)
                {
                    if (!string.IsNullOrEmpty(fields[i]))
                    {
                        fieldHandles[i] = outtype.GetField(fields[i]);

                        if (fieldHandles[i] == null)
                        {
                            throw new InvalidOperationException("could not find field " + fields[i] + " on type " + outtype.Name);
                        }
                        else if (fieldHandles[i].FieldType != typeof(bool))
                        {
                            throw new InvalidOperationException("field " + fields[i] + " is not a bool");
                        }
                        else if (fieldHandles[i].IsInitOnly || fieldHandles[i].IsLiteral || fieldHandles[i].IsStatic)
                        {
                            throw new InvalidOperationException("field " + fields[i] + " is read only or static");
                        }
                    }
                }
            }
        }
Exemple #24
0
        internal IEnumerable <Tuple <string, PathAction> > GetActions(MethodInfo[] targetMethods,
                                                                      MethodInfo[] interfaceMethods,
                                                                      IList <Type> definitionsTypesList)
        {
            int methodsCounts = interfaceMethods.Length;

            for (int index = 0; index < methodsCounts; index++)
            {
                MethodInfo implementation = targetMethods[index];
                MethodInfo declaration    = interfaceMethods[index];

                //if a tag from either implementation or declaration is marked as not visible, skip it
                List <SwaggerWcfTagAttribute> methodTags =
                    implementation.GetCustomAttributes <SwaggerWcfTagAttribute>().ToList();
                methodTags =
                    methodTags.Concat(declaration.GetCustomAttributes <SwaggerWcfTagAttribute>()).ToList();

                methodTags = methodTags.Distinct().ToList();

                // If no tags on the method - check declared Type/Interface itself
                if (methodTags.Count < 1)
                {
                    methodTags = implementation.DeclaringType.GetCustomAttributes <SwaggerWcfTagAttribute>()
                                 .Concat(declaration.DeclaringType.GetCustomAttributes <SwaggerWcfTagAttribute>())
                                 .ToList();
                }

                if ((methodTags.Count == 0 && HiddenTags.Contains("default")) ||
                    methodTags.Any(t => HiddenTags.Contains(t.TagName)))
                {
                    continue;
                }

                //if the method is marked Hidden anywhere, skip it (even if methods tags listed as visible).
                if ((implementation.GetCustomAttribute <SwaggerWcfHiddenAttribute>() != null ||
                     declaration.GetCustomAttribute <SwaggerWcfHiddenAttribute>() != null)
                    )
                {
                    continue;
                }

                //find the WebGet/Invoke attributes, or skip if neither is present
                WebGetAttribute    wg = declaration.GetCustomAttribute <WebGetAttribute>();
                WebInvokeAttribute wi = declaration.GetCustomAttribute <WebInvokeAttribute>();
                if (wg == null && wi == null)
                {
                    continue;
                }

                string httpMethod  = (wi == null) ? "GET" : wi.Method ?? "POST";
                string uriTemplate = GetUriTemplate(wi, wg, declaration);

                bool wrappedRequest  = IsRequestWrapped(wg, wi);
                bool wrappedResponse = IsResponseWrapped(wg, wi);

                var wcfPathAttribute = (implementation.GetCustomAttribute(typeof(SwaggerWcfPathAttribute), false) as SwaggerWcfPathAttribute)
                                       ?? (declaration.GetCustomAttribute(typeof(SwaggerWcfPathAttribute), false) as SwaggerWcfPathAttribute);
                int sortOrder = (wcfPathAttribute?.SortOrder).GetValueOrDefault();


                //implementation description overrides interface description
                string description =
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(implementation, "Description") ??
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(declaration, "Description") ??
                    Helpers.GetCustomAttributeValue <string, DescriptionAttribute>(implementation, "Description") ??
                    Helpers.GetCustomAttributeValue <string, DescriptionAttribute>(declaration, "Description") ??
                    "";

                string summary =
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(implementation, "Summary") ??
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(declaration, "Summary") ??
                    "";

                string operationId =
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(implementation, "OperationId") ??
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(declaration, "OperationId") ??
                    "";
                if (operationId == "")
                {
                    if (implementation.DeclaringType != null)
                    {
                        operationId = implementation.DeclaringType.FullName + ".";
                    }
                    operationId += implementation.Name;
                }

                string externalDocsDescription =
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(implementation,
                                                                                      "ExternalDocsDescription") ??
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(declaration,
                                                                                      "ExternalDocsDescription") ??
                    "";

                string externalDocsUrl =
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(implementation, "ExternalDocsUrl") ??
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(declaration, "ExternalDocsUrl") ??
                    "";

                ExternalDocumentation externalDocs = null;
                if (!string.IsNullOrWhiteSpace(externalDocsDescription) || !string.IsNullOrWhiteSpace(externalDocsUrl))
                {
                    externalDocs = new ExternalDocumentation
                    {
                        Description = externalDocsDescription,
                        Url         = HttpUtility.HtmlEncode(externalDocsUrl)
                    };
                }

                bool deprecated =
                    Helpers.GetCustomAttributeValue <SwaggerWcfPathAttribute>(implementation, "Deprecated");
                if (!deprecated)
                {
                    deprecated = Helpers.GetCustomAttributeValue <SwaggerWcfPathAttribute>(declaration, "Deprecated");
                }

                string operationPath =
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(implementation, "OperationPath") ??
                    Helpers.GetCustomAttributeValue <string, SwaggerWcfPathAttribute>(declaration, "OperationPath");
                if (!string.IsNullOrWhiteSpace(operationPath))
                {
                    uriTemplate = ConcatPaths(operationPath, uriTemplate);
                }

                PathAction operation = new PathAction
                {
                    Id          = httpMethod.ToLowerInvariant(),
                    SortOrder   = sortOrder,
                    Summary     = summary,
                    Description = description,
                    Tags        =
                        methodTags.Where(t => !t.HideFromSpec).Select(t => HttpUtility.HtmlEncode(t.TagName)).ToList(),
                    Consumes     = new List <string>(GetConsumes(implementation, declaration)),
                    Produces     = new List <string>(GetProduces(implementation, declaration)),
                    Deprecated   = deprecated,
                    OperationId  = HttpUtility.HtmlEncode(operationId),
                    ExternalDocs = externalDocs,
                    Responses    = GetResponseCodes(implementation, declaration, wrappedResponse, definitionsTypesList),
                    Security     = GetMethodSecurity(implementation, declaration)
                                   // Schemes = TODO: how to get available schemes for this WCF service? (schemes: http/https)
                };

                //try to map each implementation parameter to the uriTemplate.
                ParameterInfo[] parameters = declaration.GetParameters();
                if (parameters.Any())
                {
                    operation.Parameters = new List <ParameterBase>();
                }

                List <SwaggerWcfHeaderAttribute> headers =
                    implementation.GetCustomAttributes <SwaggerWcfHeaderAttribute>().ToList();
                headers = headers.Concat(declaration.GetCustomAttributes <SwaggerWcfHeaderAttribute>()).ToList();

                // remove duplicates
                headers = headers.GroupBy(h => h.Name).Select(g => g.First()).ToList();

                // parameters - headers
                foreach (SwaggerWcfHeaderAttribute attr in headers)
                {
                    operation.Parameters.Add(new ParameterPrimitive
                    {
                        Name        = attr.Name,
                        Description = attr.Description,
                        Default     = attr.DefaultValue,
                        In          = InType.Header,
                        Required    = attr.Required,
                        TypeFormat  = new TypeFormat(ParameterType.String, null)
                    });
                }

                bool        isGetRequest       = httpMethod == "GET";
                int         bodyParameterCount = parameters.Where(p => GetInType(uriTemplate, p.Name) == InType.Body).Count();
                TypeBuilder typeBuilder        = null;
                if (!wrappedRequest && !isGetRequest && bodyParameterCount > 1)
                {
                    wrappedRequest = true;
                }
                if (wrappedRequest)
                {
                    typeBuilder = new TypeBuilder(implementation.GetWrappedName(declaration));
                }

                var declarationName = declaration.Name;
                foreach (ParameterInfo parameter in parameters)
                {
                    SwaggerWcfParameterAttribute settings =
                        implementation.GetParameters()
                        .First(p => p.Position.Equals(parameter.Position))
                        .GetCustomAttribute <SwaggerWcfParameterAttribute>() ??
                        parameter.GetCustomAttribute <SwaggerWcfParameterAttribute>();

                    if (implementation.GetParameters()
                        .First(p => p.Position.Equals(parameter.Position))
                        .GetCustomAttribute <SwaggerWcfHiddenAttribute>() != null ||
                        parameter.GetCustomAttribute <SwaggerWcfHiddenAttribute>() != null)
                    {
                        continue;
                    }

                    List <SwaggerWcfTagAttribute> piTags =
                        methodTags.Concat(parameter.GetCustomAttributes <SwaggerWcfTagAttribute>())
                        .ToList();

                    InType inType = GetInType(uriTemplate, parameter.Name);

                    if (inType == InType.Body && wrappedRequest)
                    {
                        bool required = settings != null && settings.Required;

                        if (!required && !parameter.HasDefaultValue)
                        {
                            required = true;
                        }

                        typeBuilder.AddField(parameter.Name, parameter.ParameterType, required);

                        continue;
                    }

                    if (piTags.Any(t => HiddenTags.Contains(t.TagName)))
                    {
                        continue;
                    }

                    Type type = settings == null || settings.ParameterType == null
                        ? parameter.ParameterType
                        : settings.ParameterType;

                    TypeFormat typeFormat = Helpers.MapSwaggerType(type, definitionsTypesList);

                    operation.Parameters.Add(GetParameter(typeFormat, declaration, implementation, parameter, settings, uriTemplate, wrappedRequest,
                                                          definitionsTypesList, inType));
                }

                if (wrappedRequest)
                {
                    TypeFormat typeFormat = Helpers.MapSwaggerType(typeBuilder.Type, definitionsTypesList);

                    operation.Parameters.Add(new ParameterSchema
                    {
                        Name      = implementation.GetWrappedName(declaration) + "Wrapper",
                        In        = InType.Body,
                        Required  = true,
                        SchemaRef = typeFormat.Format
                    });
                }

                if (!string.IsNullOrWhiteSpace(uriTemplate))
                {
                    int indexOfQuestionMark = uriTemplate.IndexOf('?');
                    if (indexOfQuestionMark >= 0)
                    {
                        uriTemplate = uriTemplate.Substring(0, indexOfQuestionMark);
                    }

                    uriTemplate = RemoveParametersDefaultValuesFromUri(uriTemplate);
                }

                yield return(new Tuple <string, PathAction>(uriTemplate, operation));
            }
        }
Exemple #25
0
 public EnumField(string name, InType intype, Type outtype, string dsitem, string units, Dictionary <int, object> map, object defaultValue)
     : base(name, intype, outtype, dsitem, units)
 {
     this.map          = map;
     this.defaultValue = defaultValue;
 }
 public RawField(string name, InType intype, Type outtype, string dsitem, string units)
     : base(name, intype, outtype, dsitem, units)
 {
 }
Exemple #27
0
        private ParameterBase GetParameter(TypeFormat typeFormat,
                                           MethodInfo declaration,
                                           MethodInfo implementation,
                                           ParameterInfo parameter,
                                           SwaggerWcfParameterAttribute settings,
                                           string uriTemplate,
                                           bool wrappedRequest,
                                           IList <Type> definitionsTypesList,
                                           InType inType)
        {
            string description = settings?.Description;
            bool   required    = settings != null && settings.Required;
            string name        = inType == InType.Query ? ResolveParameterNameFromUri(uriTemplate, parameter) : parameter.Name;

            if (inType == InType.Path)
            {
                required = true;
            }

            if (!required && !parameter.HasDefaultValue)
            {
                required = true;
            }

            Type paramType = settings == null || settings.ParameterType == null
                ? parameter.ParameterType
                : settings.ParameterType;

            if (paramType.IsGenericType && paramType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                required  = false;
                paramType = paramType.GenericTypeArguments[0];
            }

            if (typeFormat.Type == ParameterType.Object)
            {
                return(new ParameterSchema
                {
                    Name = name,
                    Description = description,
                    In = inType,
                    Required = required,
                    SchemaRef = typeFormat.Format
                });
            }

            if (inType == InType.Body)
            {
                if (typeFormat.Type == ParameterType.Array)
                {
                    Type       t             = paramType.GetElementType() ?? GetEnumerableType(paramType);
                    TypeFormat subTypeFormat = Helpers.MapSwaggerType(t);

                    ParameterItems items;

                    if (subTypeFormat.IsPrimitiveType || subTypeFormat.IsEnum)
                    {
                        items = new ParameterItems
                        {
                            TypeFormat = subTypeFormat
                        };
                    }
                    else
                    {
                        items = new ParameterItems
                        {
                            Items = new ParameterSchema
                            {
                                SchemaRef = t.GetModelName()
                            }
                        };
                    }

                    ParameterPrimitive arrayParam = new ParameterPrimitive
                    {
                        Name             = name,
                        Description      = description,
                        In               = inType,
                        Required         = required,
                        TypeFormat       = typeFormat,
                        Items            = items,
                        CollectionFormat = CollectionFormat.Csv
                    };

                    //it's a complex type, so we'll need to map it later
                    if (definitionsTypesList != null && !definitionsTypesList.Contains(t))
                    {
                        definitionsTypesList.Add(t);
                    }

                    return(arrayParam);
                }
                if (typeFormat.IsPrimitiveType || typeFormat.IsEnum)
                {
                    bool isGetRequest = implementation.GetCustomAttributes <WebGetAttribute>().Any() ||
                                        declaration.GetCustomAttributes <WebGetAttribute>().Any();
                    if (!isGetRequest)
                    {
                        WebInvokeAttribute webInvoke = implementation.GetCustomAttribute <WebInvokeAttribute>()
                                                       ?? declaration.GetCustomAttribute <WebInvokeAttribute>();
                        if (webInvoke != null && webInvoke.Method == "GET")
                        {
                            isGetRequest = true;
                        }
                    }
                    if (!wrappedRequest && isGetRequest)
                    {
                        ParameterPrimitive paramPrimitive = new ParameterPrimitive
                        {
                            Name        = name,
                            Description = description,
                            In          = InType.Query,
                            Required    = required,
                            TypeFormat  = typeFormat
                        };
                        return(paramPrimitive);
                    }
                    else
                    {
                        ParameterPrimitive paramPrimitive = new ParameterPrimitive
                        {
                            Name        = name,
                            Description = description,
                            In          = inType,
                            Required    = required,
                            TypeFormat  = typeFormat
                        };
                        return(paramPrimitive);
                    }
                }

                //it's a complex type, so we'll need to map it later
                if (definitionsTypesList != null && !definitionsTypesList.Contains(paramType))
                {
                    definitionsTypesList.Add(paramType);
                }

                typeFormat = new TypeFormat(ParameterType.Object,
                                            HttpUtility.HtmlEncode(paramType.GetModelName()));

                return(new ParameterSchema
                {
                    Name = name,
                    Description = description,
                    In = inType,
                    Required = required,
                    SchemaRef = typeFormat.Format
                });
            }

            ParameterPrimitive param = new ParameterPrimitive
            {
                Name        = name,
                Description = description,
                In          = inType,
                Required    = required,
                TypeFormat  = typeFormat
            };

            return(param);
        }
Exemple #28
0
 public DataProperty(LocatedRef <string> name, InType inType)
     : base(name)
 {
     InType = inType ?? throw new ArgumentNullException(nameof(inType));
 }