Configuration DefaultValue Behaviours - c#

[ConfigurationProperty("Name", DefaultValue = "test")]
public string Name
{
get { return (string)this["Name"]; }
set { this["Name"] = "Ram"; }
}
CorticonConfig config = new CorticonConfig();
string test = config.Name;
I have a property with "Name" and also I am setting the value to name.While I m trying to get the value, I am getting default value.
My question is: can we set property value as above?
And what is the behaviour of Default value property?

Your property setter doesn't work like you think it's working.
The set part is executed when you set the property (you make property = something), and in that case, your something would be on the value keyword.
So in your case, if you do:
CorticonConfig config = new CorticonConfig();
config.Name = "whatever";
string test = config.Name;
test will have "Ram", because you are always asigning that value there, but it won't execute that code unless you do config.Name = <something>.
The correct way to have a setter like that would be:
set
{
this["Name"] = value;
}
And if you need a default value other than the one you are setting on your attribute, apply it after constructing the object:
CorticonConfig config = new CorticonConfig();
config.Name = "Ram";
The DefaultValue you pass on the attribute gives it a default value if no settings have been ever saved, so when you read it, it'll return that.

Related

Used Named Optional Parameters for Method

I have a method where I have several optional boolean parameters, different properties of an object will be given a value based on which parameters are true.
Here is the method for context:
public static AutoPatientLookup InitializeTestPatientInfo(bool SSN = false, bool PatientNumber = false, bool Gender = false)
{
AutoPatientLookup TestAPIParameters = new AutoPatientLookup();
TestAPIParameters.FirstName = "First";
TestAPIParameters.LastName = "Last";
TestAPIParameters.DOB = "4/9/1953";
TestAPIParameters.PracticeID = 11071;
if (SSN)
{
TestAPIParameters.SSN = 000010281;
}
if (PatientNumber)
{
TestAPIParameters.PatientNumber = 458;
}
if (Gender)
{
TestAPIParameters.Gender = "F";
}
return TestAPIParameters;
}
However, sometimes I want the second or third boolean parameter to be true but I'm unable to designate that as the parameter I want to switch without explicitly stating true or false for the preceding parameters.
This if I want to initialize an AutoPatientLookup object that has a value for its gender property, I would have to call it like this:
InitializeTestPatientInfo(false,false,true);
I tried something along the lines of
InitializeTestPatientInfo(Gender = true);
and
InitializeTestPatientInfo(bool Gender = true);
but nothing seems to work. Is there a correct syntax for accomplishing for what I'm attempting? Even though the initialization syntax isn't very inconvenient when there are only three boolean parameters this could be more applicable if there are dozens.
The syntax you want to use is:
InitializeTestPatientInfo(Gender: true);
Try
InitializeTestPatientInfo(Gender: true);
You can name your parameter that you are assigning:
Do this instead
InitializeTestPatientInfo(Gender: true);

How can I set the value of a variable?

I have found this example to set the value of a Class property:
Ship ship = new Ship();
string value = "5.5";
var property = ship.GetType().GetProperty("Latitude");
var convertedValue = property.Converter.ConvertFrom(value);
property.SetValue(self, convertedValue);
But I want to set value of a variable in my "this".
i.e. in my main form I have a private double "Momentum"
string value = "5.5";
var property = this.GetType().GetProperty("Momentum");
var convertedValue = property.Converter.ConvertFrom(value);
property.SetValue(self, convertedValue);
This does NOT work - "property" is null.
How do I alter the above code to achieve this?
Seriously, why are you using reflection if you need to set the field value from a variable you own?
Okay, let's forget that... If you have a field and not a property, you need to use GetField:
var value = "5.5";
var field = this.GetType().GetField(nameof(Momentum), BindingFlags.NonPublic);
field.SetValue(self /* or this */, value);
Also, this might be a good place to use nameof, but that is just a suggestion.

Using A SeT Property To Set Multiple Properties Of A Class Simultaneously In C#

