Example #1
0
 public InteropManager(CompilerEnvironment env)
 {
     this.env = env;
     rootEnv = env.Global.Environment();
     attributeHelper = env.AttributeHelper;
     typeRepresentationCache = new Map<CST.QualifiedTypeName, TypeRepresentation>();
 }
        public void Intercept(IInvocation invocation)
        {
            var attributeHelper = new AttributeHelper();
            var methodHaveUnitOfWorkAttribute = attributeHelper.MethodDefinedAttribute<UnitOfWorkAttribute>(invocation);

            if (!methodHaveUnitOfWorkAttribute)
            {
                invocation.Proceed();
                return;
            }

            _unitOfWork.BeginTransaction();
            invocation.Proceed();
            _unitOfWork.Commit();
        }
        public static string GetContractReference(Type type)
        {
            var attribs = type.GetCustomAttributes(false);
            var helper = new AttributeHelper(attribs);

            var name = Maybe.String
                .GetValue(() => helper.GetString<ProtoContractAttribute>(p => p.Name))
                .GetValue(() => helper.GetString<DataContractAttribute>(p => p.Name))
                .GetValue(() => helper.GetString<XmlTypeAttribute>(p => p.TypeName))
                .GetValue(() => type.Name);

            var ns = Maybe.String
                .GetValue(() => helper.GetString<DataContractAttribute>(p => p.Namespace))
                .GetValue(() => helper.GetString<XmlTypeAttribute>(p => p.Namespace))
                .Convert(s => s.Trim() + "/", "");

            return ns + name;
        }
Example #4
0
        public static string GetContractReference(Type type)
        {
            var attribs = type.GetCustomAttributes(false);
            var helper = new AttributeHelper(attribs);

            var s1 = Optional<string>.Empty;
            var name = s1
                .Combine(() => helper.GetString("ProtoContractAttribute","Name"))
                .Combine(() => helper.GetString("DataContractAttribute", "Name"))
                .Combine(() => helper.GetString("XmlTypeAttribute", "TypeName"))
                .GetValue(type.Name);

            var ns = s1
                .Combine(() => helper.GetString("DataContractAttribute", "Namespace"))
                .Combine(() => helper.GetString("XmlTypeAttribute", "Namespace"))
                .Convert(s => s.Trim() + "/", "");

            ns = AppendNesting(ns, type);

            return ns + name;
        }
Example #5
0
        public static IEnumerable<CompletionPort> ReadBytesAsync(AsyncMachine<byte[]> machine, Stream stream, int length)
        {
            var attributeHelper = new AttributeHelper<VhdHeader>();
            var buffer = new byte[length];

            int readCount = 0;
            int remaining = length;
            while (remaining > 0)
            {
                stream.BeginRead(buffer, readCount, remaining, machine.CompletionCallback, null);
                yield return CompletionPort.SingleOperation;
                var currentRead = stream.EndRead(machine.CompletionResult);
                if (currentRead == 0)
                {
                    break;
                }
                readCount += currentRead;
                remaining -= currentRead;
            }
            machine.ParameterValue = buffer;
            yield break;
        }
        public IEnumerable<IConfigurationOptions> ParseXml(string contentsOfConfigFile)
        {
            if (String.IsNullOrEmpty(contentsOfConfigFile))
                throw new ArgumentException("contentsOfConfigFile is null or empty.", "contentsOfConfigFile");

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(contentsOfConfigFile);
            XmlNodeList configNodes = doc.DocumentElement.SelectNodes("//config");
            var result = new List<IConfigurationOptions>();
            foreach (XmlNode configNode in configNodes)
            {
                IConfigurationOptions options = new DefaultConfigurationOptions();
                var attrib = new AttributeHelper(".//add[@key='{0}']/@value", configNode);
                options.AssemblyDirectory = attrib.Get("assemblydirectory");
                options.AbstractBaseName = attrib.Get("abstractbasename");
                options.BaseTypeName = attrib.Get("basetypename");
                options.ConnectionString = attrib.Get("connectionstring");
                options.DataNamespace = attrib.Get("datanamespace");
                options.IocVerboseLogging = attrib.GetBool("iocverboselogging", false);
                options.GenerateColumnList = attrib.GetBool("generatecolumnlist", true);
                options.GenerateComments = attrib.GetBool("generatecomments", true);
                options.UseMicrosoftsHeader = attrib.GetBool("usemicrosoftsheader", false);
                options.Namespace = attrib.Get("namespace");
                options.OutputPath = attrib.Get("outputpath");
                options.EnumOutputPath = attrib.Get("enumoutputpath");
                options.EnumNamespace = attrib.Get("enumnamespace");
                options.StaticPrimaryKeyName = attrib.Get("staticprimarykeyname");
                options.OnlyTablesWithPrefix.AddRange(attrib.Get("onlytableswithprefix").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
                options.SkipTablesWithPrefix.AddRange(attrib.Get("skiptableswithprefix").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
                options.SkipTables.AddRange(attrib.Get("skiptables").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
                options.Enums = ParseEnums(configNode);
                LoadEnumReplacements(configNode, options);
                options.Components = ParseComponents(configNode);
                result.Add(options);
            }
            return result;
        }
 public CoreFramework(string orgCode)
 {
     OrgCode        = orgCode;
     columnAttrList = AttributeHelper.GetEntityColumnAtrributes <TEntity>();
 }
Example #8
0
        public virtual void CheckObjectLiteral(TypeDefinition type, ITranslator translator)
        {
            if (!this.IsObjectLiteral(type))
            {
                return;
            }

            var objectCreateMode = this.GetObjectCreateMode(type);

            if (objectCreateMode == 0)
            {
                var ctors = type.GetConstructors();

                foreach (var ctor in ctors)
                {
                    foreach (var parameter in ctor.Parameters)
                    {
                        if (parameter.ParameterType.FullName == "Bridge.ObjectCreateMode")
                        {
                            TranslatorException.Throw(Constants.Messages.Exceptions.OBJECT_LITERAL_PLAIN_NO_CREATE_MODE_CUSTOM_CONSTRUCTOR, type);
                        }

                        if (parameter.ParameterType.FullName == "Bridge.ObjectInitializationMode")
                        {
                            continue;
                        }

                        TranslatorException.Throw(Constants.Messages.Exceptions.OBJECT_LITERAL_PLAIN_CUSTOM_CONSTRUCTOR, type);
                    }
                }
            }

            if (type.IsInterface)
            {
                if (type.HasMethods && type.Methods.GroupBy(m => m.Name).Any(g => g.Count() > 1))
                {
                    TranslatorException.Throw(Constants.Messages.Exceptions.OBJECT_LITERAL_INTERFACE_NO_OVERLOAD_METHODS, type);
                }

                if (type.HasEvents)
                {
                    TranslatorException.Throw(Constants.Messages.Exceptions.OBJECT_LITERAL_INTERFACE_NO_EVENTS, type);
                }
            }
            else
            {
                if (type.Methods.Any(m => !m.IsRuntimeSpecialName && m.Name.Contains(".") && !m.Name.Contains("<")) ||
                    type.Properties.Any(m => !m.IsRuntimeSpecialName && m.Name.Contains(".") && !m.Name.Contains("<")))
                {
                    TranslatorException.Throw(Constants.Messages.Exceptions.OBJECT_LITERAL_INTERFACE_NO_EXPLICIT_IMPLEMENTATION, type);
                }
            }

            if (type.BaseType != null)
            {
                TypeDefinition baseType = null;
                try
                {
                    baseType = type.BaseType.Resolve();
                }
                catch (Exception)
                {
                }

                if (objectCreateMode == 1 && baseType != null && baseType.FullName != "System.Object" && baseType.FullName != "System.ValueType" && this.GetObjectCreateMode(baseType) == 0)
                {
                    TranslatorException.Throw(Constants.Messages.Exceptions.OBJECT_LITERAL_CONSTRUCTOR_INHERITANCE, type);
                }

                if (objectCreateMode == 0 && baseType != null && this.GetObjectCreateMode(baseType) == 1)
                {
                    TranslatorException.Throw(Constants.Messages.Exceptions.OBJECT_LITERAL_PLAIN_INHERITANCE, type);
                }
            }

            if (type.Interfaces.Count > 0)
            {
                foreach (var @interface in type.Interfaces)
                {
                    TypeDefinition iDef = null;
                    try
                    {
                        iDef = @interface.Resolve();
                    }
                    catch (Exception)
                    {
                    }

                    if (iDef != null && iDef.FullName != "System.Object" && !this.IsObjectLiteral(iDef))
                    {
                        TranslatorException.Throw(Constants.Messages.Exceptions.OBJECT_LITERAL_INTERFACE_INHERITANCE, type);
                    }
                }
            }

            if (objectCreateMode == 0)
            {
                var hasVirtualMethods = false;

                foreach (MethodDefinition method in type.Methods)
                {
                    if (AttributeHelper.HasCompilerGeneratedAttribute(method))
                    {
                        continue;
                    }

                    if (method.IsVirtual && !(method.IsSetter || method.IsGetter))
                    {
                        hasVirtualMethods = true;
                        break;
                    }
                }

                if (hasVirtualMethods)
                {
                    Bridge.Translator.TranslatorException.Throw(Constants.Messages.Exceptions.OBJECT_LITERAL_NO_VIRTUAL_METHODS, type);
                }
            }
        }
Example #9
0
 public static string ResourceKey(this Enum enumValue)
 {
     return(AttributeHelper.GetAttributeValue <ResourceKeyAttribute, string>(enumValue));
 }
 public VhdParentLocatorFactory(VhdDataReader dataReader, long offset)
 {
     this.dataReader = dataReader;
     this.offset = offset;
     attributeHelper = new AttributeHelper<ParentLocator>();
 }
Example #11
0
        public override CodeAttributeDeclaration GetAttributeDeclaration()
        {
            List <string> errorList = new List <string>();

            if (!IsValid(errorList))
            {
                throw new ArgumentException(errorList[0]);
            }

            CodeAttributeDeclaration attribute = new CodeAttributeDeclaration("ValidateRange");

            switch (_type)
            {
            case RangeValidationType.Integer:
                if (!string.IsNullOrEmpty(_min))
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgument(int.Parse(_min)));
                }
                else
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgumentUsingSnippet("Int32.MinValue"));
                }

                if (!string.IsNullOrEmpty(_max))
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgument(int.Parse(_max)));
                }
                else
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgumentUsingSnippet("Int32.MaxValue"));
                }
                break;

            case RangeValidationType.DateTime:
                if (!string.IsNullOrEmpty(_min))
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgument(DateTime.Parse(_min)));
                }
                else
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgumentUsingSnippet("DateTime.MinValue"));
                }

                if (!string.IsNullOrEmpty(_max))
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgument(DateTime.Parse(_max)));
                }
                else
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgumentUsingSnippet("DateTime.MaxValue"));
                }
                break;

            case RangeValidationType.String:
                if (!string.IsNullOrEmpty(_min))
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgument(_min));
                }
                else
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgumentUsingSnippet("String.Empty"));
                }

                if (!string.IsNullOrEmpty(_max))
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgument(_max));
                }
                else
                {
                    attribute.Arguments.Add(AttributeHelper.GetPrimitiveAttributeArgumentUsingSnippet("String.Empty"));
                }
                break;

            default:
                throw new ArgumentOutOfRangeException("Type");
            }

            base.AddAttributeArguments(attribute, ErrorMessagePlacement.UnOrdered);
            return(attribute);
        }
