banner



Can I Put A Wcf Service File In Any Web Application

In i of my previous posts, I wrote about the .Internet build configuration system. I mentioned the app.config file, merely didn't really swoop into it. So let's accept a closer look at this file at present.

When you create a (non-spider web) .NET Framework application in Visual Studio, an app.config file is added to your project. When you create a class library or a .Internet Cadre project, such a file is non included, although it tin exist done afterward.

In a web project (i.e. ASP.Cyberspace) you will use a similar file, the spider web.config. A lot of what I volition cover in this article is applicable to spider web projects, but there are subtle differences. That is why I'll only focus on the app.config.

The app.config file is an XML file whose goal information technology is to contain whatsoever variable configuration of your application. It is a central place to put:

  • Connection strings to databases
  • Connection details to external services
  • Application settings
  • Other details on how the application should be run and/or hosted

An app.config file is automatically added to your project when you create a new awarding under the Windows Classic Desktop header in Visual Studio:

You lot can start typing under the <configuration> section and Visual Studio'due south Intellisense volition provide you with the possible options:

The most well-known sections are "appSettings" and the "connectionStrings".

AppSettings

AppSettings provide an easy style to access string values, based on a sure key. Take these appSettings for instance:

Nosotros can access this value past using this slice of code:

Every bit a side note: you will need to import the System.Configuration namespace too, by calculation "using System.Configuration" at the top of your file.

A possible problem with AppSettings is that nosotros volition go back a string. Yet in the in a higher place example, we're clearly working with an integer. Nosotros volition accept to parse the value for it to be more meaningful. Another issue is that there is no compile-time checking that we entered the correct central, equally it is just a string.

If your needs are simple, y'all could be fine with this. If things commencement to get a picayune more complicated, you might want to look into "Settings", which I'll cover after.

ConnectionStrings

The connectionStrings section is the identify to put your connection strings to any databases you want to admission. This is a uncomplicated example:

Find how there is too a "providerName". This tells ORM libraries similar Entity Framework which provider they should be using. The provider will differ depending on the database you're trying to admission (e.g. SQL Server, PostgreSQL, MariaDB, etc.).

If you need to access the connexion string directly, you can utilize code similar this:

Settings

Call back how the AppSettings only provided united states of america with cord values? The Settings system was introduced in .NET two.0 to ameliorate this. To use this, double click the properties of your projection:

Then become to the settings tab. In the beginning, your project will not yet take a default settings file, so click on the link to create one. You'll see a nice UI where yous can define your settings, their values, scopes, and types:

I've added our "pollInterval" in these settings, and at present I can access it like this:

The nice thing is that we have compile-time checking now, and we're certain the "pollInterval" variable is an integer.

The Settings system has now created two new files under the Properties folder: Settings.Designer.cs and Settings.settings. You do not need to await into these files, and information technology'due south best non to change them manually. They are automatically generated, so any changes will be overwritten anyhow.

The outcome of these two files is a class containing the settings every bit properties. By the mode, you can change the access (public or internal) by using the dropdown in the Settings tab of the projection backdrop.

Working with the Settings system will also change your app.config. In the to a higher place example, our app.config at present includes this:

For more than on the .Internet settings system and the departure in scopes, check out the MSDN documentation.

Custom Configuration Sections

There is a next step in app.config possibilities: custom configuration sections. These merit a carve up article, and so I will only comprehend them here soon.

As I mentioned at the get-go of this article, a class library doesn't contain an app.config file. Just sometimes, the author of a course library might want to allow other developers to configure certain parts of the library in the host's app.config file.

Ane choice would be for the author to certificate the necessary AppSettings. But the AppSettings have the disadvantages I've already mentioned, and they don't permit for whatsoever deeper hierarchy.

Custom configuration sections give the class library author the solution to this. When the author has set information technology all up correctly, the developer using the library can add together something like this to the app.config file:

<configuration>   <configSections>     <sectionGroup name="pageAppearanceGroup">       <department          name="pageAppearance"          type="Samples.AspNet.PageAppearanceSection"          allowLocation="true"          allowDefinition="Everywhere"       />     </sectionGroup>   </configSections>    ...    <pageAppearanceGroup>     <pageAppearance remoteOnly="truthful">       <font proper noun="TimesNewRoman" size="xviii"/>       <color background="000000" foreground="FFFFFF"/>     </pageAppearance>   </pageAppearanceGroup>  </configuration>

