Change the default value of a settingsvalue - c#

id didnt find anything on Stackoverflow or on the internet, im sorry if this question was already posted (or if its simply impossible).
Is there a way to change the default value of a *.settigs-property, for example if i have the setting "USER"
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("TESTUSER")]
public string SQLServer {
get {
return ((string)(this["USER"]));
}
set {
this["USER"] = value;
}
}
would there be a way to change (at runtime) the DefaultSettingValueAttribute ("TESTUSER") to another value (i.e: "John Doe").
Thanks in advance

You can override the Properties property of the ApplicationSettingsBase class:
public override SettingsPropertyCollection Properties
{
get
{
var properties = base.Properties;
properties["SQLServer"].DefaultValue =
String.Format("John Doe {0}", DateTime.Now);
return properties;
}
}

Related

C# json deserialiser how to set property

My code is:
namespace RTT_API
{
class routepoint
{
public string description { get; set; }
public string TIPLOC { get { return TIPLOC; } set { SetStationRef(); } }
public string publicTime { get; set; }
public Guid StationRef { get; set; }
public void SetStationRef()
{
SqlCommand comStationRef = new SqlCommand("select uniqueref from station where tiploc=#tiploc", Globals.RTTConn);
comStationRef.Parameters.Add("#tiploc");
comStationRef.Parameters["#tiploc"].Value = TIPLOC;
SqlDataReader rdrStationRef = comStationRef.ExecuteReader();
if (rdrStationRef.HasRows == true)
{
rdrStationRef.Read();
StationRef = rdrStationRef.GetGuid(1);
rdrStationRef.Close();
}
else
{
rdrStationRef.Close();
comStationRef.CommandText="Insert into station(tiploc) values (#tiploc)";
comStationRef.ExecuteNonQuery();
}
rdrStationRef.Close();
}
}
}
I would appreciate help with the following:
If I try to debug the TIPLOC value I receive a Stackoverflow error. It worked OK when the definition was only:
public string TIPLOC { get; set; }
The SetStationRef method doesn't run when the value is set
The TIPLOC value is set by a JSON deserialise command. Is using a custom 'set' method the correct way to set the StationRef value? I tried putting code in the class constructor but it looks like the constructor runs before the JSON deserialise sets the properties? I'm new to C# so trying not to get into any bad practices to start with.
Thanks
This line
public string TIPLOC { get { return TIPLOC; } set { SetStationRef(); } }
will return TIPLOC indefinitely because it is calling itself. Calling return TIPLOC will call the getter of TIPLOC and its just going to keep doing that until it overflows the stack. When you debug the debugger will try and retrieve the value of the property and will get stuck in that loop.
set { SetStationRef(); } also ignores the value. I assume you want to call SetStationRef(value);. In the setter of a property the value the user is trying to set gets passed in as a local variable called value
From the overall look I think what you are trying to achieve is something along the lines of
private string tiploc;
public string TIPLOC
{
get
{
if(tiploc == null)
{
tiplock = GetValueFromDatabase(); // Replace this to retrieve the value
}
tiploc;
}
set
{
SetStationRef(value);
tiploc = value;
}
}
My original three questions were:
If I try to debug the TIPLOC value I receive a Stackoverflow error
The SetStationRef method doesn't run when the value is set -
The TIPLOC value is set by a JSON deserialise command. Is using a custom 'set' method the correct way to set the StationRef value? I tried putting code in the class constructor but it looks like the constructor runs before the JSON deserialise sets the properties? I'm new to C# so trying not to get into any bad practices to start with.
Question 1 was answered by Ben and his help enabled me to find a solution to questions 2 and 3 so a lot of credit is due to him.
I've only added a separate answer because the custom accessor needs to be defined on the StationRef and not the Tiploc (the Tiploc is set by the Deserialisation code) as follows:
public string tiploc { get; set; }
public Guid StationRef
{
get
{
if (stationRef == Guid.Empty)
{
stationRef = Globals.GetStationRef(tiploc);
}
return stationRef;
}
set
{
stationRef = value;
}
}