Example #12
0
        public static string StrName(this Enum enumValue)
        {
            var attrValue = AttributeHelper.GetAttributeValue <StringNameAttribute, string>(enumValue);

            return(string.IsNullOrEmpty(attrValue) ? enumValue.ToString().ToLower() : attrValue);
        }
Example #13
0
 public KerppiMain()
 {
     InitializeComponent();
     Application.Current.DispatcherUnhandledException += KerppiExceptionHandler;
     Title = AttributeHelper.GetAttribute <System.Reflection.AssemblyProductAttribute>().Product;
 }
Example #14
0
        void RegisterFactories()
        {
            var types = AttributeHelper.GetInterfacesWithSpecificAttribute(AssemblyName, typeof(WindsorFactoryAttribute));

            RegisterEachTypeAsFactory(types);
        }
Example #15
0
        public string GetHtml(string url, out HttpStatusCode code,
                              string post = null)
        {
            string result = "";

            HttpHelper.HttpResponse response;
            code = HttpStatusCode.NotFound;
            if (Regex.IsMatch(url, @"^[A-Z]:\\")) //本地文件
            {
                if (File.Exists(url))
                {
                    result = File.ReadAllText(url, AttributeHelper.GetEncoding(this.Http.Encoding));
                    code   = HttpStatusCode.Accepted;
                }
            }
            else
            {
                var mc = extract.Matches(url);
                if (SysProcessManager == null)
                {
                    code = HttpStatusCode.NoContent;
                    return("");
                }
                var crawler = this.SysProcessManager.GetTask <SmartCrawler>(ShareCookie.SelectItem);
                if (crawler != null)
                {
                    Http.ProxyIP = crawler.Http.ProxyIP;
                    if (Http.Parameters != crawler.Http.Parameters)
                    {
                        var cookie = crawler.Http.GetHeaderParameter().Get <string>("Cookie");
                        if (string.IsNullOrWhiteSpace(cookie) == false)
                        {
                            Http.SetValue("Cookie", cookie);
                        }
                    }
                }
                Dictionary <string, string> paradict = null;
                foreach (Match m in mc)
                {
                    if (paradict == null)
                    {
                        paradict = XPathAnalyzer.ParseUrl(URL);
                    }
                    if (paradict == null)
                    {
                        break;
                    }
                    var str = m.Groups[1].Value;
                    if (paradict.ContainsKey(str))
                    {
                        url = url.Replace(m.Groups[0].Value, paradict[str]);
                    }
                }
                response = helper.GetHtml(Http, url, post).Result;
                result   = response.Html;
                code     = response.Code;
            }
            result = JavaScriptAnalyzer.Decode(result);
            if (IsSuperMode)
            {
                result = JavaScriptAnalyzer.Parse2XML(result);
            }

            return(result);
        }