Suppose I have a very large list of objects and each object in the list has the following properties: ID, Name, Make, Model, Color, Price
I know that if I want to quickly locate an object in the list I can use an Indexer and search for the object using it's ID.
But once I locate the object how do I change more than one property at the same time?
I thought about returning the MyClass Object in the get property of the Indexer so that I have access to all of its properties. However, I don't know what to do in the set property of the Indexer to make it work. Below is my code
public MyClass this[int id]
{
get {return myObjectList.FirstOrDefault(item => item.ID == id);}
set {// something = value;}
}
But once I locate the object how do I change more than one properties at the same time?
It looks like you want to do something like
List[4] = {Name = "name",
Make = "make",
Model = "model",
Color = "color",
Price = "price
};
Which is not possible in C#. There's no syntax to set multiple properties of an existing object simultaneously. You can create a new object and replace the one in the list:
List[4] = new MyClass {
Name = "name",
Make = "make",
Model = "model",
Color = "color",
Price = "price
};
But that's creating a new object, not modifying an existing one.
The only way to set multiple properties is with individual sets:
MyClass obj = List[4];
obj.Name = "name";
obj.Make = "make";
obj.Model = "model";
ojb.Color = "color";
obj.Price = "price";
Note that this does not involve the setter of the index property at all. It's not uncommon for collections to have a get-only indexer so that the list itself cannot be mutated through the indexer, although the properties of the objects inside can.

Conditions inside a C# Class

I have this below script in my Class.
aggrgt.Add(new PlainBrgDataSummaryChartAggrgt
{
label = m.label,
goal = m.goal,
groupCode = m.groupCode,
groupValue1 = m.groupValue1,
graphSwitch = m.graphSwitch,
orderByAsc = m.orderByAsc,
metricID = m.metricID,
scoreWk1 = metricscoreWk1.metricScore1,
});
The condition I want is when metricscoreWk1 is null, scoreWk1 = metricscoreWk1.metricScore1 is eliminated.
This may help you:
scoreWk1 = metricscoreWk1.metricScore1 ==null ? 0 : metricscoreWk1.metricScore1
That is, if the value of metricscoreWk1.metricScore1 is null 0(or else any default value) will be assigned else the original value will be assigned to scoreWk1
You can't put "" for Double, the closest analogue, INHO, is Double.NaN (Not A Number):
// Let's have Double.NaN for unknown/undefined etc. value
scoreWk1 = metricscoreWk1.metricScore1 ?? Double.NaN;
You could either:
Create the PlainBrgDataSummaryChartAggrgt object without setting the scoreWk1 field. If metricscoreWk1 is not null, you then set the field and you then add the object to the list.
If you have a setter for metricScore1, you could add a check wherein you ensure that metricscoreWk1 is not null. If it is, the value is not updated.
The second option would allow you to keep your current initialization structure, but the first is more explicit. Should you opt for the second approach, I'd recommend you document it.

Searching for pages with any value in property

EPiServer only:
How do I search for pages with any value in a given property? I can do a search for pages with a specific value in the property, but I can't figure out how to search for "not empty".
For example, this doesn't work:
var criterias = newPropertyCriteriaCollection
{
new PropertyCriteria()
{
Condition = CompareCondition.NotEqual,
Name = "MyProperty",
IsNull = false,
Type = PropertyDataType.String,
Value = ""
}
};
var pages = DataFactory.Instance.FindPagesWithCriteria(PageReference.StartPage, criterias);
An exception is thrown, "The crieria value cannot be null or empty. Set the IsNull property to search for null."
Any ideas?
Yeah, this is confusing. In case anyone else stumbles on this, here's how to search for pages with a certain PageReference property set to something:
new PropertyCriteria()
{
createdCriteria.Name = "MyProperty";
createdCriteria.Type = PropertyDataType.PageReference;
createdCriteria.Condition = EPiServer.Filters.CompareCondition.NotEqual;
createdCriteria.Value = "0";
createdCriteria.IsNull = false;
}
Unless I'm missing a trick, this doesn't appear to be possible using the EPiServer PropertyCriteriaCollection.
I've had a dig around in reflector and here are my findings. The FPWC method eventually calls EPiServer.DataAccess.PropertySearchDB.FastFindPagesWithCriteria().
Within this method is the following:
foreach (PropertyCriteria criteria in criterias)
{
if (criteria.IsNull)
{
criteria.Value = null;
}
else if (string.IsNullOrEmpty(criteria.Value))
{
throw new EPiServerException("The crieria value cannot be null or empty. Set the IsNull property to search for null.");
}
...
}
So its not possible to search for an empty string value, without setting IsNull to true. This is then fed down to the EPiServer.DataAccess.PropertySearchDB.ExecuteCriteria method, which constructs and formats the DB command. Because IsNull is true, the netPropertySearchNull stored proc is used. Searching for a string needs to use the netPropertySearchString stored proc.
if (criteria.IsNull && !PageDB.IsMetaData(criteria.Name))
{
cmd.CommandText = "netPropertySearchNull";
}
My suggestion would be to load the full list of pages and filter using linq. Alternatively you could look into bypassing the API and implementing a direct DB query, or use some of the low level EPiServer data access methods (not recommended)
Apologies for my first answer - I really should test code before posting :)
I've seen something where the page has a a hidden bool property "Property X contains a value" that is set in the Saving event.
Then that bool property is used as a PropertyCriteria instead of the one you are REALLY interested in.
To find empty values you need to specify the IsNull property on the PropertyCriteria and use the Equal compare condition.
E.g
var criterias = newPropertyCriteriaCollection
{
new PropertyCriteria()
{
Condition = CompareCondition.NotEqual,
Name = "MyProperty",
IsNull = true,
Type = PropertyDataType.String
}
};

Categories

Resources