override a linq attribute c#

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Gender", DbType="Int NOT NULL", UpdateCheck=UpdateCheck.Never)]
public int Gender
{
get
{
return this._Gender;
}
set
{
if ((this._Gender != value))
{
this.OnGenderChanging(value);
this.SendPropertyChanging();
this._Gender = value;
this.SendPropertyChanged("Gender");
this.OnGenderChanged();
}
}
}
there is an attribute for update check which I set it to never. But when ever I made a small change in dbml I must set this property of this field to never again. How can I override this attribute for ever in an partial class?
Update: as an example I can change dbml connection string like this, one time for ever:
partial class DataBaseDataContext : System.Data.Linq.DataContext
{
public DataBaseDataContext() :
base(ConfigurationManager.ConnectionStrings["MyConnection"].ToString())
{
OnCreated();
}
}
Open the dbml file in the designer and set Update Check for the property to the desired value. Don't modify the generated files directly, it will be overwritten.

Attributes of properties in MetadataType are ignored by EntLib Validation

It's an EntLib-Validator-issue again. I'm playing with EntLib 5.0 in C# and .Net 4.0 on XP pro.
I have some business objects (partial classes) generated by T4 templates. So I decided to put their validation attributes in buddy-classes by using MetadataTypeAttribute as definitely recommended by the documentation of entLib 5.0 (msdn).
But the Validator object I get from the ValidatorFactory doesn't know about the validation attributes, defined in the metadata-class.
The business object is defined like this:
[MetadataType(typeof(PatientMetadata))]
public partial class Patient
{
private string _Name;
private int _DiagnosisCount;
public int DiagnosisCount
{
get
{
return _DiagnosisCount;
}
set
{
if (value != _DiagnosisCount)
{
_DiagnosisCount = value;
}
}
}
public string Name
{
get
{
return _Name;
}
set
{
if (value != _Name)
{
_Name = value;
}
}
}
}
And the metadata class like this, according to documentation:
public class PatientMetadata
{
[RangeValidator(4)]
public int DiagnosisCount { get; set; }
[StringLengthValidator(64, ErrorMessage = "Name must not exceed 64 chars.")]
public string Name { get; set; }
}
If I know try to do validation this way:
var factory = ValidationFactory.DefaultCompositeValidatorFactory;
var validator = factory.CreateValidator<Patient>();
...then watching into validator (during debugging) already says, that it's just an AndCompositeValidator without any children validators.
Again, if I put the validation attributes right in the Patient class, it works perfectly.
By now, I have no real idea, what I'm missing here, since I think doing everything according to the docs.
Thanks in advance to you guys!
The property names of the metadata class must match the property names of the main class.
In your case your metadata class should look like:
public class PatientMetadata
{
[RangeValidator(0, RangeBoundaryType.Inclusive, 10, RangeBoundaryType.Ignore)]
public int DiagnosisCount { get; set; }
[StringLengthValidator(6, ErrorMessage = "Name must not exceed 6 chars.")]
public string Name { get; set; }
}
Also, the docs indicate the accepted approach is to declare all return types as object. However, the docs also talk about using properties but in their example use fields so take it under advisement. :)

Tag to edit DataMember of user control in visual studio designer

I have the [AttributeProvider (typeof(IListSource))] tag which lets me edit the DataSource field via dropdown list in the visual studio editor. Is there a similar tag to use so i can edit the DataMember property the same way. Right now i have to type in the value for DataMember which take a lot of time if i have to keep looking up the field names...
[AttributeProvider(typeof(IListSource))]
public object DataSource
{
get
{
return this.dataSource;
}
set
{
this.dataSource = value;
BindTextBox();
}
}
[Editor("System.Windows.Forms.Design.DataMemberFieldEditor", typeof(System.Drawing.Design.UITypeEditor))]
public String DataMember
{
get
{
return this.dataMember;
}
set
{
this.dataMember = value;
BindTextBox();
}
}
I ended up using [Browsable(true)]. this let me edit the field as a text field but no drop down menu...

A question about writing data to a custom section?

