I have a class library that has a function with this code:
this.apikey = ConfigurationManager.AppSettings["ApiKey"];
When I call this function in a console application, it says AppSettings has no keys. also it states the connection string is aspnet... whereas mine is sqlserver. So it is certainly not reading my library app config even though Im calling that in a library function.
Is this normal or am I doing something wrong?
I was hoping to avoid having to make and parse an xml and reinvent the wheel.
Thanks
Is this normal or am I doing something wrong?
It is normal and you are doing something wrong.
A library does not, usually, have its own configuration - it is subject to the configuration of the running application.
If you add your appSettings and connectionStrings to the application configuration all will work.
In other words, when an application loads and the libraries it uses are loaded, the application configuration is read - no other configuration file is read. When calling the static methods of ConfigurationManager, the loaded configuration is what's in effect.
There are ways to load specific configuration files, but that's not the default behaviour.
You are certainly wrong at some place. May be you have written your keys in different section than the appSettings. Just check it, and if it is correct then , you will need to reinvent the wheel as below:
XDocument.Load(HttpContext.Current.Server.MapPath("~/web.config"));
Be sure to add System.Web namespace to your project before using HttpContext
Related
I am using NLog for some logging and thanks to these answers:
Getting Logger Name into Excel file with NLog
https://stackoverflow.com/questions/50123661/nlog-in-c-sharp-with-severity-and-categories?noredirect=1#comment87344565_50123661
I am able to log different types of events (ex: "Thermal", "Database",etc.) to a single file with the logger field showing the type of event. One simply calls for example:
NLog.LogManager.GetLogger("Database").Debug("Error writing to DB");
This all works fine and might be enough. However, you'll notice that any programmer is free to put any name they want in GetLogger AND misspell it. "GetLogger("Datobuse"). It would be nice if the programmer had to choose from an enum or other structure:
NLog.LogManager.GetLogger(LoggerNames.Database).Debug("Error writing to DB");
This seems like it might be a common problem and might already have an elegant solution. I can imagine overriding the LogManager class but am not sure of the specifics. Note that LogManager is a public static class in the NLog library so not clear how to hide it. Also, there is the nice property that if you fill in the config file once in your app project, the config file works perfectly for all the projects in the solution as long as you include NLog as a reference.
I'll go down the path of creating a library project that makes use of NLog library and then include that it my main project UNLESS there is already a great solution. I'm betting there is, but haven't seen one.
Thanks,
Dave
If you have "global" logger names, then the easy solution is just to use global logger instances.
The same global NLog Logger instance can be used by multiple locations without getting into threading issues.
What is the preferred way of reading an application's configuration file in .NET 4? I've seen several articles on how to do with .NET 2. I don't know if things have changed/improved with .NET 4.
The ConfigurationManager is still the preferred way of reading the application config and web config files.
To use it you will first need to add a reference in your project to System.Configuration.
Then you will need to add a reference to it in your class with:
using System.Configuration;
Once you have done this you will be able to access things like your AppSettings and ConnectionStrings by calling these static properties on the ConfigurationManager class.
e.g.
ConfigurationManager.AppSettings["settingname"];
Most developers seem to be happy with the string-based ConfigurationManager.AppSettings style of configuration, but there is another way: strongly typed configuration.
The MSDN reference is here: http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx
In a nutshell, you can define your own configuration setting section and have your own strongly typed configuration items in there. Amongst other things this
(as the name implies) can force use of enumerated options
allows you to define user-based or application-based settings
allows you to define defaults
The main downside is that it's a bit of a faff to get going as there's quite a bit of code to implement and test.
I need to create a Error logging project from scratch in C#.
I would like to save to a file with several levels, this logging project I am taking as an assignment from which I can learn many things and want to build it as small loggin utility for now.
I saw few loggin project which has singleton pattern and a config file having some entries and also in the consuming application config - some references of logger proj interface are there
can some one please give me an idea as how can I create a new logger
proj from scratch and what is the purpose of having entries in
config ?
pseudo code for logger project or any link
Thanks in advance.
Instead of implementing your own logging mechanism you may want to check whether existing components are an option. For example log4net is a frequently used framework that people use for .NET based projects.
Also, the Logging Application Block from Microsoft:
http://msdn.microsoft.com/en-us/library/ff632023.aspx
http://msdn.microsoft.com/en-us/library/ff664569(v=PandP.50).aspx
There are several key elements you need to consider before making one from scratch. Just to name what comes to my head :
How do you want to log? Do you want to save logs to a file, in a database, to send mails, just to have the logs shown in a console?
If you persist the logs, do you want to log everything, forever, or you want a "rolling" X lines to be kept, the rest discarded?
Do you want to have several level of logs? For example, you could log some things Info, Warning, Error, Critical Error, etc.
Do you want your logging library to support custom formatting for the logs?
As for the question about the config, it's really something you want to do. If you're talking about the app.config files, it allows you to can change the configuration of your application without rebuilding it. It can also provide some default parameters the user can override. By user, I mean another developer using your library.
I've currently written code to use the ServiceContractGenerator to generate web service client code based on a wsdl, and then compile it into an assembly in memory using the code dom. I'm then using reflection to set up the binding, endpoint, service values/types, and then ultimately invoke the web service method based on xml configuration that can be altered at run time.
This all currently works fine. However, the problem I'm currently running into, is that I'm hitting several exotic web services that require lots of custom binding/security settings. This is forcing me to add more and more configuration into my custom xml configurations, as well as the corresponding updates to my code to interpret and set those binding/security settings in code.
Ultimately, this makes adding these 'exotic' services slower, and I can see myself eventually reimplementing the 'system.serviceModel' section of the web or app.config file, which is never a good thing.
My question is, and this is where my lack of experience .net and C# shows, is there a way to define the configuration normally found in the web.config or app.config 'system.serviceModel' section somewhere else, and at run time supply this to configuration to the web service client?
Is there a way to attach an app.config directly to an assembly as a resource or any other way to supply this configuration to the client?
Basically, I'd like attach an app.config only containing a 'system.serviceModel' to the assembly containing a web service client so that it can use its configuration. This way I wouldn't need to handle every configuration under the sun, I could let .net do it for me.
Fyi, it's not an option for me to put the configuration for every service in the app.config for the running application.
Any help would be greatly appreciated.
Thanks in advance!
Bryan
Create a custom class deriving from
ChannelFactory.
Override the protected
CreateDescription method. In the
override, you need to...
Call base.CreateDescription().
Read in your custom configuration.
Create a custom ServiceEndpoint based
on your configuration. Don't forget
the bindings, behaviors, etc.
Return that custom ServiceEndpoint.
More details HERE
The following couple links talk about loading WCF Configuration settings from config files other than the app.config. May be what you are looking for but not certain.
http://blogs.msdn.com/dotnetinterop/archive/2008/09/22/custom-service-config-file-for-a-wcf-service-hosted-in-iis.aspx
http://weblogs.asp.net/cibrax/archive/2007/10/19/loading-the-wcf-configuration-from-different-files-on-the-client-side.aspx
Are your proxy classes deriving from ClientBase<T>? If so, then there is a constructor that accepts a Binding and an EndpointAddress. You should be able to use those instead of the corresponding configuration data.
Could someone tell me the advantages to using the ConfigurationManager class which load's a config file for manipulation VS an XML file with a class you build to read it yourself?
Recently, I built a class which inherits from ConfigurationSection in order to manipulate a custom section within app.config. This was quite a bit of work compared to just opening and reading an XML file.
Some people chose the first approach, others chose the second.
What's good practice?
This is an old question, but what the hell... so yes, there is quite some code overhead in writing configuration sections and elements, but what you get as compared to using your own class with an XML serializer include:
Type conversions and validations: if one of your configuration settings is, say, a "Type" (maybe you store in your configuration what kind of implementation you need to create for some provider), then the ConfigurationManager will not only convert whatever was written in the .config file to a System.Type, but you can also add validation attribtues on your ConfigurationElement's property, like "SubclassTypeValidatorAttribute", which will check that the given type derives from your base provider class/interface. You can of course add your own validators, so that in the rest of your code, you just "get" the configuration and you know everything's valid.
Multi-level settings hierarchy: you can play around with storing settings at the machine, application or user levels, which gives you a mechanism to handle default vs. user-specific settings. You also have APIs to load configurations from custom locations.
No duplication in config files: if you're using other .NET features like TraceSources and stuff, the configuration for that is already in the .config file (say you're troubleshooting a problem and you want to turn on some debug trace that's off by default... you do that by just modifying the .config). If you're using your own config file for your custom settings, then you end up with 2 configuration files, which is not so good.
There's probably other benefits, but that's what comes to mind so far.
It's just a recommended and easier way of reading and writing data to configuration files. Using XML DOM is too low level.
You can always get raw xml configuration from ConfigurationSection using section.SectionInformation.GetRawXml() if needed. Likewise use SetRawXml to set this.
There are a few gotchas though when using ConfigurationManager, for example when you load a config file using OpenMappedExeConfiguration, you get an in memory configuration which is "merged" and has sections from machine.config. You can check if a section came from the file you provided using section.ElementInformation.Source.Equals(source.FilePath).
Reference: MSDN