Example #16
0
        private static void CreateMethod(CompilerClassLoader loader, TypeBuilder tb, ProxyMethod pm)
        {
            MethodBuilder mb         = pm.mw.GetDefineMethodHelper().DefineMethod(loader.GetTypeWrapperFactory(), tb, pm.mw.Name, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final);
            List <string> exceptions = new List <string>();

            foreach (TypeWrapper tw in pm.exceptions)
            {
                exceptions.Add(tw.Name);
            }
            AttributeHelper.SetThrowsAttribute(mb, exceptions.ToArray());
            CodeEmitter ilgen = CodeEmitter.Create(mb);

            ilgen.BeginExceptionBlock();
            ilgen.Emit(OpCodes.Ldarg_0);
            invocationHandlerField.EmitGet(ilgen);
            ilgen.Emit(OpCodes.Ldarg_0);
            ilgen.Emit(OpCodes.Ldsfld, pm.fb);
            TypeWrapper[] parameters = pm.mw.GetParameters();
            if (parameters.Length == 0)
            {
                ilgen.Emit(OpCodes.Ldnull);
            }
            else
            {
                ilgen.EmitLdc_I4(parameters.Length);
                ilgen.Emit(OpCodes.Newarr, Types.Object);
                for (int i = 0; i < parameters.Length; i++)
                {
                    ilgen.Emit(OpCodes.Dup);
                    ilgen.EmitLdc_I4(i);
                    ilgen.EmitLdarg(i);
                    if (parameters[i].IsNonPrimitiveValueType)
                    {
                        parameters[i].EmitBox(ilgen);
                    }
                    else if (parameters[i].IsPrimitive)
                    {
                        Boxer.EmitBox(ilgen, parameters[i]);
                    }
                    ilgen.Emit(OpCodes.Stelem_Ref);
                }
            }
            invokeMethod.EmitCallvirt(ilgen);
            TypeWrapper      returnType  = pm.mw.ReturnType;
            CodeEmitterLocal returnValue = null;

            if (returnType != PrimitiveTypeWrapper.VOID)
            {
                returnValue = ilgen.DeclareLocal(returnType.TypeAsSignatureType);
                if (returnType.IsNonPrimitiveValueType)
                {
                    returnType.EmitUnbox(ilgen);
                }
                else if (returnType.IsPrimitive)
                {
                    Boxer.EmitUnbox(ilgen, returnType);
                }
                else if (returnType != CoreClasses.java.lang.Object.Wrapper)
                {
                    ilgen.EmitCastclass(returnType.TypeAsSignatureType);
                }
                ilgen.Emit(OpCodes.Stloc, returnValue);
            }
            CodeEmitterLabel returnLabel = ilgen.DefineLabel();

            ilgen.EmitLeave(returnLabel);
            // TODO consider using a filter here (but we would need to add filter support to CodeEmitter)
            ilgen.BeginCatchBlock(Types.Exception);
            ilgen.EmitLdc_I4(0);
            ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.mapException.MakeGenericMethod(Types.Exception));
            CodeEmitterLocal exception = ilgen.DeclareLocal(Types.Exception);

            ilgen.Emit(OpCodes.Stloc, exception);
            CodeEmitterLabel rethrow = ilgen.DefineLabel();

            ilgen.Emit(OpCodes.Ldloc, exception);
            errorClass.EmitInstanceOf(null, ilgen);
            ilgen.EmitBrtrue(rethrow);
            ilgen.Emit(OpCodes.Ldloc, exception);
            runtimeExceptionClass.EmitInstanceOf(null, ilgen);
            ilgen.EmitBrtrue(rethrow);
            foreach (TypeWrapper tw in pm.exceptions)
            {
                ilgen.Emit(OpCodes.Ldloc, exception);
                tw.EmitInstanceOf(null, ilgen);
                ilgen.EmitBrtrue(rethrow);
            }
            ilgen.Emit(OpCodes.Ldloc, exception);
            undeclaredThrowableExceptionConstructor.EmitNewobj(ilgen);
            ilgen.Emit(OpCodes.Throw);
            ilgen.MarkLabel(rethrow);
            ilgen.Emit(OpCodes.Rethrow);
            ilgen.EndExceptionBlock();
            ilgen.MarkLabel(returnLabel);
            if (returnValue != null)
            {
                ilgen.Emit(OpCodes.Ldloc, returnValue);
            }
            ilgen.Emit(OpCodes.Ret);
            ilgen.DoEmit();
        }
Example #17
0
        public override void TraverseChildren(IMethodDefinition methodDefinition)
        {
            if (!this.printCompilerGeneratedMembers)
            {
                if (methodDefinition.IsConstructor && methodDefinition.ParameterCount == 0 &&
                    AttributeHelper.Contains(methodDefinition.Attributes, methodDefinition.Type.PlatformType.SystemRuntimeCompilerServicesCompilerGeneratedAttribute))
                {
                    return;
                }

                // Skip if this is a method generated for use by a property or event
                foreach (var p in methodDefinition.ContainingTypeDefinition.Properties)
                {
                    if ((p.Getter != null && p.Getter.ResolvedMethod == methodDefinition) ||
                        (p.Setter != null && p.Setter.ResolvedMethod == methodDefinition))
                    {
                        return;
                    }
                }
                foreach (var e in methodDefinition.ContainingTypeDefinition.Events)
                {
                    if ((e.Adder != null && e.Adder.ResolvedMethod == methodDefinition) ||
                        (e.Remover != null && e.Remover.ResolvedMethod == methodDefinition))
                    {
                        return;
                    }
                }

                if (AttributeHelper.Contains(methodDefinition.Attributes, methodDefinition.Type.PlatformType.SystemRuntimeCompilerServicesCompilerGeneratedAttribute))
                {
                    return; // eg. an iterator helper - may have invalid identifier name
                }
            }

            // Cctors should probably be outputted in some cases
            if (methodDefinition.IsStaticConstructor)
            {
                return;
            }

            foreach (var ma in SortAttributes(methodDefinition.Attributes))
            {
                if (Utils.GetAttributeType(ma) != SpecialAttribute.Extension)
                {
                    PrintAttribute(methodDefinition, ma, true, null);
                }
            }

            foreach (var ra in SortAttributes(methodDefinition.ReturnValueAttributes))
            {
                PrintAttribute(methodDefinition, ra, true, "return");
            }

            PrintToken(CSharpToken.Indent);

            PrintMethodDefinitionVisibility(methodDefinition);
            PrintMethodDefinitionModifiers(methodDefinition);

            bool conversion = IsConversionOperator(methodDefinition);

            if (!conversion)
            {
                PrintMethodDefinitionReturnType(methodDefinition);
                if (!methodDefinition.IsConstructor && !IsDestructor(methodDefinition))
                {
                    PrintToken(CSharpToken.Space);
                }
            }
            PrintMethodDefinitionName(methodDefinition);
            if (conversion)
            {
                PrintMethodDefinitionReturnType(methodDefinition);
            }

            if (methodDefinition.IsGeneric)
            {
                Traverse(methodDefinition.GenericParameters);
            }
            Traverse(methodDefinition.Parameters);
            if (methodDefinition.IsGeneric)
            {
                PrintConstraints(methodDefinition.GenericParameters);
            }
            if (!methodDefinition.IsAbstract && !methodDefinition.IsExternal)
            {
                Traverse(methodDefinition.Body);
            }
            else
            {
                PrintToken(CSharpToken.Semicolon);
            }
        }
        /// <summary>
        ///     分析一个类型中的所有智能属性
        /// </summary>
        /// <param name="type">要分析的类型</param>
        /// <returns>返回分析的结果</returns>
        public override Dictionary <short, GetObjectAnalyseResult> Analyse(Type type)
        {
            if (type == null)
            {
                return(null);
            }
            Dictionary <short, GetObjectAnalyseResult> result = GetObject(type.FullName);

            if (result != null)
            {
                return(result);
            }
            var targetProperties = type.GetProperties().AsParallel().Where(property => AttributeHelper.GetCustomerAttribute <ThriftPropertyAttribute>(property) != null);

            if (!targetProperties.Any())
            {
                return(null);
            }
            result = targetProperties.Select(property => new GetObjectAnalyseResult
            {
                VTStruct   = GetVT(property.PropertyType),
                Property   = property,
                TargetType = type,
                Nullable   = Nullable.GetUnderlyingType(property.PropertyType) != null,
                Attribute  = AttributeHelper.GetCustomerAttribute <ThriftPropertyAttribute>(property)
            }.Initialize()).DefaultIfEmpty().OrderBy(property => property.Attribute.Id).ToDictionary(property => property.Attribute.Id);
            RegistAnalyseResult(type.FullName, result);
            return(result);
        }
Example #19
0
 public EntitySet(EntityContext context)
 {
     this._helper        = Xinchen.DbEntity.DbHelper.GetInstance(context.DbHelper.ConnectionString);
     this._entityType    = typeof(TEntity);
     this._entityMapper  = new EntityMapper <TEntity>();
     this._properties    = this._entityMapper.Properties;
     this._propertyNames = new string[this._properties.Length];
     this._propertyDict  = new Dictionary <string, PropertyInfo>();
     for (int i = 0; i < this._properties.Length; i++)
     {
         this._propertyNames[i] = "[" + this._properties[i].Name + "]";
         this._propertyDict.Add(this._properties[i].Name, this._properties[i]);
     }
     this._tableAttr   = (TableAttribute)this._entityType.GetCustomAttributes(EntitySet <TEntity> ._tableAttrType, true).FirstOrDefault <object>();
     this._keyProperty = this._properties.FirstOrDefault <PropertyInfo>(propertyInfo => AttributeHelper.GetAttribute <KeyAttribute>(propertyInfo) != null);
     if (this._keyProperty == null)
     {
         throw new EntityException("实体没有主键:" + TypeName);
     }
     this._autoIncrementProperty = this._properties.FirstOrDefault <PropertyInfo>(x => AttributeHelper.GetAttribute <AutoIncrementAttribute>(x) != null);
 }
