How to get a string representation of a property name of a Model in MVC3? - string

I have the following model:
Public Class MyModel
Public Property MyModelId As Integer
Public Property Description As String
Public Property AnotherProperty As String
End Class
Is there a method to get a property name of the Model as a string representation like the following code?
Dim propertyName as String = GetPropertyNameAsStringMethod(MyModel.Description)
So the propertyName variable has "Description" as value.

Check the Darin Dimitrov' answer on this SO thread - Reflection - get property name.
class Foo
{
public string Bar { get; set; }
}
class Program
{
static void Main()
{
var result = Get<Foo, string>(x => x.Bar);
Console.WriteLine(result);
}
static string Get<T, TResult>(Expression<Func<T, TResult>> expression)
{
var me = expression.Body as MemberExpression;
if (me != null)
{
return me.Member.Name;
}
return null;
}
}
Hope this help..

Here is a helper extension method you can use for any property:
public static class ReflectionExtensions
{
public static string PropertyName<T>(this T owner,
Expression<Func<T, object>> expression) where T : class
{
if (owner == null) throw new ArgumentNullException("owner");
var memberExpression = (MemberExpression)expression.Body;
return memberExpression.Member.Name;
}
}
However, this will only work on instances of a class. You can write a similar extension method that will operate directly on the type instead.

You need to do it using reflection.
There are already loads of posts on stack overflow like this:
How to get current property name via reflection?
Reflection - get property name
Get string name of property using reflection
Reflection - get property name
I believe that the answer will be along the lines of:
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);

Create an extension method and then use it where needed.
Private Shared Function GetPropertyName(Of T)(exp As Expression(Of Func(Of T))) As String
Return (DirectCast(exp.Body, MemberExpression).Member).Name
End Function
have a look at this post as well.

I have solved this issue editing a bit #NiranjanKala's source example,
converting the code in vb.Net like this
<System.Runtime.CompilerServices.Extension()> _
Public Function GetPropertyName(Of T, TResult)(expression As Expression(Of Func(Of T, TResult))) As String
Dim [me] = TryCast(expression.Body, MemberExpression)
If [me] IsNot Nothing Then
Return [me].Member.Name
End If
Return Nothing
End Function
Then I am able to call the extension like this
Dim propertyName as String = GetPropertyName(Of MyModel, String)(Function(x) x.Description)
Then propertyName variable has "Description" as string value.

Related

How to use fieldset in lightning Component

I want to create a custom lightning component to create new Case records and need to use fieldset to include fields in component. Need to use this only for one object. I never used fieldsets so dont have any idea on it. It would be really great if you can share some sample code or any link for the same.
You can use this utility class
This is the wrapper class to hold the meta info about the fields
public with sharing class DataTableColumns {
#AuraEnabled
public String label {get;set;}
#AuraEnabled
public String fieldName {get;set;}
#AuraEnabled
public String type {get;set;}
public DataTableColumns(String label, String fieldName, String type){
this.label = label;
this.fieldName = fieldName;
this.type = type;
}
}
Class FieldSetHelper has a method getColumns () this will return the list of DataTableColumns wrapper containing the information about the filedset columns
public with sharing class FieldSetHelper {
/*
#param String strObjectName : required. Object name to get the required filed set
#param String strFieldSetName : required. FieldSet name
#return List<DataTableColumns> list of columns in the specified fieldSet
*/
public static List<DataTableColumns> getColumns (String strObjectName, String strFieldSetName) {
Schema.SObjectType SObjectTypeObj = Schema.getGlobalDescribe().get(strObjectName);
Schema.DescribeSObjectResult DescribeSObjectResultObj = SObjectTypeObj.getDescribe();
Schema.FieldSet fieldSetObj = DescribeSObjectResultObj.FieldSets.getMap().get(strFieldSetName);
List<DataTableColumns> lstDataColumns = new List<DataTableColumns>();
for( Schema.FieldSetMember eachFieldSetMember : fieldSetObj.getFields() ){
String dataType =
String.valueOf(eachFieldSetMember.getType()).toLowerCase();
DataTableColumns datacolumns = new DataTableColumns(
String.valueOf(eachFieldSetMember.getLabel()) ,
String.valueOf(eachFieldSetMember.getFieldPath()),
String.valueOf(eachFieldSetMember.getType()).toLowerCase() );
lstDataColumns.add(datacolumns);
}
return lstDataColumns;
}
}
After you getting all those field set information the create lightning component dynamically

How to display the ToString of an object which is in a ListBox?