This is taken from the .NET docs, and even though it concerns ASP.NET, the aforementioned mechanism is used in archetype desktop apps.

As you lot can come across in the above example, the developer using the library

  • showtime defines a new sectionGroup under the configSections tag
  • then defines a section under that, pointing to the correct type that will handle the config section
  • and finally provides the configuration details.

Y'all tin can run into that the pageAppearance is more complex than the elementary AppSettings or Settings sections tin can handle.

As I said, this is beyond the purpose of this article, only I encourage y'all to cheque out the documentation I linked to above.

There'southward More

So far, we've but covered application settings. Simply we can consider connection strings as a sort of application setting as well.

Merely the app.config file can comprise more than that. Call back how a default app.config contained this:

This is where we define which .Net runtime(s) the application supports. Y'all could change this if your application needs to run on other (higher or lower) runtimes.

The assemblyBinding tag is another tag y'all will run across hands. In short, it allows you to signal to a certain version of an assembly, fifty-fifty when a unlike version is required. Once more, this is out of the scope of this article, but the documentation should help you lot further.

Some other example is the arrangement.serviceModel tag, which is the place to configure any connections to WCF services.

What Happens When Nosotros Compile This?

Proficient, by now you know what the app.config is for and how to use it. Now you might be wondering what happens behind the scenes. Well, when you compile your application, the compiler actually copies the app.config file to the output folder, simply gives information technology some other proper noun:

When you start your application (ConsoleApp1.exe in our example), the matching config file will be loaded too.

It is possible to alter this file while the application is running, simply you will need to restart the application for the changes to accept event. Luckily, there are ways around this:

  • A phone call to ConfigurationManager.RefreshSection("…") will reload the given section
  • For applicationSettings, y'all will need to call Backdrop.Settings.Default.Reload();

Keep in mind that a new compilation or deployment can overwrite the changed values. So it's meliorate to brand the changes in your source lawmaking (which is under source control, right?) and redeploy.

Secrets

You should consider not putting confidential information in your config files. Things like passwords and API keys should be kept out of the app.config file. In an age where more and more code is made open source, you could take chances exposing your secrets to the outside world. Even if your repository is individual, it's a best practice to put the secrets elsewhere. Get-go, if you lot notice it normal to exercise and then, you won't practise it when you're working on a public and open source project. Simply second, y'all never know when your private repository may become public, on purpose or past accident.

Y'all can easily solve this by putting your secrets in separate files:

See how both the appSettings and the connectionStrings point to some other file? Also notation that nosotros tin can combine an external file with appSettings, but for connectionStrings we need to choose.

If we make sure nosotros don't put these files under source control, they can remain absolutely private. Another thing to remember is to tell the compiler to copy these files to the output directory:

After that, you lot can use the appSettings and connectionStrings in your code like you did before.

A Final Tip

Want to know if y'all're getting it correct as y'all larn C#?

Get an instant, automatic code review with CodeIt.Correct.

I want to revisit the point I made near the appSettings non being type-safe. If you lot have multiple places where y'all admission your appSettings, you might not like having to repeat the (string) key everywhere, and having to convert the string value to the correct type every time. A simple solution to this is to create your own class that wraps the telephone call to ConfigurationManager:

In all other locations of your lawmaking, you can now call this class and be sure y'all're getting an integer.

Happy Configuring!

This article aimed at showing y'all the basics of the app.config file, and some best practices. The app.config file is a basic slice of the .Cyberspace Framework, yet I've seen several projects putting their configuration in other places (like apparently text files or the registry). Unless you have a very good reason to practice so, it's more convenient and familiar to use the app.config file. You tin can alter information technology hands, the .NET Framework supports it out of the box and almost all .Net developers know how it works.

Learn more how CodeIt.Correct can help y'all automate code reviews and better the quality of your code.

Source: https://blog.submain.com/app-config-basics-best-practices/

Posted by: lamontbost1962.blogspot.com

0 Response to "Can I Put A Wcf Service File In Any Web Application"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel