Is there a way to dynamically change log name at runtime? - c#

I currently am writing to a statically named log file as defined in my serilog config:
<add key="serilog:write-to:File.path" value="%LOCALAPPDATA%\App_Data\Logs\StaticallyNamedLog.log" />
I'd like to be able to change the logfile name at runtime i.e.
<add key="serilog:write-to:File.path" value="%LOCALAPPDATA%\App_Data\Logs\{appname}-Log.log" />
In log4net for example I'd set a log4net global property value for "appname" in code before the settings were read in.
log4net.globalContext.properties["appname"] = "App1"
log4net.config.xmlConfigurator.configure("log4net.config")
Then in the logfile I'd reference it like so
%property{appname}
This would then get substituted into this path.
How can I do the equivalent in Serilog? I've done a lot of searching but can't find anything on this specific problem.
Thanks

Related

Modifying appSettings "file" attribute at runtime

string appConfPath = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;
string fullPath = appConfPath + "\\Local\\RandFolder\\ThisOne\\application.settings.xml";
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.File = fullPath;
config.AppSettings.Settings.Add("Password", "djydyjdjtdtyjddj");
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
var temp = config.AppSettings;
I am currently trying to set the "file" attribute of my appSettings configuration and reference XML's included settings at runtime. I am unable to do this before compile because the XML settings file will change based on the local machines settings.
However, after making the above changes, the temp variable only contains the "Password" item and is unable to retrieve the other settings located in the included file path. I know the file attribute is being set but for some reason the referenced setting are still hidden. The application.settings.xml file looks like this...
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="ServerLocation" />
<add key="PerforceURI" value="yuhsgbyluvgblsg" />
</appSettings>
Any help is greatly appreciated!
I won't try to critique what you are doing, but provide you with a simple explanation of what you are seeing.
ConfigurationManager.RefreshSection refreshes the section in the Configuration instance used by the static ConfigurationManager. It does not effect the Configuration instance you created by calling OpenExeConfiguration; for that to occur you would need to call OpenExeConfiguration again.

Using pre-defined string for "Path" attribute in FileSystemWatcher

I'm making a simple winforms application in C#, with VS2010. My winforms design contains a FileSystemWatcher, which fires a pile of code when a file is created.
My problem is that the path for FileSystemWatcher needs to be defined prior to the program running, as it won't always be the same.
I have a string called startPath which I'd like to use, but it would appear that I can't just add this to the "path" field in the FileSystemWatcher properties in my design.
I was able to get it to work if I edited my form1.designer.cs, but as I swiftly learned this code is regenerated even if a different component of the form is edited!
As you might have guessed, I'm still very much learning C#.net (about a week in), and am by no means experienced! If I'm missing something stupid, please point it out!
The FileSystemWatcher has a path property that can be used to change the path after the FileSystemWatcher object is initialized. Otherwise, you'll have to re-setup your watcher if you use the constructor to set the path to watch.
FileSystemWatcher.Path Property
Storing the path itself can be easily done through the Application Settings as mentioned by #leppie
Reference for settings:
Application Settings Overview
Using Settings in C#
Saving User Settings in Winform Application
I assigned my user defined string as the path at run time like so:
In my form1.cs:
protected override void OnActivated(EventArgs e)
{
base.OnActivated(e);
fileSystemWatcher1.Path = inputPath;
}
I think this is an ok way of doing it (it seems to be working!), the string "inputPath" is defined earlier by getting the corresponding setting from my configuration file. It just didn't seem to want to play nice if I placed it settings.cs.
Add the required path to the appSettings part of your app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="watcherPath" value="\\myPC\myShare\myFolder\" />
</appSettings>
</configuration>
Then you can access this value from with your code, and assign it to the FileWatcher path:
string myPath = System.Configuration.ConfigurationManager.AppSettings["watcherPath"];
FileSystemWatcher fsw = new FileSystemWatcher(myPath);

How to get the key value from the AppSettings.Config file?

I'm trying to get my key value set in the appsettings.Config file but seems not working.
This is what i wrote for that. The code is called from the constructor of an MDI file and its returning only null value. Anybody know why?
var getValue = ConfigurationSettings.AppSettings["ShowQueryTextbox"];
I also tried with ConfigurationManager.AppSettings . That too didnt work.
My AppSettings Code is as follows.
<configuration>
<appSettings>
<add key="ShowQueryTextbox" value="true"/>
</appSettings>
</configuration>
ConfigurationSettings.AppSettings are obsolete, try
ConfigurationManager.AppSettings["ShowQueryTextbox"];
Remember that to use:
ConfigurationManager.AppSettings["MyKey"];
You need to add reference to System.Configuration to your project.
The issue arise on renaming the App.Config file as AppSettings.Config. Thanks for all the guidances and help.
The ConfigurationManager is still up to date - Year 2017.
Btw, if you simply want to convert the appsettings configuration value from string to bool, then use Convert.ToBoolean
if (Convert.ToBoolean(ConfigurationManager.AppSettings["EnableLoggingInfo"]))
{
log.Info(message);
}
In your appsettings configuration (web.config)
<appSettings>
<add key="EnableLoggingInfo" value="true" />
</appSettings>
I am able to get like this:
System.Configuration.ConfigurationManager.AppSettings.Get("KEY").ToString();
Assuming you have added it to the required config file, Can you check the case of the key you are trying to access it's case sensitive so if you have keyed in a different case, it won't be returning the expected value.
This error can also arise if you have the appsettings in the wrong configuration file - example in a WCF application it should be the one in the hosting project
Check Properties.Settings.Default.ShowQueryTextbox.