Example #20
0
        public static IEnumerable <CustomPropertyInfo> GetToolProperty(Type tool, Object instance = null, bool mustBrowsable = true)
        {
            Object newinstance;

            if (instance == null)
            {
                instance    = PluginProvider.GetObjectInstance(tool);
                newinstance = instance;
            }
            else
            {
                newinstance = PluginProvider.GetObjectInstance(tool);
            }
            var propertys =
                tool.GetProperties().Where(
                    d => d.CanRead && d.CanWrite && AttributeHelper.IsEditableType(d.PropertyType)).ToArray();

            foreach (var propertyInfo in propertys.OrderBy(GetOrder))
            {
                var name = propertyInfo.Name;
                if (name == "ObjectID" || name == "Enabled" || name == "ColumnSelector")
                {
                    continue;
                }

                var property = new CustomPropertyInfo();

                string typeName     = null;
                var    defaultValue = GetDefaultValue(propertyInfo, newinstance, out typeName);
                var    currentValue = GetDefaultValue(propertyInfo, instance, out typeName);
                property.CurrentValue = currentValue;
                property.DefaultValue = defaultValue;
                var desc = GlobalHelper.Get("no_desc");
                // var fi =type.GetField(propertyInfo.Name);
                var browseable =
                    (BrowsableAttribute[])propertyInfo.GetCustomAttributes(typeof(BrowsableAttribute), false);
                if (browseable.Length > 0 && browseable[0].Browsable == false && mustBrowsable)
                {
                    continue;
                }
                var descriptionAttributes =
                    (LocalizedDescriptionAttribute[])propertyInfo.GetCustomAttributes(
                        typeof(LocalizedDescriptionAttribute), false);
                var nameAttributes =
                    (LocalizedDisplayNameAttribute[])propertyInfo.GetCustomAttributes(
                        typeof(LocalizedDisplayNameAttribute), false);
                if (nameAttributes.Length > 0)
                {
                    name = GlobalHelper.Get(nameAttributes[0].DisplayName);
                }
                if (descriptionAttributes.Length > 0)
                {
                    desc = GlobalHelper.Get(descriptionAttributes[0].Description);
                }
                desc                  = string.Join("\n", desc.Split('\n').Select(d => d.Trim('\t', ' ')));
                property.Desc         = desc;
                property.Name         = name;
                property.DefaultValue = defaultValue;
                property.OriginName   = propertyInfo.Name;
                property.TypeName     = typeName;
                yield return(property);
            }
        }
        protected View CreateHeader()
        {
            var type = GetListItemType();

            if (type == null)
            {
                _header.BackgroundColor = headerBackgroundColor;
                return(_header);
            }

            var attrib = type.GetAttribute <AutoFormsListUIAttribute>();

            _header = new Grid
            {
                ColumnSpacing     = attrib.ColumnSpacing,
                RowSpacing        = 0,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions   = LayoutOptions.StartAndExpand,
                RowDefinitions    = new RowDefinitionCollection
                {
                    new RowDefinition {
                        Height = GridLength.Auto
                    }
                }
            };
            Grid.SetRow(_header, 1);

            _header.Padding = new Thickness(attrib.ListItemPaddingLeft, attrib.ListHeaderPaddingTop, attrib.ListItemPaddingRight, attrib.ListHeaderPaddingBottom);

            var headerStyle = attrib?.ColumnHeaderGridStyle ?? null;

            if (string.IsNullOrEmpty(headerStyle) == false &&
                Application.Current.Resources.TryGetValue(headerStyle, out object headerObj))
            {
                _header.Style = (Style)headerObj;
            }
            else
            {
                _header.BackgroundColor = headerBackgroundColor;
            }

            var props = AttributeHelper.GetPropertyAttributes <AutoFormsListItemAttribute>(type);

            var   style           = LabelStyle;
            Style sortButtonStyle = null;

            var headerLabelStyle      = attrib?.ColumnHeaderLabelStyle ?? null;
            var headerSortButtonStyle = attrib?.ColumnHeaderSortButtonStyle ?? null;

            if (string.IsNullOrEmpty(headerLabelStyle) == false &&
                Application.Current.Resources.TryGetValue(headerLabelStyle, out object obj))
            {
                style = (Style)obj;
            }

            if (string.IsNullOrEmpty(headerSortButtonStyle) == false &&
                Application.Current.Resources.TryGetValue(headerSortButtonStyle, out object sortButtonStyleObj))
            {
                sortButtonStyle = (Style)sortButtonStyleObj;
            }

            string sortedStateProperty = null;

            if (_config.Attribute is AutoFormsListAttribute listAttribute)
            {
                sortedStateProperty = listAttribute.SortedStateProperty;
            }

            foreach (var p in props)
            {
                var property  = p.Item1;
                var attribute = GetFilteredAttribute(Filter, p.Item2);

                if (property == null || attribute == null)
                {
                    continue;
                }

                _header.ColumnDefinitions.Add(new ColumnDefinition {
                    Width = new GridLength(attribute.Value, attribute.GridType)
                });

                View view;
                if (attribute.SortValue != null && !string.IsNullOrWhiteSpace(sortedStateProperty))
                {
                    view = new SortButton
                    {
                        Text              = attribute.Label,
                        VerticalOptions   = LayoutOptions.CenterAndExpand,
                        HorizontalOptions = LayoutOptions.StartAndExpand,
                        SortValue         = attribute.SortValue
                    };
                    if (sortButtonStyle != null)
                    {
                        view.Style = sortButtonStyle;
                    }
                    view.SetBinding(SortButton.SortedStateProperty, sortedStateProperty);
                }
                else
                {
                    view = new Label
                    {
                        Style                   = style,
                        Text                    = attribute.Label,
                        VerticalOptions         = LayoutOptions.CenterAndExpand,
                        VerticalTextAlignment   = TextAlignment.Start,
                        HorizontalOptions       = LayoutOptions.StartAndExpand,
                        HorizontalTextAlignment = attribute.HorizontalHeaderAlignment,
                        LineBreakMode           = LineBreakMode.TailTruncation,
                    };
                }

                //view.BackgroundColor = Color.Green;

                Grid.SetColumn(view, _header.ColumnDefinitions.Count - 1);
                _header.Children.Add(view);
            }

            if (HasActions)
            {
                _header.ColumnDefinitions.Add(new ColumnDefinition {
                    Width = new GridLength(ActionButtonWidth, GridUnitType.Absolute)
                });
            }

            _header.DebugGrid(Color.Transparent);

            return(_header);
        }
