I am trying to access a custom attribute applied to a method within a castle interceptor, but method Attribute.GetCustomAttribute() return null.
public class MyIntecept : Castle.DynamicProxy.IInterceptor
{
public void Intercept(IInvocation invocation)
{
// myAttr is null.
var myAttr = (MyAttribute)Attribute.GetCustomAttribute(
invocation.Method, typeof(MyAttribute));
}
}
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)]
public class MyAttribute : Attribute
{
readonly string _value;
public MyAttribute(string value)
{
this._value = value;
}
public string Value
{
get { return this._value; }
}
}
public interface IMyInterface
{
void Do();
}
public class MyClass : IMyInterface
{
[MyAttribute("MyValue")]
public void Do()
{
Console.WriteLine("Do");
}
}
How can i get 'MyAttribute'?
P.S. I'am using Castle.Core 3.3.3
Put the attribute "MyAttribute" on the method inside the interface and not inside the class
Related
When I bind data with custom controller, the following code works well.
public class searchContactCtrl {
String searchText;
public String getSearchText(){
return searchText;
}
public void setSearchText(String s ){
searchText =s;
}
}
but if I changed getter method of "searchText" as below, an error was occured.
public class searchContactCtrl {
public String searchText{get;}
public void setSearchText(String s ){
searchText =s;
}
}
Error message:
Compile Error: member variable not visible for assignment
Why is this happening?
You will need to define a private setter for the searchText property. E.g.
public class searchContactCtrl {
public String searchText {
get;
private set;
}
public void setSearchText(String s) {
searchText = s;
}
}
Or you could just remove the private modifier and directly set searchText without the setSearchText method.
I have a sample application that shows how to host Nancy on node.js.
To do that I need to change the rootpath. I ended up with something like that:
public class Startup
{
public static void Configuration(IAppBuilder app)
{
string rootpath = app.Properties["node.rootpath"] as string;
app.UseNancy(options => options.Bootstrapper = new NodeBootstrapper(rootpath));
}
}
public class NodeRootPathProvider : IRootPathProvider
{
private string rootpath;
public NodeRootPathProvider(string rootpath)
{
this.rootpath = rootpath;
}
public string GetRootPath()
{
return this.rootpath;
}
}
public class NodeBootstrapper : DefaultNancyBootstrapper
{
private string rootpath;
public NodeBootstrapper(string rootpath)
: base()
{
this.rootpath = rootpath;
}
protected override IRootPathProvider RootPathProvider
{
get { return new NodeRootPathProvider(this.rootpath); }
}
}
Is there a way to simplfy this?
In my custom control I have 3 properties(State,Value,Count), State property with Enum(Dock,Float,Tab), if the Enum value(Float) means I want to Hide(Browsable False) Value property in WPF. Is there any possibility to do this with PropertyChanged of the State.
In the setter for State, just check what the value is. If it's Float hide, else unhide.
private StateEnum _state;
public StateEnum State {
get { return _state; }
set
{
if (value == StateEnum.Float)
{
// Hide stuff
}
else
{
// Show stuff
}
name = value;
}
}
Normally you cannot hide a property conditionally.
However, there is a trick.
You can define a value interface and wrapper for your value property and implement for value and nonvalue states.
Example:
public interface IValueWrapper {}
public class BasicValueWrapper : IValueWrapper
{
public int Value { get; set; }
}
public class NoneValueWrapper : IValueWrapper {}
Main Class :
public class MainClass
{
private StateEnum _state;
public StateEnum State {
get { return _state; }
set
{
if (value == StateEnum.Float)
{
// Hide stuff
this.Value= new NoneValueWrapper();
}
else
{
// Show stuff
this.Value= new BasicValueWrapper();
}
name = value;
}
}
public IValueWrapper Value { get; set; }
}
I'm trying to use the [TypeDescriptionProviderAttribute] in order to give my class a custom type descriptor. This works, but when I implement INotifyPropertyChanged WPF seems to ignore the custom type descriptor and go straight for the CLR property (if it exists). Here's a snippet, I'll paste the full example later on:
//[TypeDescriptionProvider(typeof(MyProvider))]
class MyModel : Object
//, INotifyPropertyChanged
//, ICustomTypeDescriptor
{
public string TheProperty { get { return "CLR - TheProperty"; } }
I bind a TextBlock to TheProperty. When I...
Leave everything commented
I see "CLR - TheProperty" as expected.
Use [TypeDescriptionProvider]
I see "MyPropertyDescriptor - TheProperty" as expected.
Use ICustomTypeDescriptor
I see "MyPropertyDescriptor - TheProperty" as expected.
Use ICustomTypeDescriptor and INotifyPropertyChanged
I see "MyPropertyDescriptor - TheProperty" as expected.
Use [TypeDescriptionProvider] and INotifyPropertyChanged
I see "CLR - TheProperty". Why is this? The weird thing is that custom properties without a CLR property are shown normally. My custom type descriptor also returns a "MyPropertyDescriptor - AnotherProperty" which works in all cases because there is no CLR AnotherProperty defined.
In summary, given this XAML
<StackPanel>
<TextBlock Text="{Binding TheProperty}" />
<TextBlock Text="{Binding AnotherProperty}" />
</StackPanel>
AnotherProperty always works as expected because the model does not have a CLR property named "AnotherProperty". TheProperty works as expected except when [TypeDescriptionProvider] and INotifyPropertyChanged are both used.
Here's the full code. It's a bit long but most of it is irrelevant, it's just required by System.ComponentModel
public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();
DataContext = new MyModel();
}
}
//[TypeDescriptionProvider(typeof(MyProvider))]
class MyModel : Object
//, INotifyPropertyChanged
//, ICustomTypeDescriptor
{
public string TheProperty { get { return "CLR - TheProperty"; } }
public event PropertyChangedEventHandler PropertyChanged;
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(this);
}
public string GetClassName()
{
return TypeDescriptor.GetClassName(this);
}
public string GetComponentName()
{
return TypeDescriptor.GetComponentName(this);
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(this);
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this);
}
public PropertyDescriptor GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(this);
}
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes);
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(this);
}
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return TypeDescriptor.GetProperties(this, attributes);
}
public PropertyDescriptorCollection GetProperties()
{
return MyTypeDescriptor.GetCustomProperties();
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
}
class MyProvider : TypeDescriptionProvider
{
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
return new MyTypeDescriptor();
}
}
class MyTypeDescriptor : CustomTypeDescriptor
{
public override PropertyDescriptorCollection GetProperties()
{
return GetCustomProperties();
}
public static PropertyDescriptorCollection GetCustomProperties()
{
return new PropertyDescriptorCollection(
new[] {
new MyPropertyDescriptor("TheProperty"),
new MyPropertyDescriptor("AnotherProperty")
});
}
}
class MyPropertyDescriptor : PropertyDescriptor
{
public MyPropertyDescriptor(string propName)
: base(propName, null)
{
}
public override bool CanResetValue(object component)
{
return false;
}
public override Type ComponentType
{
get { return typeof(MyModel); }
}
public override object GetValue(object component)
{
return "MyPropertyDescriptor - " + Name;
}
public override bool IsReadOnly
{
get { return true; }
}
public override Type PropertyType
{
get { return typeof(string); }
}
public override void ResetValue(object component)
{
throw new InvalidOperationException("cannot reset value");
}
public override void SetValue(object component, object value)
{
throw new InvalidOperationException("property is readonly");
}
public override bool ShouldSerializeValue(object component)
{
return true;
}
}
Old question, but for people looking for an answer..
Problem is in System.Windows.PropertyPath.ResolvePropertyName(String, Object, Type, Object, Boolean) private method. I have found it in PresentationFramework.dll in .NET 4.0.
Extracted from .NET Reflector:
object propertyHelper = DependencyProperty.FromName(str, ownerType);
if ((propertyHelper == null) && (item is ICustomTypeDescriptor))
{
propertyHelper = TypeDescriptor.GetProperties(item)[str];
}
if ((propertyHelper == null) && ((item is INotifyPropertyChanged) || (item is DependencyObject)))
{
propertyHelper = this.GetPropertyHelper(ownerType, str);
}
if (propertyHelper == null)
{
propertyHelper = TypeDescriptor.GetProperties(item)[str];
}
if (propertyHelper == null)
{
propertyHelper = this.GetPropertyHelper(ownerType, str);
}
if ((propertyHelper == null) && throwOnError)
{
throw new InvalidOperationException(SR.Get("PropertyPathNoProperty", new object[] { ownerType.Name, str }));
}
return propertyHelper;
As you can see, retrieving property identifier (DependencyProperty / PropertyDescriptor / PropertyInfo) goes like this:
Try get DependencyProperty,
If item implements ICustomTypeDescriptor, use TypeDescriptor to get PropertyDescriptor,
If item implements INotifyPropertyChanged or is DependencyObject, use System.Reflection to get PropertyInfo,
Else use TypeDescriptor to get PropertyDescriptor,
Else use System.Reflection to get PropertyInfo,
Else throw exception or return null.
So System.Reflection/PropertyInfo gets precedence over TypeDescriptor/PropertyDescriptor if item implements INotifyPropertyChanged interface. I believe they choose this strategy for performance reasons because PropertyInfo is much more lighter than PropertyDescriptor.
Solution to your problem would be to implement ICustomTypeDescriptor (preferably explicitly) so that it transfers ICustomTypeDescriptor method calls to appropriate TypeDescriptor method calls but not with object parameter, but Type parameter (this.GetType()). This way your TypeDescriptionProvider will be used.
models from shell-view-model with abstract factory pattern. I need inject in view-models classes from external assembly. If I use abstract factory pattern on creation view-models. Problem is imported classes in view-models are null.
Shell-view-models look like this:
public interface IViewModelFactory
{
ILogOnViewModel CreateLogOnViewModel(IShellViewModel shellViewModel);
IMessengerViewModel CreateMessengerViewModel(IShellViewModel shellViewModel);
}
[Export(typeof(IViewModelFactory))]
public class DefaulFactoryViewModel:IViewModelFactory
{
#region Implementation of IViewModelFactory
public ILogOnViewModel CreateLogOnViewModel(IShellViewModel shellViewModel)
{
return new LogOnViewModel(shellViewModel);
}
public IMessengerViewModel CreateMessengerViewModel(IShellViewModel shellViewModel)
{
return new MessengerViewModel(shellViewModel);
}
#endregion
}
public interface IShellViewModel
{
void ShowLogOnView();
void ShowMessengerView();
}
[Export(typeof(IShellViewModel))]
public class ShellViewModel : Conductor<IScreen>, IShellViewModel
{
private readonly IViewModelFactory _factory;
[ImportingConstructor]
public ShellViewModel(IViewModelFactory factory)
{
_factory = factory;
ShowLogOnView();
}
public void ShowLogOnView()
{
var model = _factory.CreateLogOnViewModel(this);
// var model = IoC.Get<LogOnViewModel>();
ActivateItem(model);
}
public void ShowMessengerView()
{
var model = _factory.CreateMessengerViewModel(this);
ActivateItem(model);
}
}
Some view-model.:
public class LogOnViewModel : Screen,ILogOnViewModel
{
[Import]//inject class from external assembly
private IPokecConnection _pokecConn;
private readonly IShellViewModel _shellViewModel=null;
private User _user=null;
public LogOnViewModel(IShellViewModel shellViewModel)
{
_shellViewModel = shellViewModel;
_user = new User();
}
}
variable _pokecConn are null becasuse I use abstract factory on creation new view-models.
if I use in shell-view model this:
var model = IoC.Get<LogOnViewModel>();
instead this:
var model = _factory.CreateLogOnViewModel(this);
and add Export attribute on view-models classes it works good, but I would like use abstract factory, and inject in view-model only classes from extrenal assembly.
It exist solution on this problem, or I must create view-models from IoC and export all class? Thanl for advance.
EDITED :
MEF BOOTSTRAPER CLASS:
public class MefBootStrapper : Bootstrapper<IShellViewModel>
{
#region Fields
private CompositionContainer _container;
#endregion
#region Overrides
protected override void Configure()
{ // configure container
#if SILVERLIGHT
_container = CompositionHost.Initialize(
new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()));
#else
var catalog =
new AggregateCatalog(
AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());
//add external DLL
catalog.Catalogs.Add(
new AssemblyCatalog(string.Format(
CultureInfo.InvariantCulture, "{0}{1}", System.IO.Directory.GetCurrentDirectory(), #"\Pokec_Toolkit.dll")));
_container = new CompositionContainer(catalog);
#endif
var batch = new CompositionBatch();
batch.AddExportedValue<IWindowManager>(new WindowManager());
batch.AddExportedValue<IEventAggregator>(new EventAggregator());
batch.AddExportedValue(_container);
_container.Compose(batch);
_container.SatisfyImportsOnce(this);
}
protected override object GetInstance(Type serviceType, string key)
{
string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
var exports = _container.GetExportedValues<object>(contract);
if (exports.Count() > 0)
return exports.First();
throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
}
protected override IEnumerable<object> GetAllInstances(Type serviceType)
{
return _container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
}
protected override void BuildUp(object instance)
{
_container.SatisfyImportsOnce(instance);
}
#endregion
}
Did you forget the attribute ImportingConstructor for the LogOnViewModel constructor?
EDIT: Import property always null (MEF import issue)