コード例 #1
0
        private DiskGeometry ReadDiskGeometry(VhdPropertyAttribute attribute)
        {
            long offset = GetFooterOffset() + attribute.Offset;

            var attributeHelper = new AttributeHelper <DiskGeometry>();
            var diskGeometry    = new DiskGeometry();

            diskGeometry.Cylinder = dataReader.ReadInt16(offset + attributeHelper.GetAttribute(() => diskGeometry.Cylinder).Offset);
            diskGeometry.Heads    = dataReader.ReadByte(offset + attributeHelper.GetAttribute(() => diskGeometry.Heads).Offset);
            diskGeometry.Sectors  = dataReader.ReadByte(offset + attributeHelper.GetAttribute(() => diskGeometry.Sectors).Offset);
            return(diskGeometry);
        }
コード例 #2
0
        public ParentLocator Create()
        {
            var locator = new ParentLocator();

            locator.PlatformCode                = ReadPlaformCode(attributeHelper.GetAttribute(() => locator.PlatformCode));
            locator.PlatformDataSpace           = ReadPlatformDataSpace(attributeHelper.GetAttribute(() => locator.PlatformDataSpace));
            locator.PlatformDataLength          = ReadPlatformDataLength(attributeHelper.GetAttribute(() => locator.PlatformDataLength));
            locator.Reserved                    = ReadReserved(attributeHelper.GetAttribute(() => locator.Reserved));
            locator.PlatformDataOffset          = ReadPlatformDataOffset(attributeHelper.GetAttribute(() => locator.PlatformDataOffset));
            locator.PlatformSpecificFileLocator = ReadFileLocator(locator);
            return(locator);
        }
コード例 #3
0
        public MetaData GetMetaData(object listModel)
        {
            var metadata = new MetaData();

            var fieldUpdates = listModel.GetType()
                               .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty)
                               .Select(propertyInfo =>
            {
                var attribute = AttributeHelper.GetAttribute <SPFieldAttribute>(propertyInfo);
                return(propertyInfo, attribute);
            })
                               .Where(tuple => tuple.attribute != null)
                               .Select(tuple => ToFieldUpdateType(listModel, tuple.propertyInfo, tuple.attribute))
                               .Where(fieldUpate => fieldUpate != null)
                               .GroupBy(x => x.GetType())
                               .ToDictionary(group => group.Key, group => group.ToList());

            if (fieldUpdates.ContainsKey(typeof(FieldUpdate)))
            {
                metadata.UpdateValues = fieldUpdates[typeof(FieldUpdate)].Cast <IFieldUpdate>().ToList();
            }

            if (fieldUpdates.ContainsKey(typeof(LookupFieldUpdate)))
            {
                metadata.LookupFields = fieldUpdates[typeof(LookupFieldUpdate)].Cast <ILookupFieldUpdate>().ToList();
            }

            return(metadata);
        }
コード例 #4
0
        private void WriteLabel(TextWriter writer)
        {
            var IsDisplayed = !AttributeHelper.IsAttributeDefined <NoDisplayNameAttribute>(
                For.ModelExplorer.Metadata.ContainerType,
                For.ModelExplorer.Metadata.PropertyName);

            if (IsDisplayed)
            {
                bool IsSubItem = AttributeHelper.IsAttributeDefined <SubItemAttribute>(
                    For.ModelExplorer.Metadata.ContainerType,
                    For.ModelExplorer.Metadata.PropertyName);

                TagBuilder tagBuilder = GenerateLabel(IsSubItem);

                if (For.ModelExplorer.Metadata.IsRequired ||
                    (((RequiredCheckedAttribute)AttributeHelper
                      .GetAttribute <RequiredCheckedAttribute>(For.ModelExplorer.Metadata.ContainerType,
                                                               For.ModelExplorer.Metadata.PropertyName))?.Min > 0) ||
                    (((RequiredIfAttribute)AttributeHelper
                      .GetAttribute <RequiredIfAttribute>(For.ModelExplorer.Metadata.ContainerType,
                                                          For.ModelExplorer.Metadata.PropertyName))?.AlwaysDisplayRequiredStar == true))
                {
                    tagBuilder.InnerHtml.AppendHtml(RequiredStarSpan);
                }
                WritePrefix(writer, PrefixAttribute.Position.Label);
                tagBuilder.WriteTo(writer, _htmlEncoder);

                WriteInfoIfDescription(writer);
                WriteHelpIfHelpLink(writer);
            }
        }