Example #22
0
        /// <summary>
        /// Tries to get the assembly set up tear down attribute.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        /// <param name="setUp">The set up.</param>
        /// <param name="tearDown">The tear down.</param>
        /// <returns>True if found.</returns>
        public override bool TryGetAssemblySetupTeardownMethods(
            AssemblyEx assembly,
            out Method setUp,
            out Method tearDown)
        {
            // <preconditions>
            SafeDebug.AssumeNotNull((object)assembly, "assembly");

            // </preconditions>
            setUp = tearDown = null;

            // look for [TestClass] types
            foreach (var typeDefinition in assembly.TypeDefinitions)
            {
                if (typeDefinition.IsVisible(VisibilityContext.Exported))
                {
                    if (typeDefinition.IsEnumType ||
                        typeDefinition.GenericTypeParameters.Length > 0)
                    {
                        continue;
                    }

                    if (!this.IsFixture(typeDefinition))
                    {
                        continue;
                    }

                    // looking for assembly setup/teardown methods
                    foreach (var methodDefinition in typeDefinition.DeclaredStaticMethods)
                    {
                        if (methodDefinition.IsVisible(VisibilityContext.Exported) &&
                            methodDefinition.GenericMethodParameters.Length == 0)
                        {
                            if (AttributeHelper.IsDefined(methodDefinition, this.AssemblySetUpAttribute, true))
                            {
                                setUp = methodDefinition.Instantiate(TypeEx.NoTypes, TypeEx.NoTypes);
                            }

                            if (AttributeHelper.IsDefined(methodDefinition, this.AssemblyTearDownAttribute, true))
                            {
                                tearDown = methodDefinition.Instantiate(TypeEx.NoTypes, TypeEx.NoTypes);
                            }

                            // nothing else to look for
                            if (setUp != null && tearDown != null)
                            {
                                break;
                            }
                        }
                    }

                    // nothing else to look for
                    if (setUp != null && tearDown != null)
                    {
                        break;
                    }
                }
            }

            return(setUp != null || tearDown != null);
        }
        public override void ApplyAttribute(ulong attributeEventHandlerId, string attributeName, object attributeValue, string attributeEventUpdatesAttributeName)
        {
            switch (attributeName)
            {
            case nameof(XFD.TwoPaneView.MinTallModeHeight):
                TwoPaneViewControl.MinTallModeHeight = AttributeHelper.StringToDouble((string)attributeValue);
                break;

            case nameof(XFD.TwoPaneView.MinWideModeWidth):
                TwoPaneViewControl.MinWideModeWidth = AttributeHelper.StringToDouble((string)attributeValue);
                break;

            case nameof(XFD.TwoPaneView.Pane1Length):
                TwoPaneViewControl.Pane1Length = AttributeHelper.StringToGridLength(attributeValue, XF.GridLength.Star);
                break;

            case nameof(XFD.TwoPaneView.Pane2Length):
                TwoPaneViewControl.Pane2Length = AttributeHelper.StringToGridLength(attributeValue, XF.GridLength.Star);
                break;

            case nameof(XFD.TwoPaneView.PanePriority):
                TwoPaneViewControl.PanePriority = (XFD.TwoPaneViewPriority)AttributeHelper.GetInt(attributeValue);
                break;

            case nameof(XFD.TwoPaneView.TallModeConfiguration):
                TwoPaneViewControl.TallModeConfiguration = (XFD.TwoPaneViewTallModeConfiguration)AttributeHelper.GetInt(attributeValue, (int)XFD.TwoPaneViewTallModeConfiguration.TopBottom);
                break;

            case nameof(XFD.TwoPaneView.WideModeConfiguration):
                TwoPaneViewControl.WideModeConfiguration = (XFD.TwoPaneViewWideModeConfiguration)AttributeHelper.GetInt(attributeValue, (int)XFD.TwoPaneViewWideModeConfiguration.LeftRight);
                break;

            default:
                base.ApplyAttribute(attributeEventHandlerId, attributeName, attributeValue, attributeEventUpdatesAttributeName);
                break;
            }
        }
Example #24
0
 private SceneInfoAttribute CollectSceneInfo(MemberInfo mi)
 {
     return(AttributeHelper.GetCustomAttribute <SceneInfoAttribute>(mi));
 }
Example #25
0
        internal static void WriteClass(Stream stream, TypeWrapper tw, bool includeNonPublicInterfaces, bool includeNonPublicMembers, bool includeSerialVersionUID)
        {
            string name  = tw.Name.Replace('.', '/');
            string super = null;

            if (tw.IsInterface)
            {
                super = "java/lang/Object";
            }
            else if (tw.BaseTypeWrapper != null)
            {
                super = tw.BaseTypeWrapper.Name.Replace('.', '/');
            }
            ClassFileWriter writer = new ClassFileWriter(tw.Modifiers, name, super, 0, 49);

            foreach (TypeWrapper iface in tw.Interfaces)
            {
                if (iface.IsPublic || includeNonPublicInterfaces)
                {
                    writer.AddInterface(iface.Name.Replace('.', '/'));
                }
            }
            InnerClassesAttribute innerClassesAttribute = null;

            if (tw.DeclaringTypeWrapper != null)
            {
                TypeWrapper outer     = tw.DeclaringTypeWrapper;
                string      innername = name;
                int         idx       = name.LastIndexOf('$');
                if (idx >= 0)
                {
                    innername = innername.Substring(idx + 1);
                }
                innerClassesAttribute = new InnerClassesAttribute(writer);
                innerClassesAttribute.Add(name, outer.Name.Replace('.', '/'), innername, (ushort)tw.ReflectiveModifiers);
            }
            foreach (TypeWrapper inner in tw.InnerClasses)
            {
                if (inner.IsPublic)
                {
                    if (innerClassesAttribute == null)
                    {
                        innerClassesAttribute = new InnerClassesAttribute(writer);
                    }
                    string namePart = inner.Name;
                    namePart = namePart.Substring(namePart.LastIndexOf('$') + 1);
                    innerClassesAttribute.Add(inner.Name.Replace('.', '/'), name, namePart, (ushort)inner.ReflectiveModifiers);
                }
            }
            if (innerClassesAttribute != null)
            {
                writer.AddAttribute(innerClassesAttribute);
            }
            string genericTypeSignature = tw.GetGenericSignature();

            if (genericTypeSignature != null)
            {
                writer.AddStringAttribute("Signature", genericTypeSignature);
            }
            AddAnnotations(writer, writer, tw.TypeAsBaseType);
            writer.AddStringAttribute("IKVM.NET.Assembly", GetAssemblyName(tw));
            if (tw.TypeAsBaseType.IsDefined(JVM.Import(typeof(ObsoleteAttribute)), false))
            {
                writer.AddAttribute(new DeprecatedAttribute(writer));
            }
            foreach (MethodWrapper mw in tw.GetMethods())
            {
                if (!mw.IsHideFromReflection && (mw.IsPublic || mw.IsProtected || includeNonPublicMembers))
                {
                    FieldOrMethod m;
                    if (mw.Name == "<init>")
                    {
                        m = writer.AddMethod(mw.Modifiers, mw.Name, mw.Signature.Replace('.', '/'));
                        CodeAttribute code = new CodeAttribute(writer);
                        code.MaxLocals = (ushort)(mw.GetParameters().Length * 2 + 1);
                        code.MaxStack  = 3;
                        ushort index1 = writer.AddClass("java/lang/UnsatisfiedLinkError");
                        ushort index2 = writer.AddString("ikvmstub generated stubs can only be used on IKVM.NET");
                        ushort index3 = writer.AddMethodRef("java/lang/UnsatisfiedLinkError", "<init>", "(Ljava/lang/String;)V");
                        code.ByteCode = new byte[] {
                            187, (byte)(index1 >> 8), (byte)index1,                     // new java/lang/UnsatisfiedLinkError
                            89,                                                         // dup
                            19, (byte)(index2 >> 8), (byte)index2,                      // ldc_w "..."
                            183, (byte)(index3 >> 8), (byte)index3,                     // invokespecial java/lang/UnsatisfiedLinkError/init()V
                            191                                                         // athrow
                        };
                        m.AddAttribute(code);
                    }
                    else
                    {
                        Modifiers mods = mw.Modifiers;
                        if ((mods & Modifiers.Abstract) == 0)
                        {
                            mods |= Modifiers.Native;
                        }
                        m = writer.AddMethod(mods, mw.Name, mw.Signature.Replace('.', '/'));
                        if (mw.IsOptionalAttributeAnnotationValue)
                        {
                            m.AddAttribute(new AnnotationDefaultClassFileAttribute(writer, GetAnnotationDefault(writer, mw.ReturnType)));
                        }
                    }
                    MethodBase mb = mw.GetMethod();
                    if (mb != null)
                    {
                        ThrowsAttribute throws = AttributeHelper.GetThrows(mb);
                        if (throws == null)
                        {
                            string[] throwsArray = mw.GetDeclaredExceptions();
                            if (throwsArray != null && throwsArray.Length > 0)
                            {
                                ExceptionsAttribute attrib = new ExceptionsAttribute(writer);
                                foreach (string ex in throwsArray)
                                {
                                    attrib.Add(ex.Replace('.', '/'));
                                }
                                m.AddAttribute(attrib);
                            }
                        }
                        else
                        {
                            ExceptionsAttribute attrib = new ExceptionsAttribute(writer);
                            if (throws.classes != null)
                            {
                                foreach (string ex in throws.classes)
                                {
                                    attrib.Add(ex.Replace('.', '/'));
                                }
                            }
                            if (throws.types != null)
                            {
                                foreach (Type ex in throws.types)
                                {
                                    attrib.Add(ClassLoaderWrapper.GetWrapperFromType(ex).Name.Replace('.', '/'));
                                }
                            }
                            m.AddAttribute(attrib);
                        }
                        if (mb.IsDefined(JVM.Import(typeof(ObsoleteAttribute)), false)
                            // HACK the instancehelper methods are marked as Obsolete (to direct people toward the ikvm.extensions methods instead)
                            // but in the Java world most of them are not deprecated (and to keep the Japi results clean we need to reflect this)
                            && (!mb.Name.StartsWith("instancehelper_") ||
                                mb.DeclaringType.FullName != "java.lang.String"
                                // the Java deprecated methods actually have two Obsolete attributes
                                || GetObsoleteCount(mb) == 2))
                        {
                            m.AddAttribute(new DeprecatedAttribute(writer));
                        }
                        CustomAttributeData attr = GetAnnotationDefault(mb);
                        if (attr != null)
                        {
                            m.AddAttribute(new AnnotationDefaultClassFileAttribute(writer, GetAnnotationDefault(writer, attr.ConstructorArguments[0])));
                        }
                    }
                    string sig = tw.GetGenericMethodSignature(mw);
                    if (sig != null)
                    {
                        m.AddAttribute(writer.MakeStringAttribute("Signature", sig));
                    }
                    AddAnnotations(writer, m, mw.GetMethod());
                    AddParameterAnnotations(writer, m, mw.GetMethod());
                }
            }
            bool hasSerialVersionUID = false;

            foreach (FieldWrapper fw in tw.GetFields())
            {
                if (!fw.IsHideFromReflection)
                {
                    bool isSerialVersionUID = includeSerialVersionUID && fw.Name == "serialVersionUID" && fw.FieldTypeWrapper == PrimitiveTypeWrapper.LONG;
                    hasSerialVersionUID |= isSerialVersionUID;
                    if (fw.IsPublic || fw.IsProtected || isSerialVersionUID || includeNonPublicMembers)
                    {
                        object constant = null;
                        if (fw.GetField() != null && fw.GetField().IsLiteral&& (fw.FieldTypeWrapper.IsPrimitive || fw.FieldTypeWrapper == CoreClasses.java.lang.String.Wrapper))
                        {
                            constant = fw.GetField().GetRawConstantValue();
                            if (fw.GetField().FieldType.IsEnum)
                            {
                                constant = EnumHelper.GetPrimitiveValue(EnumHelper.GetUnderlyingType(fw.GetField().FieldType), constant);
                            }
                        }
                        FieldOrMethod f   = writer.AddField(fw.Modifiers, fw.Name, fw.Signature.Replace('.', '/'), constant);
                        string        sig = tw.GetGenericFieldSignature(fw);
                        if (sig != null)
                        {
                            f.AddAttribute(writer.MakeStringAttribute("Signature", sig));
                        }
                        if (fw.GetField() != null && fw.GetField().IsDefined(JVM.Import(typeof(ObsoleteAttribute)), false))
                        {
                            f.AddAttribute(new DeprecatedAttribute(writer));
                        }
                        AddAnnotations(writer, f, fw.GetField());
                    }
                }
            }
            if (includeSerialVersionUID && !hasSerialVersionUID && IsSerializable(tw))
            {
                // class is serializable but doesn't have an explicit serialVersionUID, so we add the field to record
                // the serialVersionUID as we see it (mainly to make the Japi reports more realistic)
                writer.AddField(Modifiers.Private | Modifiers.Static | Modifiers.Final, "serialVersionUID", "J", SerialVersionUID.Compute(tw));
            }
            AddMetaAnnotations(writer, tw);
            writer.Write(stream);
        }
