标签: custom-attributes

如何将存储库传递给ASP.NET MVC中的authorize属性

我是Castle Windsor,它适用于控制器构造函数传递正在使用的存储库.

private IStoryRepository Repository;
public StoryController(IStoryRepository Repository)
{
    this.Repository = Repository;                   
}
Run Code Online (Sandbox Code Playgroud)

现在我在管理区域中有一个Action来显示主管理菜单.我使用了自定义授权属性,只检查登录用户是否为admin(只是users表中的isAdmin标志)

 [AdminAuthorize]
 public ActionResult Menu()

 private IStoryRepository Repository;
 /// <summary>
 /// Initializes a new instance of the <see cref="AdminAuthorizeAttribute"/> class.
 /// </summary>
 public AdminAuthorizeAttribute(IStoryRepository Repository)
 {
     this.Repository = Repository;
 }

 /// <summary>
 /// Checks if the user is authorised
 /// </summary>
 /// <param name="httpContext">The HTTP context.</param>
 /// <returns>
 ///    <c>true</c> if authorized; otherwise, <c>false</c>.
 /// </returns>
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {
    return this.Repository.UserIsAdmin(httpContext.User.Identity.Name);
 }
Run Code Online (Sandbox Code Playgroud)

如何让Castle将存储库传递给属性构造函数,就像它对控制器构造函数一样?

asp.net-mvc castle-windsor custom-attributes

5
推荐指数
1
解决办法
1672
查看次数

通过自定义属性生成其他代码

我仍然是C#的新手,我对属性有疑问.是否可以编写自定义属性,在编译时生成其他代码.例如:

[Forever]
public void MyMethod()
{
    // Code
}
Run Code Online (Sandbox Code Playgroud)

变成:

