Postsharp introduce Attributes with Property Arguments - postsharp

I am trying to achieve attribute introduction like here but my attributes have property arguments like: [Foo(Bar = "Baz")]
How do I correctly pass the arguments? I'm not copying the attributes from something else, so I don't think I can use CustomAttributeData?

You can set properties of your custom attributes by using ObjectConstruction.NamedArguments dictionary.
For example:
public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
{
Type targetType = (Type) targetElement;
var objectConstruction =
new ObjectConstruction(typeof (MyCustomAttribute).GetConstructor(Type.EmptyTypes));
objectConstruction.NamedArguments["Bar"] = "Baz";
var introduceAttributeAspect = new CustomAttributeIntroductionAspect(objectConstruction);
yield return new AspectInstance(targetType, introduceAttributeAspect);
}

Related

Unable to print the values of an instance of my model

I know this is a very fundamental question but answer to this will solve many of my doubts.
val new_parent = ParentDetails(intent.extras.getString("name"),
intent.extras.getString("email"),
intent.extras.getString("parent_relation"),
intent.extras.getString("locationdata"))
println(new_parent.tostring())
The code above doesn't print the various fields and their values present in the class.
The ParentDetails is a model I have created with some fields that are initialized. The ParentDetails model:
class ParentDetails {
var parent_id: Int = 0
var parent_name: String = ""
var parent_email: String = ""
var parent_relation: String = ""
var parent_location: String=""
constructor(parent_name: String, parent_email: String, parent_relation: String,parent_location:String) {
this.parent_name = parent_name
this.parent_email = parent_email
this.parent_relation = parent_relation
this.parent_location = parent_location
}
public fun getparentId(): Int {
return parent_id
}
fun ParentDetailsprintme() {
println(parent_name)
println(parent_email)
println(parent_relation)
println(parent_location)
}
}
In fact, it prints null and accessing individual fields, it prints empty string(the way it was initialized).
How do we explain this?
As I understand your problem is that calling println(new_parent.tostring()) does not print what you would like to print in function ParentDetailsprintme.
First of all, you have a typo, the correct call would be new_parent.toString().
Note that it could have been simplified as println(new_parent).
It does not print that you defined in the ParentDetailsprintme method, as the method is not called.
What println(new_parent.toString()) prints, is actually the hashcode of the object, as this is the default behaviour of every object.
To make it work call it like println(new_parent.ParentDetailsprintme()) or override the toString() method for example as:
override fun toString() = "$parent_name $parent_email $parent_relation $parent_location"
then the following
val new_parent = ParentDetails("myName", "myEmail", "myParent_relation", "myLocationdata")
println(new_parent)
should print
myName myEmail myParent_relation myLocationdata
Kotlin's println function simply calls System.out.println(message) under the hood which will call String.valueOf() (e.g. String.valueOf(Object object) for objects, which will call the toString() method of the passed object).
/** Prints the given message and newline to the standard output stream. */
#kotlin.internal.InlineOnly
public inline fun println(message: CharArray) {
System.out.println(message)
}
Update ("Using data class method also works"):
If you make the class to be a data class:
data class ParentDetails(
val parent_id: Int = 0,
val parent_name: String = "",
val parent_email: String = "",
val parent_relation: String = "",
val parent_location: String = ""
)
and then you execute
val new_parent = ParentDetails(0, "myName", "myEmail", "myParent_relation", "myLocationdata")
println(new_parent)
you will receive as result
ParentDetails(parent_id=0, parent_name=myName, parent_email=myEmail, parent_relation=myParent_relation, parent_location=myLocationdata)
This is because data classes override the toString() function:
The compiler automatically derives the following members from all
properties declared in the primary constructor:
equals()/hashCode() pair;
toString() of the form "User(name=John, age=42)";
Did you check that you receive valid data from your intent.extras?
Also I suggest you use data class for your models.
It will look something like this:
data class ParentDetails(
var parent_id: Int = 0,
var parent_name: String = "",
var parent_email: String = "",
var parent_relation: String = "",
var parent_location: String = ""
)
You will be able to use it like this :
val new_parent = ParentDetails(
parent_name = intent.extras.getString("name"),
parent_email = intent.extras.getString("email"),
parent_relation = intent.extras.getString("parent_relation"),
parent_location = intent.extras.getString("locationdata")
)
println(new_parent.tostring())
As already mentioned, you have a typo. toString returns the hashcode of an object unless it's overridden to return something else. Look up the original implementation for more details.
By overriding the toString method, you change what it returns, and through that, what is printed when you print(someClass). DVarga showed that in their answer.
Data classes auto-generate a toString method containing the content of the class. So creating a data class is a shortcut to getting output containing the data.
The reason the method you had didn't work is because you didn't call it. if you call it instead of toString, you would get the data printed.
Also, toString is explicitly called when you print a class. You don't need to call print(someInstance.toString()), print(someInstance) is enough.
And while I'm writing an answer, you don't need to use secondary constructors in Kotlin. Primary constructors would shorten your code significantly, whether it's a data class or not. Also, you should look into naming conventions.

Making a class in Swift 2