Example #26
0
 protected string GetCollectionName()
 {
     return(AttributeHelper.GetBsonCollectionAttributeName(typeof(T)));
 }
        /// <summary>
        /// Регистрируем тип сообщения
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IMessageTypeProvider Register(this IMessageTypeProvider provider, Type type)
        {
            var tag = AttributeHelper.GetPropertyName <MessageQueueNameAttribute>(type, true);

            return(provider.Register(tag, type));
        }
Example #28
0
        public static ProductFieldStatus Status(this ProductFields enumValue)
        {
            var attrValue = AttributeHelper.GetAttributeValue <ProductFieldsStatusAttribute, ProductFieldStatus>(enumValue);

            return(attrValue);
        }
Example #29
0
        public void HandleDeliveryReportTimeout()
        {
            UniqueJob uniqueJob = this.uniqueJobList.AddOrUpdate("HandleDeliveryReportTimeout");

            if (uniqueJob == null)
            {
                return;                    // Job 已經存在
            }
            try
            {
                using (var scope = this.unitOfWork.CreateTransactionScope())
                {
                    // 若一天之後,SendMessageHistory 狀態仍然為 MessageAccepted (仍未取得派送結果),
                    // 則將此筆 SendMessageHistory 狀態改成 DeliveryReportTimeout

                    var sendMessageRuleRepository    = this.unitOfWork.Repository <SendMessageRule>();
                    var sendMessageQueueRepository   = this.unitOfWork.Repository <SendMessageQueue>();
                    var sendMessageHistoryRepository = this.unitOfWork.Repository <SendMessageHistory>();

                    var expiryDate = DateTime.UtcNow.AddTicks(-1 * DeliveryReportQueue.QueryInterval.Ticks);

                    var entities = sendMessageHistoryRepository
                                   .GetMany(p =>
                                            (p.DeliveryStatus == DeliveryReportStatus.MessageAccepted || // Infobip
                                             p.DeliveryStatus == DeliveryReportStatus.Sending) &&        // Every8d
                                                                                                         // 已經過期
                                            p.CreatedTime < expiryDate)
                                   .ToList();

                    var sendMessageQueueIds = entities.Select(p => p.SendMessageQueueId).Distinct().ToList();
                    var sendMessageRuleIds  = entities.Select(p => p.SendMessageRuleId).Distinct().ToList();
                    var sendMessageQueues   = sendMessageQueueRepository.GetMany(p => sendMessageQueueIds.Contains(p.Id)).ToList();
                    var sendMessageRules    = sendMessageRuleRepository.GetMany(p => sendMessageRuleIds.Contains(p.Id)).ToList();

                    foreach (var entity in entities)
                    {
                        var oldDeliveryStatus = entity.DeliveryStatus;
                        var newDeliveryStatus = DeliveryReportStatus.DeliveryReportTimeout;
                        var sendMessageQueue  = sendMessageQueues.Find(p => p.Id == entity.SendMessageQueueId);
                        var sendMessageRule   = sendMessageRules.Find(p => p.Id == entity.SendMessageRuleId);

                        this.logService.Debug("{0}(簡訊編號:{1},序列編號:{2}),收訊門號{3}已超過{4}未經收到派送結果,接收狀態將由{5}改成{6}",
                                              AttributeHelper.GetColumnDescription(sendMessageRule.SendTimeType),
                                              sendMessageRule.Id,
                                              sendMessageQueue.Id,
                                              entity.DestinationAddress,
                                              DeliveryReportQueue.QueryInterval.ToString(),
                                              oldDeliveryStatus.ToString(),
                                              newDeliveryStatus.ToString());

                        entity.DeliveryStatus       = newDeliveryStatus;
                        entity.DeliveryStatusString = entity.DeliveryStatus.ToString();
                        entity.Delivered            = false;
                        sendMessageHistoryRepository.Update(entity);

                        // 如果發送失敗,就回補點數
                        // 20151123 Norman, Eric 要求發送失敗不回補點數
                        //tradeService.HandleSendMessageHistory(sendMessageRule, sendMessageQueue, entity);
                    }

                    foreach (var sendMessageQueueId in sendMessageQueueIds)
                    {
                        this.logService.Debug("簡訊序列編號:{0}),重新計算 SendMessageStatistic", sendMessageQueueId);

                        this.sendMessageStatisticService.AddOrUpdateSendMessageStatistic(sendMessageQueueId);
                    }

                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                this.logService.Error(ex);
                throw;
            }
            finally
            {
                this.uniqueJobList.Remove(uniqueJob);
            }
        }
Example #30
0
 public void Controller_ShouldNotHaveAnonymousActions()
 {
     AttributeHelper.ShouldNotHaveAnonymousMethods(typeof(UnauthenticatedUserController));
 }
        public virtual PropertyViewModel CreateViewModel(object instance, PropertyDescriptor descriptor)
        {
            PropertyViewModel propertyViewModel = null;

            // Optional by Nullable type
            var nullable = descriptor.PropertyType.IsGenericType &&
                           descriptor.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>);

            if (nullable)
            {
                propertyViewModel = new OptionalPropertyViewModel(instance, descriptor, null, owner);
            }

            // Optional by Attribute
            var oa = AttributeHelper.GetAttribute <OptionalAttribute>(descriptor);

            if (oa != null)
            {
                propertyViewModel = new OptionalPropertyViewModel(instance, descriptor, oa.PropertyName, owner);
            }

            // Wide
            var wa = AttributeHelper.GetAttribute <WidePropertyAttribute>(descriptor);

            if (wa != null)
            {
                propertyViewModel = new WidePropertyViewModel(instance, descriptor, wa.ShowHeader, owner);
            }

            // If bool properties should be shown as checkbox only (no header label), we create
            // a CheckBoxPropertyViewModel
            if (descriptor.PropertyType == typeof(bool) && owner != null && !owner.ShowBoolHeader)
            {
                propertyViewModel = new CheckBoxPropertyViewModel(instance, descriptor, owner);
            }

            // Properties with the Slidable attribute set
            var sa = AttributeHelper.GetAttribute <SlidableAttribute>(descriptor);

            if (sa != null)
            {
                propertyViewModel = new SlidablePropertyViewModel(instance, descriptor, owner)
                {
                    SliderMinimum     = sa.Minimum,
                    SliderMaximum     = sa.Maximum,
                    SliderLargeChange = sa.LargeChange,
                    SliderSmallChange = sa.SmallChange
                }
            }
            ;

            // FilePath
            var fpa = AttributeHelper.GetAttribute <FilePathAttribute>(descriptor);

            if (fpa != null)
            {
                propertyViewModel = new FilePathPropertyViewModel(instance, descriptor, owner)
                {
                    Filter = fpa.Filter, DefaultExtension = fpa.DefaultExtension
                }
            }
            ;

            // DirectoryPath
            var dpa = AttributeHelper.GetAttribute <DirectoryPathAttribute>(descriptor);

            if (dpa != null)
            {
                propertyViewModel = new DirectoryPathPropertyViewModel(instance, descriptor, owner);
            }

            // Default text property
            if (propertyViewModel == null)
            {
                var tp = new PropertyViewModel(instance, descriptor, owner);

                propertyViewModel = tp;
            }

            var fsa = AttributeHelper.GetAttribute <FormatStringAttribute>(descriptor);

            if (fsa != null)
            {
                propertyViewModel.FormatString = fsa.FormatString;
            }

            var ha = AttributeHelper.GetAttribute <HeightAttribute>(descriptor);

            if (ha != null)
            {
                propertyViewModel.Height = ha.Height;
            }
            if (propertyViewModel.Height > 0)
            {
                propertyViewModel.AcceptsReturn = true;
                propertyViewModel.TextWrapping  = TextWrapping.Wrap;
            }

            var soa = AttributeHelper.GetAttribute <SortOrderAttribute>(descriptor);

            if (soa != null)
            {
                propertyViewModel.SortOrder = soa.SortOrder;
            }

            return(propertyViewModel);
        }
    }
}
Example #32
0
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            if (!ContextDataCache.TryGetContextData <GUIStyle>("BigLabel", out var bigLabel))
            {
                bigLabel.value              = new GUIStyle(GUI.skin.label);
                bigLabel.value.fontSize     = 18;
                bigLabel.value.fontStyle    = FontStyle.Bold;
                bigLabel.value.alignment    = TextAnchor.MiddleLeft;
                bigLabel.value.stretchWidth = true;
            }

            ConfigAssetGroup groupAsset = target as ConfigAssetGroup;

            GUILayoutExtension.VerticalGroup(() =>
            {
                GUILayout.Label($"Config:{groupAsset.name}", bigLabel.value);
            });

            GUILayoutExtension.VerticalGroup(() =>
            {
                List <Type> cnfTypes   = new List <Type>();
                List <string> cnfNames = new List <string>();
                foreach (var item in ReflectionHelper.GetChildTypes <IConfig>())
                {
                    string displayName = item.Name;
                    if (AttributeHelper.TryGetTypeAttribute(item, out ConfigAttribute attr))
                    {
                        displayName = attr.DisplayName;
                    }
                    cnfNames.Add(displayName);
                    cnfTypes.Add(item);
                }
                if (groupAsset.configTypeFullName == null)
                {
                    EditorGUILayout.HelpBox("没有选择配置类!!!", MessageType.Error);
                    MiscHelper.Dropdown($"选择的配置类", cnfNames, (int a) => {
                        groupAsset.configTypeFullName = cnfTypes[a].FullName;
                        groupAsset.configTypeName     = cnfTypes[a].Name;
                    }, 300);
                }
                else
                {
                    MiscHelper.Dropdown(groupAsset.configTypeFullName, cnfNames, (int a) => {
                        groupAsset.configTypeFullName = cnfTypes[a].FullName;
                        groupAsset.configTypeName     = cnfTypes[a].Name;
                    }, 300);
                }
            });

            GUILayoutExtension.VerticalGroup(() => {
                List <ConfigAsset> assets = groupAsset.GetAllAsset();
                for (int i = 0; i < assets.Count; i++)
                {
                    DrawGraph(groupAsset, assets[i]);
                }
            });

            GUILayoutExtension.VerticalGroup(() =>
            {
                if (GUILayout.Button($"创建配置", GUILayout.Height(50)))
                {
                    MiscHelper.Input($"输入配置名:", (string name) =>
                    {
                        groupAsset.CreateAsset(name);
                    });
                }
            });
        }