コード例 #5
0
        private object LoadItem(string path, string key, Type itemType, IICIndex <IICConfigItemBuffer> index)
        {
            IICConfigItemAttribute itemAttr = AttributeHelper.GetAttribute <IICConfigItemAttribute>(itemType);
            object ret = Activator.CreateInstance(itemType);

            foreach (FieldInfo field in itemType.GetFields())
            {
                IICConfigFieldAttribute fieldAttr = AttributeHelper.TryGetAttribute <IICConfigFieldAttribute>(field);
                if (fieldAttr != null)
                {
                    IICConfigItemBuffer buffer = index.TryFindOne(path, key, fieldAttr.FieldName);
                    if (buffer != null)
                    {
                        ObjectHelper.SetValue(field, ret, buffer.Value, field.FieldType);
                    }
                    else if (fieldAttr.DefaultValue != null)
                    {
                        ObjectHelper.SetValue(field, ret, fieldAttr.DefaultValue);
                    }
                    else
                    {
                        throw new ConfigurationNotFoundException(path, key, field.Name);
                    }
                }
            }
            return(ret);
        }
コード例 #6
0
        /// <summary>
        /// 通过实体类型获取实体信息
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public EntityInfo GetEntity(Type type)
        {
            EntityInfo entityInfo = null;

            if (!_entityInfos.TryGetValue(type, out entityInfo))
            {
                lock (_entityLocker)
                {
                    entityInfo           = new EntityInfo();
                    entityInfo.TableName = ExpressionUtil.GetEntityTableName(type);
                    if (string.IsNullOrWhiteSpace(entityInfo.TableName))
                    {
                        throw new Exception("实体必须标明TableAttribute");
                    }
                    entityInfo.EntityType = type;

                    var pis = ExpressionReflector.GetProperties(type).Values;
                    foreach (var property in pis)
                    {
                        var foreignKeyAttr = AttributeHelper.GetAttribute <ForeignKeyAttribute>(property);
                        if (foreignKeyAttr != null)
                        {
                            entityInfo.ForeignKeys.Add(property);
                        }
                        entityInfo.Properties.Add(property);
                    }

                    _entityInfos.Add(type, entityInfo);
                }
            }

            return(entityInfo);
        }
コード例 #7
0
        public static VhdFooter CreateFixedDiskFooter(long virtualSize)
        {
            var helper            = new AttributeHelper <VhdFooter>();
            var footer            = new VhdFooter();
            var reservedAttribute = helper.GetAttribute(() => footer.Reserved);

            footer.Cookie             = VhdCookie.CreateFooterCookie();
            footer.Features           = VhdFeature.Reserved;
            footer.FileFormatVersion  = VhdFileFormatVersion.DefaultFileFormatVersion;
            footer.HeaderOffset       = VhdConstants.VHD_NO_DATA_LONG;
            footer.TimeStamp          = DateTime.UtcNow;
            footer.CreatorApplication = WindowsAzureCreatorApplicationName;
            footer.CreatorVersion     = VhdCreatorVersion.CSUP2011;
            footer.CreatorHostOsType  = HostOsType.Windows;
            footer.PhsyicalSize       = virtualSize;
            footer.VirtualSize        = virtualSize;
            footer.DiskGeometry       = DiskGeometry.CreateFromVirtualSize(virtualSize);
            footer.DiskType           = DiskType.Fixed;
            footer.UniqueId           = Guid.NewGuid();
            footer.SavedState         = false;
            footer.Reserved           = new byte[reservedAttribute.Size];

            var footerSerializer = new VhdFooterSerializer(footer);
            var byteArray        = footerSerializer.ToByteArray();

            using (var memoryStream = new MemoryStream(byteArray))
            {
                var binaryReader  = new BinaryReader(memoryStream);
                var vhdDataReader = new VhdDataReader(binaryReader);
                var footerFactory = new VhdFooterFactory(vhdDataReader);
                var vhdFooter     = footerFactory.CreateFooter();
                return(vhdFooter);
            }
        }
