I am not sure how to use my application settings in my mvc4 application.
For example I have an setting (stored in db), wether to use logging or not.
Should I load the setting once at application startup and then store it in the session-variable and check it against that? Or should I everytime i invoke an actionresult load the setting from database?
Whats the best practise here?
You can keep this setting in web.config file:
<appSettings>
<add key="enableLogging" value="false"/>
</appSettings>
And access it like this (requires reference to System.Configuration assembly):
ConfigurationManager.AppSettings["enableLogging"];
Note that this stores only string values, so you could parse it or just compare against string.
in this case store it in :
HttpContext.Current.Cache
storing it there will be available to all the requests and set the expire to 24 hours for example
this is not permanent storage , so whenever it expire you need to read it from DB
Related
I've multiple pages that require encryption/decryption of query string. I've written the code for that and its working.
Now my requirement is to enable/disable it using web.config. Like from Web.config only, we can turn the ecryption/decryption process on or off.I don't want to go to every page and change it.
Is it possible using HTTPModules in Web.Config which will be checked from every page that tells whether to encrypt/decrypt or not?
we can have key/value pair settings in appsettings in web.config.
<appSettings>
<add key="EnableURLEncryption" value="false"/>
</appSettings>
i have a webapi project that uses cache library.I am using cache duration key that is used inside cache library.My question is what is the standard practice where should i put Cache duration key,from Where to pick the value of cache duration, inside appconfig of cache library or from web.config of webapi?
The web.config is the place to go in a web application. There's no such thing as app.config in an ASP.NET application. You could always build some mechanism to load configuration data from custom places but the first place a developer would look for such things is the web.config.
I'm developing a software in .NET 4.0, which reads and writes application settings. On finish the software will be stored on a file server. No local instances will be executed.
By default the user settings XML file is stored in every users AppData\... directory, but I want to change the file location to the same directory the executable is stored.
This means, that all users should use the same XML user-settings file with modified contents.
I've read this question and answeres where a user describes how to realize that in JSON format.
Question:
Isn't there any other (simple) way to tell the Settings class, where to read from and write to user settings?
The following has been discussed:
Users will always have enough access rights to modify the settings file.
Modifications on settings should be picked up by other users.
Users will start the application from different network computers.
I could implement my own XML file handled by the application (I'll keep this in mind).
I'm not sure if you can get the functionality that you want with the standard Settings class. But I do think that the end result your searching for can be accomplished.
If you want changes in settings user 1 makes to be instantly enforced for user 2, you should look at storing the settings in a database. Your application can then be periodically check this table for changes. For instance if user 1 changes the color of a control, then every time user 2 loads a screen with that control you check the database for the color.
Or, if you want the settings to be applied on start-up of you application. Use a datacontract + xml serializer to write settings to a file of your choosing on a network accessible path/folder. Then make sure you can handle read/write locking of this file.
These are just general ideas that I think you should consider. I dont claim these are your only options though. If you whish to pursue any of these things there are a bunch of blogs and stackoverflow pages with all the information you need.
good luck!
I added a custom Application Configuration File called AppSettings.config to my project and set its Copy to output property to Copy if newer (this copies the config file into the executables folder on building the project.
My settings must be classified as appSettings, not applicationSettings (non-editable) or userSettings (stored in the users AppData folder). Here's an example:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- single values -->
<add key="Name" value="Chris" />
<add key="Age" value="25" />
<!-- lists, semi-colon separated-->
<add key="Hobbies" value="Football;Volleyball;Wakeboarding" />
</appSettings>
</configuration>
Look at the code below, how to access and modify them:
Configuration AppConfiguration =
ConfigurationManager.OpenMappedExeConfiguration(
new ExeConfigurationFileMap {ExeConfigFilename = "AppSettings.config"}, ConfigurationUserLevel.None);
var settings = AppConfiguration.AppSettings.Settings;
// access
var name = settings["Name"].Value;
var age = settings["Age"].Value;
var hobbies = settings["Hobbies"].Value.Split(new[]{';'});
// modify
settings["Age"].Value = "50";
// store (writes the physical file)
AppConfiguration.Save(ConfigurationSaveMode.Modified);
I used the built-in app.config for default application settings and wanted to separate them from the editable global settings in AppSettings.config. That's why I use a custom config file.
That's not directly an answer to the question, but it solves the problem on how to store and share editable application settings in custom configuration files.
Hope it helps any other users! :-)
In my web.config file I have two SQL Server connection strings, one for local and one for live:
<connectionStrings>
<remove name="LocalSqlServer" />
<add name="LocalSqlServer" connectionString="[removed]" providerName="System.Data.SqlClient"/>
<add name="LiveSqlServer" connectionString="[removed]" providerName="System.Data.SqlClient"/>
</connectionStrings>
I then have a "utils" singleton class which basically sets the connection string depending if I'm running the site on "localhost" or on my live server:
if (Environment.MachineName.ToUpper() == MyOwnConfig.GetAppSettingsValue(ConfigKeys.localhost).ToUpper()) {
this.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString();
//MembershipProvider provider = Membership.Providers["LocalAspNetMemberSqlProvider"];
//RoleProvider role = Roles.Providers["LocalAspNetMemberSqlProvider"];
}
else {
this.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["LiveSqlServer"].ToString();
//MembershipProvider provider = Membership.Providers["LiveAspNetMemberSqlProvider"];
//RoleProvider role = Roles.Providers["LiveAspNetMemberSqlProvider"];
}
My Database class then simply uses the connectionString property of my utils class. All this works fine so when I place the site locally I can then simply upload it to live without making changes to the connection strings etc in the config file and it starts using my live database.
Now I'm currently implementing "membership" into my site and for ajax for use some webmethods I'm storing the providerUserKey in a text field of the current logged in user. my web method then checks that this key is authenticated. e.g.
ajaxCreds.ajaxID1 = ((MembershipUser)Membership.GetUser()).ProviderUserKey.ToString();
QUESTION:
the question I have is How do I know if this membership is from the LIVE database or my LOCAL database. As you can see from the web config I've added in the membership/provider lines (commented out) but I don't know how to use them with the above membership.getUser() command.
Alternative... Is this a good way to go? or is it simpler to edit the web.config file when I upload to live?
Many thanks
Most people don't do it this way though I applaud you for figuring all this out. Typically, people use the deployment manager or some other build system to have a different web.config value on the server verses local.
Here is a link on changing in deployment: How do I use Web.Config transform on my connection strings?
I would suggest you to read this article:
http://blogs.msdn.com/b/schlepticons/archive/2010/07/22/modifying-asp-net-providers-at-runtime.aspx
It will show you, that also others were trying to do the similar. And this is how to succeed. Solution (if adjusted) could be similar to your needs.
put all the providers into your web.config
On App_Start adjust which will be the default (based on the Environment)
Membership API will be available as you need for Provider Key
No need to search for Provider by Name
NOTE: you have to tweak the void Application_Start(object sender, EventArgs e) implementation but the idea is there
NOTE2: What you are trying to do is definitely not exception. Configuration based on environment is pretty smart! What must be achieved is standard API usage, e.g. calls via Manager pattern
System.Web.Security.Membership
System.Web.Security.Roles
and not calls to the providers by name.
For my MVC4 application, run in Azure, I store the sessions in a co-located cache. As described in this How-to that Microsoft provide.
I run two small instances, and everything seems to work fine. I can log in to the application, and I remain logged in when I browse around within the application. So the session seem to work on both instances.
However, when I update the session data something like this:
HttpContext.Current.Session["someVar"] = "new value";
That change only seem to have an effect on the instance that handle that particular request. Now as I browse around the application, sometimes I get the initial value and sometimes I get the updated value.
I haven't made any changes to the web.config, so it looks exactly as it do when it gets added by the Nuget package:
<sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
<providers>
<add name="AppFabricCacheSessionStoreProvider"
type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
cacheName="default"
useBlobMode="true"
dataCacheClientName="default" />
</providers>
</sessionState>
Do I need to handle sessions in another way when using the Azure cache, or is it something else I'm missing here?
You need to assign an applicationName so that the distributed cache can view the shared state within the same application boundary. See MSDN forum post for reference.
<add name="AppFabricCacheSessionStoreProvider"
type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
applicationName="azureMVC4App"
cacheName="default"
useBlobMode="true"
dataCacheClientName="default" />
If you want to share cache state across application boundaries, you need to assign sharedId