I have a class which holds the string I want to display and an id for that item.
ref class ListBoxItem {
private:
int id;
String ^ name;
public:
ListBoxItem(int id, const char * name) { this->id = id; this->name = gcnew System::String(name); }
virtual String ^ ToString() new { return name; }
};
And I add each item to the ListBox like this:
for(list<string>::iterator i = listItems.begin(); i != listItems.end(); i++)
listBoxItems->Items->Add(gcnew ListBoxItem(2, (*i).c_str()));
This will produce a ListBox with the correct number of items, but all the items are called "ListBoxItem".
Instead, I want the ListBox to display the string which is produced when the ToString method is invoked on ListBoxItem.
You didn't say whether you were using WinForms or WPF, but I believe this answer is valid for either.
(Note: There is a class named ListBoxItem in the framework. You might want to pick a different class name.)
I believe the issue is here:
virtual String ^ ToString() new { return name; }
^^^
This means you're creating a brand new ToString method, which doesn't have anything to do with the Object.ToString method. When the ListBox calls ToString, it doesn't have your class definition, so it just calls Object.ToString(), which you haven't changed.
Switch it to this, and you should be good:
virtual String ^ ToString() override { return name; }
^^^^^^^^

For use of constructor in c#

I have a class that has 2 properties and a constructor:
public class Card
{
public int CardName {get;set;}
public bool IsActive {get;set;}
public Card (int cardName, bool isActive)
{
CardName = cardName;
IsActive = isActive;
}
}
How do I force the developer to use the constructor instead of doing the following:
var card = new Card{ CardName = "blab", IsActive = true };
On a side note, what is the statement above called? Is that a lazy loading statement?
You already have.
By not having an empty constructor you've removed the ability to use the object initializer method of creating an object.
This:
var card = new Card{ CardName = "blab", IsActive = true };
is the same as this
var card = new Card() { CardName = "blab", IsActive = true };
And in this context new Card() is not valid.
That depends on why you want to prevent the syntax in question.
The object initializer syntax is shorthand for setting a bunch of properties immediately after construction. That is, this:
var c = new Card { CardName = "foo", IsActive = true };
Is semantically identical to this:
var c = new Card();
c.CardName = "foo";
c.IsActive = true;
In both cases, a constructor does run, but its immediately followed by a series of property initializers to apply to the new object.
In your case, since there is no parameterless constructor, you cannot use the object initializer syntax the way you posted. However, it is legal to pass constructor parameters along with the object initializer, so the following would be legal for your class:
var c = new Card("", false) { CardName = "foo", IsActive = true };
(One could argue that this syntax makes the meaning of values more clear than simply passing them to a constructor; one could also argue its just being excessively stubborn :) I could go either way)
You could prevent this second syntax from working by removing the public setters for those properties. If your goal is to prevent the user from changing the values passed into the constructor, making an immutable Card object, for example, that would be the way to go.
I should point out, though, that if one of my juniors asked me this question at work I'd really want to know why they found it necessary to prevent object initialization from being used. There are valid reasons, of course, but they are usually not the source of the question. Object initializers are a good thing -- there are cases where this syntax is very convenient (particularly with LINQ) and I use it all the time.
If you do some kind of setup in the constructor based on the initial values, but those properties are public-settable, you already have to deal with a case where the user changes those values after construction. If your goal is merely to ensure that some "setup" code happens when the object is first constructed, put that code into a default constructor and chain them together:
public class Card
{
public string CardName { get; set; }
public bool IsActive { get; set; }
public Card()
{
// setup code here.
}
public Card ( string name, bool active )
: this()
{
this.CardName = name;
this.IsActive = active;
}
}
Declare the getters of the property as 'Private'.
Something like Public int CardName {private get; set;}.

Get job title using System.DirectoryServices.AccountManagement