コード例 #8
0
        private void ExcuteExHandle(IInvocation invocation, Exception ex)
        {
            ExHandleAttribute attribute = AttributeHelper.GetAttribute <ExHandleAttribute>(invocation) as ExHandleAttribute;

            if (attribute == null)
            {
                if (ex != null)
                {
                    throw ex;
                }
                else
                {
                    return;
                }
            }
            if (attribute.IsLog)
            {
                if (LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("{0} {1} -----EXHandle ", "Exception", InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel, ex);
                }
            }
            if (attribute.IsThrow)
            {
                throw ex;
            }
            //若忽略则什么都不做
            if (attribute.IsIgnore)
            {
                return;
            }
        }
コード例 #9
0
        /// <summary>
        /// Tries the read expected exception.
        /// </summary>
        /// <param name="target">
        /// The method.
        /// </param>
        /// <param name="exceptionType">
        /// Type of the exception.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override bool TryReadExpectedException(ICustomAttributeProviderEx target, out TypeEx exceptionType)
        {
            var attribute = AttributeHelper.GetAttribute(target, ExpectedExceptionAttribute);

            if (attribute != null)
            {
                var attributeType = attribute.GetType();

                // read exception type using reflection.
                var field = attributeType.GetField("expectedException", BindingFlags.NonPublic | BindingFlags.Instance);
                if (field != null)
                {
                    var  t = field.GetValue(attribute) as Type;
                    bool isClass;
                    if (t != null && ReflectionHelper.TryGetIsClass(t, out isClass) && isClass &&
                        !ReflectionHelper.ContainsGenericParameters(t))
                    {
                        exceptionType = MetadataFromReflection.GetType(t);
                        return(true);
                    }
                }
            }

            exceptionType = null;
            return(false);
        }
コード例 #10
0
        public SPListInfo(Type type, Uri uri)
        {
            var spListAttribute = AttributeHelper.GetAttribute <SPListAttribute>(type);

            if (spListAttribute == null)
            {
                throw new ArgumentException($"The type '{type}' does not specify the attribute '{typeof(SPListAttribute)}'!", nameof(type));
            }

            this.ListAlias         = spListAttribute.Name;
            this.IsDocumentLibrary = spListAttribute.Type == SPListAttribute.ListType.DocumentLibrary;
            this.HasAttachments    = GetAttachmentsProperty(type) != null;

            if (IsDocumentLibrary)
            {
                this.documentFunc = new Lazy <Func <object, IDocument> >(() =>
                {
                    var documentProperty = GetDocumentProperty(this.Type);
                    return(obj => (IDocument)documentProperty.GetValue(obj));
                });
            }

            if (HasAttachments)
            {
                this.attachmentsFunc = new Lazy <Func <object, IEnumerable <IDocument> > >(() =>
                {
                    var attachmentsProperty = GetAttachmentsProperty(this.Type);
                    return(obj => (IEnumerable <IDocument>)attachmentsProperty.GetValue(obj));
                });
            }

            this.Type    = type;
            this.ListUri = uri;
        }