public void MyMethod()
{
    while (true)
    {
        // Code
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# attributes custom-attributes

5
推荐指数
1
解决办法
4128
查看次数

浏览器没有观察到data-*的变化,CSS属性选择器属性没有渲染

鉴于此CSS:

[data-myplugin-object="blue-window"]{
    background-color: #00f;
}

[data-myplugin-object="red-window"]{
    background-color: #f00;
}
Run Code Online (Sandbox Code Playgroud)

而这个jQuery:

$('[data-myplugin-object="blue-window"]').each(function(event){
    $(this).data({
        'myplugin-object': 'red-window'
    });
});
Run Code Online (Sandbox Code Playgroud)

这个HTML片段:

<div data-myplugin-object="blue-window">
    <p>Hello world</p>
</div>
Run Code Online (Sandbox Code Playgroud)

现在,人们会期望当jQuery片段被执行时(正确延迟到页面加载完成为止)我的蓝色窗口(最初呈现为蓝色)将变为红色.

不,它肯定没有; 并且分别在Firefox和Chrome中使用Firebug和开发者工具,我无法观察到data-*属性的任何变化.

为了使浏览器(以及DOM工具箱)能够观察到变化,我是否需要恢复.attr()或者是否有解决方法?

css jquery dom rendering custom-attributes

5
推荐指数
1
解决办法
1858
查看次数

来自属性的C#自定义属性

所以我有一个我想要循环的类的属性集合.对于每个属性,我可能有自定义属性,所以我想循环这些属性.在这种特殊情况下,我在City Class上有一个自定义属性

public class City
{   
    [ColumnName("OtroID")]
    public int CityID { get; set; }
    [Required(ErrorMessage = "Please Specify a City Name")]
    public string CityName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

该属性定义如此

[AttributeUsage(AttributeTargets.All)]
public class ColumnName : System.Attribute
{
    public readonly string ColumnMapName;
    public ColumnName(string _ColumnName)
    {
        this.ColumnMapName= _ColumnName;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试遍历属性[工作正常]然后循环遍历属性时,它只是忽略属性的for循环并且不返回任何内容.

foreach (PropertyInfo Property in PropCollection)
//Loop through the collection of properties
//This is important as this is how we match columns and Properties
{
    System.Attribute[] attrs = 
        System.Attribute.GetCustomAttributes(typeof(T));
    foreach (System.Attribute …
Run Code Online (Sandbox Code Playgroud)

c# asp.net reflection custom-attributes

5
推荐指数
2
解决办法
8579
查看次数

从配置文件中读取属性参数值

是否可以从配置文件加载属性值?例如,我的属性下面有缓存属性返回值.该属性在应用程序中使用了10次以上,我想从配置文件中加载第二个属性参数(1800秒).

[Cache(CacheType.Absolute, 1800, CacheLocation.Memory)]
Run Code Online (Sandbox Code Playgroud)

c# custom-attributes

5
推荐指数
1
解决办法
1178
查看次数

使用泛型方法获取我的枚举属性的List <string>

一开始,我们有这个基本的枚举.

public enum E_Levels {

    [ValueOfEnum("Low level")]
    LOW,

    [ValueOfEnum("Normal level")]
    NORMAL,

    [ValueOfEnum("High level")]
    HIGH
}
Run Code Online (Sandbox Code Playgroud)

而且我想得到List<string> 任何一个枚举.这样的东西Extensions.GetValuesOfEnum<E_Levels>()可以返回List<string>"低级别","正常级别"和"高级别".

StackOF帮助我获得了一个值属性:

public static class Extensions {

    public static string ToValueOfEnum(this Enum value) {

        FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
        ValueOfEnum[] attribs = fieldInfo.GetCustomAttributes(typeof(ValueOfEnum), false) as ValueOfEnum[];
        return attribs.Length > 0 ? attribs[0].value : null;
    }
}
Run Code Online (Sandbox Code Playgroud)

无论枚举如何,我都可以调用这种方法:E_Levels.LOW.ToValueOfEnum().

此外,StackOF帮助我获得了List<string>一个特定的枚举.我在控制器中制作了这个方法:

private List<string> GetLevels() {

List<string> levelsToReturn = new List<string>();
var levels = Enum.GetValues(typeof(E_Levels)).Cast<E_Levels>(); …
Run Code Online (Sandbox Code Playgroud)

c# generics enums custom-attributes

5
推荐指数
1
解决办法
5648
查看次数

创建C#属性以禁止方法执行

我希望创建一个自定义属性来抑制在C#中执行方法,即使它被调用.例如,在下面的代码块中,如果方法具有"跳过"属性,即使从Main调用它也不应该执行.

public class MyClass {

  public static void main()
  {
    aMethod();  
  }

  [Skip]
  public void aMethod() {
    ..
  }

}
Run Code Online (Sandbox Code Playgroud)

如何使用C#中的反射来实现这一目标?


在下面的代码片段中,我设法提取了带有Skip属性的方法,我无法弄清楚如何阻止它们执行!

MethodInfo[] methodInfos = typeof (MyClass).GetMethods();

foreach (var methodInfo in methodInfos)
{
  if (methodInfo.HasAttribute(typeof(SkipAttribute)))
  {
    // What goes here ??
  }
}
Run Code Online (Sandbox Code Playgroud)

我们非常欢迎任何有正确方向的帮助或建议:)

c# reflection custom-attributes methodinfo

5
推荐指数
1
解决办法
3432
查看次数

如何用反射获取枚举值的所有描述?

所以我需要List<string>从我的enum

到目前为止,这是我所做的:

枚举定义

    [Flags]
    public enum ContractorType
    {
        [Description("Recipient")]
        RECIPIENT = 1,
        [Description("Deliver")]
        DELIVER = 2,
        [Description("Recipient / Deliver")]
        RECIPIENT_DELIVER = 4
    }
Run Code Online (Sandbox Code Playgroud)

HelperClass与方法来做我需要的:

public static class EnumUtils
{
    public static IEnumerable<string> GetDescrptions(Type enumerator)
    {
        FieldInfo[] fi = enumerator.GetFields();

        List<DescriptionAttribute> attributes = new List<DescriptionAttribute>();
        foreach (var i in fi)
        {
            try
            {
                yield return attributes.Add(((DescriptionAttribute[])i.GetCustomAttributes(
                    typeof(DescriptionAttribute),
                    false))[0]);
            }
            catch { }
        }
        return new List<string>{"empty"};
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在我yield重视的那一行中,我得到了一个NullReferenceException。我错过了什么?语法对我来说似乎还不错,但也许我忽略了某些内容?

编辑: 我在这里使用.net Framework 4.0。

c# reflection ienumerable enums custom-attributes

5
推荐指数
3
解决办法
9290
查看次数

具有自定义属性的Android自定义视图

我已经制作了自定义视图,我想为它设置一些自定义属性.我想将另一个视图的id作为属性传递.

自定义视图attrs:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="IdNumber">
        <attr name="firstName" format="integer"/>
        <attr name="lastName" format="integer"/>
        <attr name="address" format="integer"/>
        <attr name="birthDate" format="integer"/>
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

我使用自定义视图的布局:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/display_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:layout_centerHorizontal="true"
        android:tag="name"
        android:ems="10" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/id_number"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/display_name"/>

    <ge.altasoft.custom_views.IdNumber
        android:id="@+id/custom_id_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/id_number"
        android:paddingLeft="35dip"
        custom:firstName="@id/display_name"/>


</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

自定义视图类的构造函数,我想获取属性值:

 public IdNumber (Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews();

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IdNumber);
        final int N = a.getIndexCount();
        for(int i …
Run Code Online (Sandbox Code Playgroud)

android view custom-attributes android-layout

5
推荐指数
1
解决办法
5214
查看次数

如何接受数据的"字典"作为自定义.NET属性参数?

我最近发现,一个.NET属性只能包含基本类型,字符串,枚举,对象和这些类型的单一参数数组作为讨论在这里.

我需要IDictionary<string, string>通过.NET属性接受,但显然我不能IDictionary<string, string>因为上述原因而使用.所以,我在这里寻找可以在这些指导方针中起作用的替代方案.

// I want to do this, but can't because of the CLR limitation
[MyAttribute(Attributes = new Dictionary { { "visibility", "Condition1" }, { "myAttribute", "some-value" } })]
Run Code Online (Sandbox Code Playgroud)

我提出的两个可能的选项是在声明中使用XMLJSON(作为.NET属性上的字符串),这可以很容易地IDictionary<string, string>为我的应用程序序列化,但是这会将声明变成一个冗长的容易出错的字符串没有语法检查.

// XML
[MyAttribute(Attributes = "<items><item key='visibility' value='Condition1'/><item key='myAttribute' value='some-value'/></items>")]

// JSON
[MyAttribute(Attributes = "{ 'visibility': 'Condition1', 'myAttribute': 'some-value' }")]
Run Code Online (Sandbox Code Playgroud)

如果有的话,还有哪些其他替代方案比这更优雅/更直接?

c# xml json custom-attributes

5
推荐指数
1
解决办法
2676
查看次数