Example #33
0
 public VhdFooterSerializer(VhdFooter vhdFooter)
 {
     this.vhdFooter       = vhdFooter;
     this.attributeHelper = new AttributeHelper <VhdFooter>();
 }
        public override BaseResponse GenerateResponse()
        {
            GetGameObjectResponse getGOResponse = new GetGameObjectResponse();

            Transform foundTransform = TransformHelper.GetFromPath(gameObjectPath);

            getGOResponse.GameObjectName = foundTransform.name;

            List <Object> components = new List <Object>(foundTransform.GetComponents <Component>());

            // Not technically a component, but include the GameObject
            components.Insert(0, foundTransform.gameObject);
            getGOResponse.Components = new List <ComponentDescription>(components.Count);
            foreach (Object component in components)
            {
                //Guid guid = ObjectMap.AddOrGetObject(component);
                ObjectMap.AddOrGetObject(component);

                ComponentDescription description = new ComponentDescription(component);
                Type componentType = component.GetType();

                while (componentType != null &&
                       componentType != typeof(System.Object) &&
                       componentType != typeof(UnityEngine.Object) &&
                       componentType != typeof(UnityEngine.Component))
                {
                    ComponentScope componentScope = new ComponentScope(componentType);
                    if ((flags & InfoFlags.Fields) == InfoFlags.Fields)
                    {
                        FieldInfo[] fieldInfos = componentType.GetFields(BINDING_FLAGS);
                        foreach (FieldInfo fieldInfo in fieldInfos)
                        {
                            if (TypeUtility.IsBackingField(fieldInfo, componentType))
                            {
                                // Skip backing fields for auto-implemented properties
                                continue;
                            }

                            object objectValue = fieldInfo.GetValue(component);

                            WrappedVariable wrappedVariable = new WrappedVariable(fieldInfo, objectValue);
                            componentScope.Fields.Add(wrappedVariable);
                        }
                    }

                    if (componentType == typeof(GameObject)) // Special handling for GameObject.name to always be included
                    {
                        PropertyInfo    nameProperty = componentType.GetProperty("name", BindingFlags.Public | BindingFlags.Instance);
                        WrappedVariable wrappedName  = new WrappedVariable(nameProperty, nameProperty.GetValue(component, null));
                        componentScope.Properties.Add(wrappedName);
                    }

                    if ((flags & InfoFlags.Properties) == InfoFlags.Properties)
                    {
                        PropertyInfo[] properties = componentType.GetProperties(BINDING_FLAGS);
                        foreach (PropertyInfo property in properties)
                        {
                            Type declaringType = property.DeclaringType;
                            if (declaringType == typeof(Component) ||
                                declaringType == typeof(UnityEngine.Object))
                            {
                                continue;
                            }

                            object[] attributes          = property.GetCustomAttributes(false);
                            bool     isObsoleteWithError = AttributeHelper.IsObsoleteWithError(attributes);
                            if (isObsoleteWithError)
                            {
                                continue;
                            }

                            // Skip properties that cause exceptions at edit time
                            if (Application.isPlaying == false)
                            {
                                if (typeof(MeshFilter).IsAssignableFrom(declaringType))
                                {
                                    if (property.Name == "mesh")
                                    {
                                        continue;
                                    }
                                }

                                if (typeof(Renderer).IsAssignableFrom(declaringType))
                                {
                                    if (property.Name == "material" || property.Name == "materials")
                                    {
                                        continue;
                                    }
                                }
                            }



                            string propertyName = property.Name;

                            MethodInfo getMethod = property.GetGetMethod(true);
                            if (getMethod != null)
                            {
                                //MethodImplAttributes methodImplAttributes = getMethod.GetMethodImplementationFlags();
                                //if ((methodImplAttributes & MethodImplAttributes.InternalCall) != 0)
                                //{
                                //    continue;
                                //}


                                object objectValue = getMethod.Invoke(component, null);

                                WrappedVariable wrappedVariable = new WrappedVariable(property, objectValue);
                                componentScope.Properties.Add(wrappedVariable);
                            }
                        }
                    }

                    if ((flags & InfoFlags.Methods) == InfoFlags.Methods)
                    {
                        MethodInfo[] methodInfos = componentType.GetMethods(BINDING_FLAGS);
                        foreach (var methodInfo in methodInfos)
                        {
                            if (TypeUtility.IsPropertyMethod(methodInfo, componentType))
                            {
                                // Skip automatically generated getter/setter methods
                                continue;
                            }

                            MethodImplAttributes methodImplAttributes = methodInfo.GetMethodImplementationFlags();
                            if ((methodImplAttributes & MethodImplAttributes.InternalCall) != 0 && methodInfo.Name.StartsWith("INTERNAL_"))
                            {
                                // Skip any internal method if it also begins with INTERNAL_
                                continue;
                            }
                            WrappedMethod wrappedMethod = new WrappedMethod(methodInfo);
                            componentScope.Methods.Add(wrappedMethod);
                        }
                    }

                    description.Scopes.Add(componentScope);

                    componentType = componentType.BaseType;
                }

                getGOResponse.Components.Add(description);
            }
            return(getGOResponse);
        }