below is my class thanks to the article found at:
URL: Derik Whittaker
My Code:
public class FavsSection : ConfigurationSection
{
public override bool IsReadOnly()
{
return base.IsReadOnly();
}
public FavsSection() // default Constructor.
{ }
[ConfigurationProperty("Items", IsRequired=true)]
public FavouritesCollection FavsItems
{
get
{
return (FavouritesCollection)(base ["Items"]);
}
}
}
[ConfigurationCollection(typeof(FavouriteElement))]
public class FavouritesCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new FavouriteElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((FavouriteElement)(element)).ItemType;
}
public FavouriteElement this[int idx]
{
get
{
return (FavouriteElement)BaseGet(idx);
}
}
public override bool IsReadOnly()
{
return base.IsReadOnly();
}
}
public class FavouriteElement : ConfigurationElement
{
[ConfigurationProperty("id", DefaultValue = "", IsKey = true, IsRequired = true)]
public string ID
{
get
{
return ((string)(base["id"]));
}
set
{
base["id"] = value;
}
}
[ConfigurationProperty("path", DefaultValue = "", IsKey = false, IsRequired = false)]
public string Path
{
get
{
return ((string)(base["path"]));
}
set
{
base["path"] = value;
}
}
}
My config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="FavouritesMenu" type="MyFileExplorer.FavsSection, MyFileExplorer" />
</configSections>
<FavouritesMenu>
<Items>
<add id="1" path="c:\foo" />
<add id="2" path="C:\foo1" />
</Items>
</FavouritesMenu>
</configuration>
As you can see I am trying to write data into my custom section called 'Favourites Menu'. I think I have got the basic gist of the idea but I don;t see how to make my next step ... something got do with the 'IsReadOnly' method? Can someone please help me fill in the blanks? Feel free to rename things to make it easier to read? I thought I would make a half decent effort before I asked for help ...
RESEARCH: StackOverFlow - SAME QUESTION!
---------- Got lost on Pike65's comment ... cannot write to collection because it is set to read only.
I presume the collection needs setting to IsReadOnly false and some helper methods are needed to add data into the collection? This part is all alittle hazy to me ...
Thanks for reading,
Ibrar
I have been doing some basic testing and to 'NO' surprise ... the above actually works. You just need to make sure that when you want to pass data to your config section, then by default they are read only. So you will need to override the 'isReadOnly()' method inorder for the above code to work.
So the solution is that the above peice of code, does work ... you just need to override an extra method to allow you to access the collection responsible for holding your element data and manipulate its contents via the properties you define in the class that extends or inherits from the Configuration Element class.
UPDATE:
The above code sample I pasted in allows you to edit what already exists in the config file inside your custom section. In order to add a new item for example like the following:
FavsSection favconfig = (FavsSection)config.GetSection("FavouritesMenu");
ToolStripMenuItem menu = (ToolStripMenuItem)returnMenuComponents("favouritesToolStripMenuItem", form);
ToolStripItemCollection items = menu.DropDownItems;
for (int i = 0; i < items.Count; i++)
{
//favconfig.FavsItems[i].ID = i.ToString();
//favconfig.FavsItems[i].Path = items[i].Text;
favconfig.FavsItems[i] = new FavouriteElement()
{
ID = i.ToString(),
Path = items[i].Text
};
}
As you can see above, I am physically adding a new 'FavouriteElement' object into the collection returned by the property 'favconfig.FavItems'. In order to to do this, one property needs extending to support this.
public FavouriteElement this[int idx]
{
get
{
return (FavouriteElement)BaseGet(idx);
}
set
{
base.BaseAdd(value);
}
}
This indexer or paramterful property as 'Jeffrey Richter' calls them needs to have it's 'Set' accessor implemented as shown above in the code snippet. I have pasted it in here as it did not take long to figure out and most of the code is changed using a template I have used from Derik Whittaker's Article. Hopefully this will alow other coders to implement something similar.
Another solution would be to simply rather than 'getting' the collection all the time that 'lassoes' together all my 'FavouriteElements', you could implement the 'set' accessor for the related property. I have not tested this but I might be worth trying out.

Categories

Resources