I've successfully used the AccountManagement code to retrieve basic AD information but it's only returning a very limited set of information about the returned object. How can I get extended information from AD using the AccountManagement functionality. Specifically the Job Title or title as it seems to be called in my instance of AD.
I know how to do it using the older DirectoryServices but I'd like to know how to do it using the new namespace.
Yes, the default set of properties on UserPrincipal is quite limited - but the great part is: there's a neat extensibility story in place!
You need to define a class descending from UserPrincipal and then you can very easily get access to a lot more properties, if needed.
The skeleton would look something like this:
namespace ADExtended
{
[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("User")]
public class UserPrincipalEx : UserPrincipal
{
// Inplement the constructor using the base class constructor.
public UserPrincipalEx(PrincipalContext context) : base(context)
{ }
// Implement the constructor with initialization parameters.
public UserPrincipalEx(PrincipalContext context,
string samAccountName,
string password,
bool enabled) : base(context, samAccountName, password, enabled)
{}
UserPrincipalExSearchFilter searchFilter;
new public UserPrincipalExSearchFilter AdvancedSearchFilter
{
get
{
if (null == searchFilter)
searchFilter = new UserPrincipalExSearchFilter(this);
return searchFilter;
}
}
// Create the "Title" property.
[DirectoryProperty("title")]
public string Title
{
get
{
if (ExtensionGet("title").Length != 1)
return string.Empty;
return (string)ExtensionGet("title")[0];
}
set { ExtensionSet("title", value); }
}
// Implement the overloaded search method FindByIdentity.
public static new UserPrincipalEx FindByIdentity(PrincipalContext context, string identityValue)
{
return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityValue);
}
// Implement the overloaded search method FindByIdentity.
public static new UserPrincipalEx FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
{
return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityType, identityValue);
}
}
}
And that's really almost all there is! The ExtensionGet and ExtensionSet methods allow you to "reach down" into the underlying directory entry and grab out all the attributes you might be interested in....
Now, in your code, use your new UserPrincipalEx class instead of UserPrincipal:
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// Search the directory for the new object.
UserPrincipalEx myUser = UserPrincipalEx.FindByIdentity(ctx, "someUserName");
if(myUser != null)
{
// get the title which is now available on your "myUser" object!
string title = myUser.Title;
}
}
Read all about the System.DirectoryServices.AccountManagement namespace and its extensibility story here:
Managing Directory Security Principals in the .NET Framework 3.5
Update: sorry - here's the UserPrincipalExSearchFilter class - missed that one in the original post. It just shows the ability to also extend the search filters, if need be:
public class UserPrincipalExSearchFilter : AdvancedFilters
{
public UserPrincipalExSearchFilter(Principal p) : base(p) { }
public void LogonCount(int value, MatchType mt)
{
this.AdvancedFilterSet("LogonCount", value, typeof(int), mt);
}
}
To Augment the above I have knocked up an extension method to call ExtensionGet. It uses reflection to get hold of the protected method you would otherwise have to inherit. You might need to use this if you are returning UserPrincipalObjects from Groups.Members, for example
public static class AccountManagmentExtensions
{
public static string ExtensionGet(this UserPrincipal up, string key)
{
string value = null;
MethodInfo mi = up.GetType()
.GetMethod("ExtensionGet", BindingFlags.NonPublic | BindingFlags.Instance);
Func<UserPrincipal, string, object[]> extensionGet = (k,v) =>
((object[])mi.Invoke(k, new object[] { v }));
if (extensionGet(up,key).Length > 0)
{
value = (string)extensionGet(up, key)[0];
}
return value;
}
}
There are simpler ways of getting to that info. Here is the way I got to Job Title in VB.NET:
Dim yourDomain As New PrincipalContext(ContextType.Domain, "yourcompany.local")
Dim user1 As UserPrincipal = UserPrincipal.FindByIdentity(yourDomain, principal.Identity.Name)
Dim Entry As DirectoryServices.DirectoryEntry = user1.GetUnderlyingObject()
Dim JobTitle As String = Entry.Properties.Item("Title").Value.ToString
To expand on Programmierus' comment, here is a simple way to do this on the fly in C#.
public static string GetProperty(UserPrincipal userPrincipal, string property)
{
DirectoryEntry d = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
return d.Properties[property]?.Value?.ToString();
}

C#: is it possible to create an object that has a value of its "default property" when referenced?

Is it possible to create an object with a constructor parameter which returns a property value when referenced, without using dot notation? Here's a few examples:
public class myObject
{
public string myObject {get; private set;}
public myObject( string tempstring)
{
this.myObject = tempstring.ToUpper();
}
}
var a = new myObject("somevalue");
Console.WriteLine( myObject ); // outputs the string "SOMEVALUE"
Here's another attempt:
public class myInt
{
public int myInt {get; private set;}
public myInt(string tempInt)
{ this.myInt = Convert.ToInt32(tempInt);
}
}
var a = new myInt("3");
var b = a + a; // ends up being an int datatype value of 6
I know I could always do var b = a.myInt + a.myInt. I guess I could create a static class with a static function that converts a parameter each time to a result, but it wouldn't maintain state.
Just curious. It would make what I am actually trying to do much less difficult.
In the first case, yes. Override the ToString method.
public class myObject
{
public string myValue {get; private set;}
public myObject( string tempstring)
{
this.myValue = tempstring.ToUpper();
}
public override string ToString()
{
return myValue;
}
}
In the second case, sort of. You shouldn't try to overload operators to offer unexpected behavior. Create a method to perform behavior that wouldn't make sense when reading the code. What you are suggesting (returning an int) would definitely not be expected by me to return an int (mostly because of the var rather than a strictly defined type). Using the + operator to return a new myInt object would make sense. Using the + operator return an int would not.
You could overload the + operator to return a new myInt object, and then also add an implicit cast to int. Just make sure it makes sense, and that it is readable.
Within the class, you could use:
public static implicit operator int(myInt m)
{
return myValue;
}
public static myInt operator +(myInt left, myInt right)
{
// requires constructor that takes int
return new myInt(left.myValue + right.myValue);
}
Of course, you could go the direct route, but again only use it when it makes it more readable and not less (note, just like methods operators cannot be overloaded simply by return type, so you'd have to pick between the two).
public static int operator +(myInt left, myInt right)
{
return left.myValue + right.myValue;
}
How about implicit conversions. See http://msdn.microsoft.com/en-us/library/z5z9kes2(VS.71).aspx

Resources