Example #35
0
        protected override void RenderAttributes(AttributesBuilder builder)
        {
            base.RenderAttributes(builder);

            if (BackgroundGradientAngle != null)
            {
                builder.AddAttribute(nameof(BackgroundGradientAngle), BackgroundGradientAngle.Value);
            }
            if (BackgroundGradientEndColor != null)
            {
                builder.AddAttribute(nameof(BackgroundGradientEndColor), AttributeHelper.ColorToString(BackgroundGradientEndColor.Value));
            }
            if (BackgroundGradientStartColor != null)
            {
                builder.AddAttribute(nameof(BackgroundGradientStartColor), AttributeHelper.ColorToString(BackgroundGradientStartColor.Value));
            }
            //IEnumerable<GradientStop> BackgroundGradientStops
            if (BorderColor != null)
            {
                builder.AddAttribute(nameof(BorderColor), AttributeHelper.ColorToString(BorderColor.Value));
            }
            if (BorderDrawingStyle != null)
            {
                builder.AddAttribute(nameof(BorderDrawingStyle), (int)BorderDrawingStyle.Value);
            }
            if (BorderGradientAngle != null)
            {
                builder.AddAttribute(nameof(BorderGradientAngle), BorderGradientAngle.Value);
            }
            if (BorderGradientEndColor != null)
            {
                builder.AddAttribute(nameof(BorderGradientEndColor), AttributeHelper.ColorToString(BorderGradientEndColor.Value));
            }
            if (BorderGradientStartColor != null)
            {
                builder.AddAttribute(nameof(BorderGradientStartColor), AttributeHelper.ColorToString(BorderGradientStartColor.Value));
            }
            //IEnumerable<GradientStop> BorderGradientStops
            if (BorderIsDashed != null)
            {
                builder.AddAttribute(nameof(BorderIsDashed), BorderIsDashed.Value);
            }
            if (BorderThickness != null)
            {
                builder.AddAttribute(nameof(BorderThickness), AttributeHelper.SingleToString(BorderThickness.Value));
            }
            if (CornerRadius != null)
            {
                builder.AddAttribute(nameof(CornerRadius), AttributeHelper.CornerRadiusToString(CornerRadius.Value));
            }
            if (Elevation != null)
            {
                builder.AddAttribute(nameof(Elevation), Elevation.Value);
            }
            if (HasShadow != null)
            {
                builder.AddAttribute(nameof(HasShadow), HasShadow.Value);
            }
            if (OffsetAngle != null)
            {
                builder.AddAttribute(nameof(OffsetAngle), AttributeHelper.DoubleToString(OffsetAngle.Value));
            }
            if (Sides != null)
            {
                builder.AddAttribute(nameof(Sides), Sides.Value);
            }
        }
 public VhdFooterSerializer(VhdFooter vhdFooter)
 {
     this.vhdFooter = vhdFooter;
     this.attributeHelper = new AttributeHelper<VhdFooter>();
 }
Example #37
0
 // Does NOT include methods marked with SecuritySafeCriticalAttribute.
 private bool IsSecurityCritical(ITypeDefinitionMember member)
 {
     return(AttributeHelper.Contains(member.Attributes, this.asmMetaHostEnvironment.platformType.SystemSecuritySecurityCriticalAttribute));
 }
        private static void ApplyChanges(List <SimpleUser> changes, ADToPermissionCenterSynchronizer context)
        {
            string[] changesIdArray             = changes.Select <SimpleUser, string>(m => m.SCObjectID).ToArray();
            PC.SchemaObjectCollection pcObjects = LoadSCObjects(changesIdArray);

            foreach (SimpleUser item in changes)
            {
                if (pcObjects.ContainsKey(item.SCObjectID))
                {
                    try
                    {
                        PC.SchemaObjectBase scObj = MeargeChanges(item.Tag, pcObjects[item.SCObjectID]);

                        PC.Adapters.SchemaObjectAdapter.Instance.Update(scObj);
                        context.Log.NumberOfModifiedItems++;
                    }
                    catch (Exception ex)
                    {
                        context.Log.NumberOfExceptions++;
                        context.Log.Status = ADSynchronizeResult.HasError;
                        LogHelper.WriteReverseSynchronizeDBLogDetail(context.Log.LogID, item.SCObjectID, AttributeHelper.Hex((byte[])item.Tag.Properties["objectguid"][0]), item.CodeName, ex.Message, ex.ToString());
                        Trace.TraceError("未成功更新," + ex.ToString());
                    }
                }
                else
                {
                    LogHelper.WriteReverseSynchronizeDBLogDetail(context.Log.LogID, item.SCObjectID, AttributeHelper.Hex((byte[])item.Tag.Properties["objectguid"][0]), item.CodeName, "未找到AD对象对应的权限中心对象。", null);
                }
            }
        }
Example #39
0
        public void SetupMetadata(CST.Global global)
        {
            NumWarnings = 0;
            NumErrors = 0;

            Global = global;

            if (tracerStream != null)
                Tracer = new CST.CSTWriter(global, CST.WriterStyle.Debug, tracerStream);

            Validity = new ValidityContext(this);

            GenericEnumeratorTypeConstructorRef = MkRef(Constants.GenericEnumeratorTypeConstructorName);
            JSContextRef = MkRef(Constants.JSContextName);
            JSObjectRef = MkRef(Constants.JSObjectName);
            JSPropertyRef = MkRef(Constants.JSPropertyName);
            JSExceptionRef = MkRef(Constants.JSExceptionName);

            GlobalMapping = new GlobalMapping(this);
            AttributeHelper = new AttributeHelper(this);
            InteropManager = new InteropManager(this);
            JSTHelpers = new JSTHelpers(this);
            InlinedMethods = new InlinedMethodCache(this);
            Traces = new Traces(this);
        }