コード例 #11
0
        private void WriteRadioGroup(TextWriter writer)
        {
            var IsDisplayed = !AttributeHelper.IsAttributeDefined <NoDisplayNameAttribute>(
                For.ModelExplorer.Metadata.ContainerType,
                For.ModelExplorer.Metadata.PropertyName);

            var id = IdOverride ?? For.Name;

            string checkedValue = (string.IsNullOrWhiteSpace(CheckedValue) || CheckedValue == "none") ? string.Empty : CheckedValue;

            if (IsDisplayed)
            {
                writer.WriteLine($"<fieldset id=\"{id}\">");
                writer.WriteLine($"<legend>{LabelOverride ?? For.ModelExplorer.Metadata.DisplayName}");
                if (For.ModelExplorer.Metadata.IsRequired ||
                    (((RequiredCheckedAttribute)AttributeHelper
                      .GetAttribute <RequiredCheckedAttribute>(For.ModelExplorer.Metadata.ContainerType,
                                                               For.ModelExplorer.Metadata.PropertyName))?.Min > 0))
                {
                    writer.WriteLine(RequiredStarSpan);
                }
                writer.WriteLine(InformationSpan.FormatSwedish(For.ModelExplorer.Metadata.Description));
                if (!string.IsNullOrEmpty(HelpLink))
                {
                    writer.WriteLine(HelpAnchor.FormatSwedish(HelpLink));
                }
                writer.WriteLine("</legend>");
            }
            bool isRow = LayoutOption == "row";

            var itArr = Items.ToArray();

            for (int i = 0; i < itArr.Length; i++)
            {
                var  item                 = itArr[i];
                var  itemName             = $"{id}_{i}";
                bool valueShouldBeChecked = !string.IsNullOrWhiteSpace(checkedValue) && item.Value == checkedValue;
                var  checkedAttr          = valueShouldBeChecked ? "checked=\"checked\"" : "";
                // Done manually because GenerateRadioButton automatically sets id=For.Name, which it shouldn't
                var inputElem = $"<input id=\"{itemName}\" name=\"{For.Name}\" type=\"radio\" value=\"{item.Value}\" {checkedAttr}/>";

                if (isRow)
                {
                    writer.WriteLine($"<label for=\"{itemName}\">");
                    WritePrefix(writer, PrefixAttribute.Position.Value);
                    writer.WriteLine(inputElem);
                    writer.WriteLine($"{item.Text}</label>");
                }
                else
                {
                    writer.WriteLine($"<label for=\"{itemName}\" class=\"radiocontainer\"> ");
                    WritePrefix(writer, PrefixAttribute.Position.Value);
                    writer.WriteLine(inputElem);
                    writer.WriteLine($"<span class=\"checkmark\"></span> <span class=\"radio-text\">{item.Text}</span ></label><br><div class=\"radiobutton-row-space\"></div>");
                }
            }
            writer.WriteLine($"</fieldset>"); //groupId
        }
コード例 #12
0
ファイル: KerppiMain.xaml.cs プロジェクト: ohel/kerppi
 private void About(object sender, RoutedEventArgs e)
 {
     MessageBox.Show(
         AttributeHelper.GetAttribute <System.Reflection.AssemblyProductAttribute>().Product + Environment.NewLine +
         "Versio: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + Environment.NewLine +
         AttributeHelper.GetAttribute <System.Reflection.AssemblyCopyrightAttribute>().Copyright + Environment.NewLine +
         "Lisenssi- ja loppukäyttäjäehdot löytyvät tiedostosta Kerppi.txt",
         "Tietoa sovelluksesta", MessageBoxButton.OK, MessageBoxImage.Information);
 }
コード例 #13
0
ファイル: MiscSetting.xaml.cs プロジェクト: ohel/kerppi
        public MiscSetting(string miscTableKey, string description)
        {
            InitializeComponent();
            Title = AttributeHelper.GetAttribute <System.Reflection.AssemblyProductAttribute>().Product;

            key = miscTableKey;
            textBlockDescription.Text = description;
            textBoxValue.Text         = DBHandler.QueryMisc(miscTableKey);
            textBoxValue.Focus();
        }
コード例 #14
0
 public ListRestrictedClients(Action callback)
 {
     InitializeComponent();
     Title       = AttributeHelper.GetAttribute <System.Reflection.AssemblyProductAttribute>().Product;
     DataContext = DataModel.Client.LoadAllRestricted()
                   .Select(c => new ClientListItem {
         Name = c.Name, IdCode = c.IdCode, Id = c.Id
     })
                   .ToList();
     _callback = callback;
 }
コード例 #15
0
        private static IPluginMetadata GetPluginMetadata(Type pluginType)
        {
            var metadata = AttributeHelper.GetAttribute <MapWindowPluginAttribute>(pluginType) as IPluginMetadata;

            if (metadata == null)
            {
                throw new ApplicationException("Plugin type must be decorated with MapWindowPluginAttribute.");
            }

            return(metadata);
        }
コード例 #16
0
        /// <summary>
        /// Gets MVP presenter to display UI for the tool.
        /// </summary>
        public static IPresenter <ToolViewModel> GetPresenter(this ITool tool, IAppContext context)
        {
            var attr = AttributeHelper.GetAttribute <GisToolAttribute>(tool.GetType());

            if (attr.PresenterType != null)
            {
                return(context.Container.GetInstance(attr.PresenterType) as IPresenter <ToolViewModel>);
            }

            return(context.Container.GetInstance <ToolPresenter>());
        }
コード例 #17
0
        private void WritePrefix(TextWriter writer, PrefixAttribute.Position condition)
        {
            var Prefix = (PrefixAttribute)AttributeHelper.GetAttribute <PrefixAttribute>(
                For.ModelExplorer.Metadata.ContainerType,
                For.ModelExplorer.Metadata.PropertyName);

            if (Prefix != null && Prefix.PrefixPosition == condition)
            {
                writer.WriteLine(Prefix.Text);
            }
        }
コード例 #18
0
 static CompanyRepository()
 {
     TableName  = AttributeHelper.GetAttribute <Company, TableAttribute>().Name;
     IdField    = AttributeHelper.GetAttribute <Company, ColumnAttribute>(nameof(Company.ID)).Name;
     TitleField = AttributeHelper.GetAttribute <Company, ColumnAttribute>(nameof(Company.Title)).Name;
     OrganizationalFormField = AttributeHelper.GetAttribute <Company, ColumnAttribute>(nameof(Company.OrganizationalForm)).Name;
     SelectAllCommand        = String.Format("select {0}, {1}, {2} from {3}", IdField, TitleField, OrganizationalFormField, TableName);
     SelectByIdCommand       = String.Format("{0} where {1}={2}", SelectAllCommand, IdField, "{0}");
     SelectByAllFieldCommand = String.Format("{0} where {1}='{2}' and {3}='{4}'", SelectAllCommand, TitleField, "{0}", OrganizationalFormField, "{1}");
     DeleteCommand           = String.Format("DELETE FROM {0} WHERE {1}='{2}'", TableName, IdField, "{0}");
     InsertCommand           = String.Format("INSERT INTO {0} ({1},{2}) values ('{3}', '{4}')", TableName, TitleField, OrganizationalFormField, "{0}", "{1}");
     UpdateCommand           = String.Format("UPDATE {0} SET {1}='{2}', {3}='{4}' where {5}='{6}'", TableName, TitleField, "{0}", OrganizationalFormField, "{1}", IdField, "{2}");
 }
コード例 #19
0
 private void Init(string name, BinaryColumnTypeOption dataType, int size)
 {
     this.name     = name;
     this.dataType = dataType;
     if (dataType == BinaryColumnTypeOption.String)
     {
         this.size = size;
     }
     else
     {
         this.size = AttributeHelper.GetAttribute <BinaryColumnTypeIdentity>(dataType).Size;
     }
 }
コード例 #20
0
ファイル: RpcClientInterface.cs プロジェクト: ilahsa/bai_pro
        public RpcClientInterface(Type intf)
        {
            if (!intf.IsInterface)
            {
                throw new NotSupportedException();
            }

            RpcServiceAttribute serviceAttr = AttributeHelper.GetAttribute <RpcServiceAttribute>(intf);

            ServiceName    = serviceAttr.ServiceName;
            ClientCheck    = serviceAttr.ClientChecking;
            EnableCounters = serviceAttr.EnableCounters;
            _methods       = new HybridDictionary <string, RpcClientMethodSensor>();

            foreach (MethodInfo method in intf.GetMethods())
            {
                RpcClientMethodSensor m;
                string methodName = method.Name;

                RpcServiceBatchMethodAttribute battr = AttributeHelper.TryGetAttribute <RpcServiceBatchMethodAttribute>(method);
                if (battr != null)
                {
                    if (!string.IsNullOrEmpty(battr.MethodName))
                    {
                        methodName = battr.MethodName;
                    }

                    m = new RpcClientMethodSensor()
                    {
                        ArgsType     = battr.ArgsType,
                        BatchManager = new RpcClientBatchManager(battr.BatchCount, battr.IdleMs)
                    };
                }
                else
                {
                    RpcServiceMethodAttribute attr = AttributeHelper.GetAttribute <RpcServiceMethodAttribute>(method);

                    if (!string.IsNullOrEmpty(attr.MethodName))
                    {
                        methodName = battr.MethodName;
                    }

                    m = new RpcClientMethodSensor()
                    {
                        ArgsType     = attr.ArgsType,
                        BatchManager = null
                    };
                }
                _methods.Add(methodName, m);
            }
        }