Sharing application configurations across a solution

I have a solution which has multiple output projects (a website, and admin tool, and a SOAP API layer).
They each share common projects in the solution (the service layer, data layer etc). In one of these common projects, I am looking to store a config layer.
Right now, we have three seperate appsettings config files for each output project -
development.AppSettings.config
testing.AppSettings.config
production.AppSettings.config
So altogether, there are nine config files. Only one is used in each project, as they are referenced by utilising the configSource attribute in the web.config appsettings node.
Anyhoo, it's getting to be a pain any time we want to add/remove values from our config files, because it means that we have to change all nine files to do this. And here's what I'd like to do:
In the common project, we have three config files as above. These would be set to copy to the output directory, so that each project has a copy of them. These would be the 'base' config.
Then in each project, I would like to have three files again, but they wouldn't necessarily have to contain the same values as the base configs. If they did however, then the base config value would be overridden by the value in the output project config. A form of configuration inheritance, I suppose.
On application start, I'd like to be able to get these two config files - the base config, and the project config file. And then set the app settings accordingly.
What I'm wondering though, is what's a nice way of determining which file to use? Also, I'm wondering if this is a good way of sharing application values across a large solution, and if there's another, perhaps more efficient way of doing it?
If I'm in development mode, then I don't want production.appsettings.config, and vice versa if I'm in production mode.
Is there a simple way to get the mode (development/testing/production) that I'm in before I go off and get the configurations?
You can have one set of files (3 configs) and link/share them in whatever projects you need.
http://www.devx.com/vb2themax/Tip/18855
Hope this helps.
You could use the ConfigurationManager.OpenExeConfiguration static method. This will allow you to work with as many config files as you want.
You may also try creating a custom class to store all of your settings. You could then serialize your object to save it as a file. You could extend your base custom config class to fit all your other projects.
After some careful thought, and a trip to the toilet at 03:30, I came across a solution which works.
Let's say that we have some appSettings in our base config file:
<add key="MyKey1" value="MyValue1" />
<add key="MyKey2" value="MyValue2" />
<!-- And so on... -->
<add key="MyKey5" value="MyValue5" />
And in my output project, I have three appSettings:
<!-- This is used to identify which config to use. -->
<add key="Config" value="Development" />
<!-- Different value to the one in the base -->
<add key="MyKey2" value="NewValue2" />
<!-- This key does not exist in the base config -->
<add key="MyKey6" value="MyValue6" />
In my Application_Start, I have a call to GetConfigs():
ConfigHelper.GetConfig(HostingEnvironment.MapPath("~/bin/BaseConfig"));
And the actual GetConfigs function:
public static void GetConfigs()
{
if (configMode == null)
{
configMode = ConfigurationManager.AppSettings.Get("Config").ToLowerInvariant();
}
//Now load the app settings file and retrieve all the config values.
var config = XElement.Load(#"{0}\AppSettings.{1}.config".FormatWith(directory, configMode))
.Elements("add")
.Select(x => new { Key = x.Attribute("key").Value, Value = x.Attribute("value").Value })
//If the current application instance does not contain this key in the config, then add it.
//This way, we create a form of configuration inheritance.
.Where(x => ConfigurationManager.AppSettings.Get(x.Key) == null);
foreach (var configSetting in config)
{
ConfigurationManager.AppSettings.Set(configSetting.Key, configSetting.Value);
}
}
Now, my output project effectively has the following configuration settings:
<add key="Config" value="Development" />
<add key="MyKey1" value="MyValue1" />
<add key="MyKey2" value="NewValue2" />
<!-- And so on... -->
<add key="MyKey5" value="MyValue5" />
<add key="MyKey6" value="MyValue6" />
Simples!

Can't access custom profile properties from web.config?

I have the following two profile properties in my web.config file between the System.Web tags:
<anonymousIdentification enabled="true"/>
<profile>
<properties>
<add name="CustomerName" allowAnonymous="true"/>
<add name="CustomerID" allowAnonymous="true"/>
</properties>
</profile>
When I try to access the Profile.CustomerName or Profile.CustomerID from an aspx.cs file, it doesn't show up. I thought when you create a custom profile property, it automatically updates the aspnetdb with the new properties. Profile doesn't show up in intellisense as well.
This problem occurs if you are creating a Web Application. Web Apps, unlike Websites, don't generate the ProfileCommon class.
You could either follow this method:
http://webproject.scottgu.com/CSharp/Migration2/Migration2.aspx
(Appendix 2)
I haven't personally used the above assembly, so someone else might give some advice on that.
However, you could also try:
Object customerName = HttpContext.Current.Profile.GetPropertyValue("CustomerName")
You won't get intellisense with this method, but as long as you know the property name, it can be accessed like that.
Specify properties in web.config file as follows : -
Now, write the following code : -
Compile and run the code. You will get following output: -

Categories

Resources