How should I correctly create such a class which can be used from any .swift-file of my project and does not need to be initialized with a variable?
I mean that I want not to have to write something like
someVar = myClass()
in each file where I want this class to be usable. I just want this class to have a global public variables and change them from a .swift-file of my project by doing something like
myClass.myVar = value
I'm thinking about making this class a separate file. What's a correct way to do this?
You can create a static property inside a class or struct and call it anywhere. E.g:
//Config.swift
struct Config
{
static var field1 : String = "Field_Value"
static var field2 : String = "Field_Value"
}
You can use the property calling StructName.propertyName.
E.g:
//MyCode.swift
print(Config.field1)
Config.field1 = "New Value"
You can create a new class, make a variable off that class outside any class.
Class Awesome{
}
let awesomeness = Awesome()
you can than use 'awesomeness' as class instance in every other swift file

method based on variable type

I just have the following scenario
i want to return string from method but the method should be based on variable type which is (Type CType)
i need to make the render class like this
public string render(TextBox ctype){
return "its text box";
}
public string render(DropDown ctype){
return "its drop down";
}
you know TextBox is a Type thats why i can declare the Type variable like this
var CType = typeof(TextBox)
and i need to call the render method like this
render(Ctype);
so if the Ctype is type of TextBox it should call the render(TextBox ctype)
and so on
How can i make it ?
you should use a template function
public customRender<T>(T ctype)
{
if(ctype is TextBox){
//render textbox
}
else if(ctype is DropDown){
//render dropdown
}
}
hope it will help
First of all, even if you don't see an if or a switch, there will still be one somewhere hidden inside some functions. Distinguishing types at runtime that are not known at compile-time simply will not be possible without any such kind of branching of the control flow.
You can use one of the collection classes to build a map at runtime that maps Type instances to Func<T, TResult> methods. For example, you can use the Dictionary type to create such a map:
var rendererFuncs = new Dictionary<Type, Func<object, string>>();
You could then add some entries to that dictionary like this:
rendererFuncs[typeof(TextBox)] = ctype => "its text box";
rendererFuncs[typeof(DropDown)] = ctype => "its drop down";
Later on, you can call the appropriate function like this:
string renderedValue = rendererFuncs[Ctype.GetType()](Ctype);
Or, if you want to be on the safe side (in case there are Ctype values that have no appropriate renderer):
string renderedValue;
Func<object, string> renderer;
if (rendererFuncs.TryGetValue(Ctype.GetType(), out renderer)) {
renderedValue = renderer(Ctype);
} else {
renderedValue = "(no renderer found)";
}
Note that this will only work for as long as Ctype is of the exact type used as a key in the dictionary; if you want any subtypes to be correctly recognized as well, drop the dictionary and build your own map that traverses the inheritance hierarchy of the type being searched (by using the Type.BaseType property).

Can't use string.Format() in Anonymous Type

I'm hoping to achieve something as follows:
var comboBoxItems = from state in states
select new
{
Key = state.Code,
Value = string.Format("{0} ({1})", state.Name, state.Code)
};
this.stateComboBox.DisplayMember = "Value";
this.stateComboBox.ValueMember = "Key";
this.stateComboBox.DataSource = new BindingSource(comboBoxItems, null);
However, it gives me the following error when it attempts to bind to the DataSource:
"LINQ to Entities does not recognize the method 'System.String
Format(System.String, System.Object, System.Object)' method, and this
method cannot be translated into a store expression."
Is there any way to include a method like string.Format() in the Anonymous Type?
var comboBoxItems = from state in states.ToList()
select new
{
Key = state.Code,
Value = string.Format("{0} ({1})", state.Name, state.Code)
};
You cannot use Format in LINQ 2 Entities as it cannot be translated to SQL. A call to ToList will cause the items to be loaded from DB and your format will now execute properly.

How can I store all the properties of a class in an array of objects?

Let's say I've a class myClass which has few properties, such as property1, property2, perperty3, etc. Now, I'd like to populate an array with each of those properties so that, I can access each of them through its index. Is there an automatic way of doing so?
Here's an example from SportsStore (Pro ASPN.NET MVC/Steve Sanderson/Apress) on how to gather all the active controllers in the the 'Assembly'.
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach(Type t in controllerTypes)
//Do something
I wonder if there is some thing like the one above I can use to collect (only) properties of a class and store them in a array, no matter each one's type value (int, string, or custom type)
I hope I was able to express myself clearly. Otherwise I can amend the text.
Thanks for helping.
You could use reflection:
var foo = new
{
Prop1 = "prop1",
Prop2 = 1,
Prop3 = DateTime.Now
};
var properties = TypeDescriptor.GetProperties(foo.GetType());
var list = new ArrayList();
foreach (PropertyDescriptor property in properties)
{
var value = property.GetValue(foo);
list.Add(value);
}
and LINQ version which looks better to the eye:
var list = TypeDescriptor
.GetProperties(foo.GetType())
.Cast<PropertyDescriptor>()
.Select(x => x.GetValue(foo))
.ToArray();
I got this from here:
foreach(Type t in controllerTypes)
{
foreach (MemberInfo mi in t.GetMembers() )
{
if (mi.MemberType==MemberTypes.Property)
{
// If the member is a property, display information about the property's accessor methods
foreach ( MethodInfo am in ((PropertyInfo) mi).GetAccessors() )
{
// do something with [am]
}
}
}
}
would the Type.GetProperties() method help you?