コード例 #21
0
        private bool tryAccess(IInvocation invocation)
        {
            PermissionPointAttribute attribute = AttributeHelper.GetAttribute <PermissionPointAttribute>(invocation) as PermissionPointAttribute;

            if (attribute == null)
            {
                return(true);
            }
            string strLogHeader = "Access accepted";

            try
            {
                IPermissionPointResolve resolve = IocCoreFactory.Get <IPermissionPointResolve>(attribute.ResolveType);
                PermissionPoint         point   = new DefaultPermissionPoint(attribute,
                                                                             InterceptorHelper.GetInvocationTarget(invocation),
                                                                             InterceptorHelper.GetInvocationMethod(invocation) as MemberInfo,
                                                                             InterceptorHelper.GetInvocationMethodArgs(invocation)) as PermissionPoint;
                PermissionInfo info = resolve.Resolve(point);
                info++;
                if (attribute.IsAcceptLog && LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("{0} {1} {2} {3}-----Access Log ", strLogHeader, PrincipalTokenHolder.CurrentPrincipal.ToString(), attribute.ToString(), InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel);
                }
            }
            catch (AccessException ex)
            {
                strLogHeader = "Access Denied";
                if (attribute.IsAcceptLog && LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("{0} {1} {2} {3}-----Access Log ", strLogHeader, PrincipalTokenHolder.CurrentPrincipal.ToString(), attribute.ToString(), InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel, ex);
                }
                if (attribute.IsAlert)
                {
                    Console.WriteLine("Access diny alert!");
                }
                if (attribute.IsThrow)
                {
                    throw ex;
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
コード例 #22
0
ファイル: CacheInterceptor.cs プロジェクト: lyllylyq/IocCore
        public override void Intercept(IInvocation invocation)
        {
            CacheAttribute attribute = AttributeHelper.GetAttribute <CacheAttribute>(invocation) as CacheAttribute;

            attribute.Key = getKey(invocation, attribute);
            ICache cache     = IocCoreFactory.Get <ICache>();
            object cacheData = cache.Get(attribute.Key);

            if (cacheData != null)
            {
                invocation.ReturnValue = cacheData;
                if (LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("Cache Hit! Key:\"{0}\" Caller:{1}", attribute.Key, InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel);
                }
                return;
            }
            IDependencyWrapper dependency;

            if (!String.IsNullOrWhiteSpace(attribute.DependencyCallback))
            {
                dependency = getDependency(invocation, attribute);
            }
            else
            {
                dependency = null;
            }
            invocation.Proceed();
            if (dependency != null)
            {
                object     returnValue       = invocation.ReturnValue;
                MethodInfo onRemovedCallback = invocation.TargetType.GetMethod(attribute.OnRemovedCallback);
                cache.Insert(
                    attribute.Key,
                    returnValue,
                    dependency.Instance,
                    attribute.Absolute,
                    attribute.Sliding,
                    (int)attribute.Priority,
                    onRemovedCallback);
                if (LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("Cache Insert! Key:\"{0}\" Caller:{1}", attribute.Key, InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel);
                }
            }
        }
コード例 #23
0
        private IEnumerable <CompletionPort> ReadDiskGeometryAsync(AsyncMachine <DiskGeometry> machine, VhdPropertyAttribute attribute)
        {
            long offset = GetFooterOffset() + attribute.Offset;

            var attributeHelper = new AttributeHelper <DiskGeometry>();
            var diskGeometry    = new DiskGeometry();

            dataReader.BeginReadInt16(offset + attributeHelper.GetAttribute(() => diskGeometry.Cylinder).Offset, machine.CompletionCallback, null);
            yield return(CompletionPort.SingleOperation);

            diskGeometry.Cylinder = dataReader.EndReadInt16(machine.CompletionResult);

            dataReader.BeginReadByte(offset + attributeHelper.GetAttribute(() => diskGeometry.Heads).Offset, machine.CompletionCallback, null);
            yield return(CompletionPort.SingleOperation);

            diskGeometry.Heads = dataReader.EndReadByte(machine.CompletionResult);

            dataReader.BeginReadByte(offset + attributeHelper.GetAttribute(() => diskGeometry.Sectors).Offset, machine.CompletionCallback, null);
            yield return(CompletionPort.SingleOperation);

            diskGeometry.Sectors = dataReader.EndReadByte(machine.CompletionResult);

            machine.ParameterValue = diskGeometry;
        }
コード例 #24
0
        private void PostProceed(IInvocation invocation)
        {
            LogAttribute attribute = AttributeHelper.GetAttribute <LogAttribute>(invocation) as LogAttribute;

            if (attribute != null && attribute.IsPostLog)
            {
                //拦截器log屏蔽
                if (LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("{0} -----Post log", InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel);
                }
            }
        }
コード例 #25
0
        public static string GetCacheKey <T>(T item)
        {
            if (item == null)
            {
                return(string.Empty);
            }

            // Step 1. Get CacheAttributes
            CacheAttribute cacheAttribute = AttributeHelper.GetAttribute <CacheAttribute>(item.GetType());

            if (cacheAttribute == null)
            {
                throw new NotImplementedException($"CacheAttribute not found for type [{item.GetType().Name}].");
            }

            return(cacheAttribute.GetCacheKey(item));
        }
コード例 #26
0
ファイル: MapCollector.cs プロジェクト: hello-web/EasySmartQQ
        public void CollectMapInfo(Type objectType)
        {
            var tableAttr = AttributeHelper.GetAttribute <TableMapAttribute>(objectType, true);

            if (tableAttr == null)
            {
                throw new Exception(string.Format("type [{0}] dose not bind [TableMapAttribute] attribute", objectType.Name));
            }
            var  properties        = AttributeHelper.GetProperties(objectType);
            bool hasPrimaryKeyAttr = false;

            foreach (var property in properties)
            {
                var primaryKeyAttr = AttributeHelper.GetPropertyAttribute <PrimaryKeyAttribute>(property);
                if (primaryKeyAttr != null)
                {
                    hasPrimaryKeyAttr        = true;
                    tableAttr.PrimaryKeyInfo = primaryKeyAttr;
                }
                else
                {
                    var propertyAttr = AttributeHelper.GetPropertyAttribute <PropertyFieldMapAttribute>(property);
                    if (propertyAttr != null)
                    {
                        tableAttr.Maps.Add(propertyAttr.PropertyName, new TableObjectMapInfo()
                        {
                            PropertyName = propertyAttr.PropertyName,
                            PropertyType = propertyAttr.PropertyType,
                            FieldName    = propertyAttr.FieldName,
                            FieldType    = propertyAttr.FieldType
                        });
                    }
                }
            }
            if (hasPrimaryKeyAttr)
            {
                OrmMapCache.Instance.OrmMap.Add(objectType, tableAttr);
            }
            else
            {
                throw new Exception(string.Format("type [{0}] has no one property that binds [PrimaryKeyAttribute] attribute", objectType.Name));
            }
        }
コード例 #27
0
        private T LoadSection <T>(string sectionName, IICIndex <IICConfigItemBuffer> index) where T : IICConfigSection
        {
            IICConfigSectionAttribute sectionAttr = AttributeHelper.GetAttribute <IICConfigSectionAttribute>(typeof(T));
            T section = Activator.CreateInstance <T>();

            foreach (FieldInfo field in typeof(T).GetFields())
            {
                IICConfigFieldAttribute fieldAttr = AttributeHelper.TryGetAttribute <IICConfigFieldAttribute>(field);
                if (fieldAttr != null)
                {
                    IICConfigItemBuffer item = index.TryFindOne(sectionAttr.SectionName, string.Empty, fieldAttr.FieldName);
                    if (item != null)
                    {
                        ObjectHelper.SetValue(field, section, item.Value, field.FieldType);
                    }
                    else
                    {
                        ObjectHelper.SetValue(field, section, fieldAttr.DefaultValue);
                    }
                    continue;
                }

                IICConfigItemAttribute itemAttr = AttributeHelper.TryGetAttribute <IICConfigItemAttribute>(field);
                if (itemAttr != null)
                {
                    object item = LoadItem(sectionName + "." + itemAttr.ItemName, string.Empty, field.FieldType, index);
                    field.SetValue(section, item);
                    continue;
                }

                IICConfigItemCollectionAttribute colletionAttr = AttributeHelper.TryGetAttribute <IICConfigItemCollectionAttribute>(field);
                if (colletionAttr != null)
                {
                    Type[]            types      = field.FieldType.GetGenericArguments();
                    Type              keyType    = types[0];
                    Type              itemType   = types[1];
                    IConfigCollection collection = LoadCollection(sectionName + "." + colletionAttr.ItemName, keyType, itemType, field.FieldType, index);
                    field.SetValue(section, collection);
                    continue;
                }
            }
            return(section);
        }
コード例 #28
0
        private void WriteTextArea(TextWriter writer)
        {
            var tagBuilder = _htmlGenerator.GenerateTextArea(
                ViewContext,
                For.ModelExplorer,
                For.Name,
                rows: 5,
                columns: 80,
                htmlAttributes: new { @class = "form-control" });
            var placeholderAttribute = (PlaceholderAttribute)AttributeHelper.GetAttribute <PlaceholderAttribute>(
                For.ModelExplorer.Metadata.ContainerType,
                For.ModelExplorer.Metadata.PropertyName);

            if (placeholderAttribute != null)
            {
                tagBuilder.Attributes.Add("placeholder", placeholderAttribute.Text);
            }
            WritePrefix(writer, PrefixAttribute.Position.Value);
            tagBuilder.WriteTo(writer, _htmlEncoder);
        }
コード例 #29
0
ファイル: AyxContainer.cs プロジェクト: shuiliangzi/AvalonDI
        private void InjectPropertyDependency(object o)
        {
            foreach (var property in o.GetType().GetProperties())
            {
                if (property.PropertyType.IsValueType)
                {
                    continue;
                }
                var attr = AttributeHelper.GetAttribute <AutoInjectAttribute>(property);
                if (attr == null)
                {
                    continue;
                }
                if (property.GetValue(o, null) != null)
                {
                    continue;
                }

                var valueType     = property.PropertyType;
                var propertyValue = Get(valueType, attr.Token);
                property.SetValue(o, propertyValue, null);
            }
        }
コード例 #30
0
        private void WriteInput(TextWriter writer)
        {
            bool IsNoAutoComplete = AttributeHelper.IsAttributeDefined <NoAutoCompleteAttribute>(
                For.ModelExplorer.Metadata.ContainerType,
                For.ModelExplorer.Metadata.PropertyName);

            var tagBuilder = _htmlGenerator.GenerateTextBox(
                ViewContext,
                For.ModelExplorer,
                For.Name,
                value: For.Model,
                format: null,
                htmlAttributes: new { @class = (IsNoAutoComplete && string.IsNullOrEmpty(For.Model?.ToString())) ? "form-control no-auto-complete" : "form-control" });
            var placeholderAttribute = (PlaceholderAttribute)AttributeHelper.GetAttribute <PlaceholderAttribute>(
                For.ModelExplorer.Metadata.ContainerType,
                For.ModelExplorer.Metadata.PropertyName);

            if (placeholderAttribute != null)
            {
                tagBuilder.Attributes.Add("placeholder", placeholderAttribute.Text);
            }
            //The regular expressions are not added as client side valdations for some reason.
            // Remove this code if this is fixed in future versions of .Net Core, or by some better setup of things that I have not found....
            if (For.Metadata.ValidatorMetadata.SingleOrDefault(m => m.GetType() == typeof(RegularExpressionAttribute)) is RegularExpressionAttribute regex &&
                !tagBuilder.Attributes.Any(a => a.Key == "data-val-regex"))
            {
                tagBuilder.Attributes.Add("data-val-regex", regex.ErrorMessage);
                tagBuilder.Attributes.Add("data-val-regex-pattern", regex.Pattern);
            }
            // This is how we override unobtrusive validation error messages, because globaLIES.js is not doing what we expect it to.
            if (tagBuilder.Attributes.Any(a => a.Key == "data-val-number"))
            {
                tagBuilder.Attributes["data-val-number"] = $"Fältet {For.Metadata.DisplayName} får endast innehålla siffror.";
            }
            WritePrefix(writer, PrefixAttribute.Position.Value);
            tagBuilder.WriteTo(writer, _htmlEncoder);
        }