How make stringConnection throw a txt file MVC Entity Framework - c#

Is there a way to acomplish that? I know how to do it with the web.config file but I was told that cannot be in web.config cuz it must be in a text file where the connection string must be.
Here is what i have tried:
<configuration>
<connectionStrings configSource="ConexionBaseDeDatos.txt"></connectionStrings>
</configuration>
Similar like if i'd it use the a .config file like this
<configuration>
<connectionStrings configSource="ConexionBaseDeDatos.config"></connectionStrings>
</configuration>
And the base name
using System.Data.Entity;
namespace appSwicth.Models {
public class ConexionBaseDeDatos:DbContext {
DbContext db;
public ConexionBaseDeDatos() :base()
{
}
}
}
But I got an error:
"Root Element is missing"
And then the url of the file and nothing more.(the url is totally correct). In the txt file i have nothing now. Could that be the reason of why? I added a connectiong string to it but still not worked, maybe im doing something wrong.
Any way to solve this? If you need more, let me know.

Following is the Standard Format to mention the External Configuration file only.
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings configSource="Your_File_Name.config"/>
</configuration>
It's self explanatory from it's name Config Source
The Source belongs to Configuration files only.
From MSDN - Storing and Retrieving Connection Strings
Alternative - From the above comments
Fetch the information from App Settings like below.
<add key="ConexionBaseDeDatos" value="ConexionBaseDeDatos.txt"/>

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.

How to read web.config section as XML in C#?

This is copied example from:
How to read custom config section in app.config in c#
I want to read following custom section from app.config:
<StartupFolders>
<Folders name="a">
<add folderType="Inst" path="c:\foo" />
<add folderType="Prof" path="C:\foo1" />
</Folders>
<Folders name="b">
<add folderType="Inst" path="c:\foo" />
<add folderType="Prof" path="C:\foo1" />
</Folders>
</StartupFolders>
And this is my case too. However, I don't want to create custom class for handling values, defining this class in web.config, and then finally using it. It is heavy-weight for my needs.
Instead I would like to do something very simple -- retrieve a section as XML. Then I could use regular Linq.Xml to parse it. This way, I don't need to create new classes per each section, I don't need to declare them. For my purpose it is sufficient on one hand, and minimal at the other (I do it once, key-value mapper for nested sections). I.e. perfect.
The only missing piece is (my question) -- how to get a web.config section as XML?
Note about the section:
it cannot be encoded, because it has to be edited by hand
it cannot be serialized for the same reason
So I am not looking for a workaround how to squeeze entire section as value in appSettings, but I am really looking for a method to get proper section as XML.
I would like to get it from ConfigManager (!), because this way I don't have to deal with resolving which web.config should I read, etc. I.e. less chance to make mistake than mimicing web.config precedence manually.
Forgive me for reminding this, but please avoid "answers", you shouldn't do this, use custom class per each section, etc. I already considered this, and opted against it.
I think you either have to do it manually and load the Web config into memory:
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/Web.config"));
Or you will need to create the custom configuration sections you want to avoid.
You can define a re-usable custom config section that exposes the section XML as you desire. The key is, that you don't have to define a different class for each custom config section.
For clarity, my project namespace is "ConsoleApp1" as is the assembly name (this appears in type definitions).
First, create a custom config section that exposes the XML reader:
public class XmlConfigSection : ConfigurationSection
{
public XmlReader Xml { get; private set; }
override protected void DeserializeSection(XmlReader reader)
{
Xml = reader;
}
}
You can then define any of your custom sections to use this class in the app.config:
<configSections>
<section name="StartupFolders" type="ConsoleApp1.XmlConfigSection, ConsoleApp1" />
<section name="AnotherCustomSection" type="ConsoleApp1.XmlConfigSection, ConsoleApp1" />
</configSections>
Then in your code, you can access raw XmlReader of the config section like this:
var xmlReader = (ConfigurationManager.GetSection("StartupFolders") as XmlConfigSection).Xml;
If you then want an XML string instead of the reader you can do something like this (though I'd suggest sticking with the XmlReader):
StringBuilder sb = new StringBuilder();
while (xmlReader.Read())
sb.AppendLine(xmlReader.ReadOuterXml());
var xmlStr = sb.ToString();
Totally untested but could you use something like this? :
ConfigurationSection exampleSection =
(ConfigurationSection)ConfigurationManager
.GetSection("system.web/exampleSection");
Then possibly use exampleSection.ElementInformation to get more info?

Using ConfigurationManager's OpenExeConfiguration and GetSection,(Custom config file and section)

Is it possible to retrieve a custom configuration section from a config file other than the app.config or web.config.
I tried using the System.Configuration.ConfigurationManager's OpenExeConfiguration and GetSection method calls together but without luck. My intention is to define custom configuration sections for interchangeable process adapters and contain the custom config section in a separate config file other than app.config and web.config. I see plenty of examples for appsettings and connectionstrings.
static private DigiKeyReadTaskConfigSection digiKeyReadTaskConfigSection;
static DigiKeyReadTaskConfigSection DigiKeyReadTaskConfigSection {
get {
if (digiKeyReadTaskConfigSection == null) {
digiKeyReadTaskConfigSection = (DigiKeyReadTaskConfigSection)ConfigurationManager.OpenExeConfiguration("ReadTask.config").GetSection("DigiKeyReadTaskConfigSection");
}
return digiKeyReadTaskConfigSection;
}
}
The digiKeyReadTaskConfigSection = (DigiKeyReadTaskConfigSection)ConfigurationManager.OpenExeConfiguration call seems to be working however the (DigiKeyReadTaskConfigSection)ConfigurationManager.OpenExeConfiguration("ReadTask.config").GetSection("DigiKeyReadTaskConfigSection") returns null.
The ReadTask.config file lives in the bin file of the App:
<configuration> <configSections>
<section name="DigiKeyReadTaskConfigSection" type="DataReadInc.WebSiteRead.TaskConfigSection.DigiKeyReadTaskConfigSection, DataReadInc.WebSiteRead" />
<section name="ArrowReadTaskConfigSection" type="DataReadInc.WebSiteRead.TaskConfigSection.ArrowReadTaskConfigSection, DataReadInc.WebSiteRead" /> </configSections> <DigiKeyReadTaskConfigSection DigiKeySiteURL="http://search.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&site=us&keywords="
SiteLogInURL="https://ordering.digikey.com/RegisteredUser/Login.aspx,formName=" SiteLoginId="X" SiteLoginPassword="X" /> <ArrowReadTaskConfigSection ArrowAmericaSiteURL="http://components.arrow.com/part/search/"
SiteLoginURL="http://components.arrow.com/login/processlogin#" SiteLoginId="X" SiteLoginPassword="X" /> </configuration>
I have seen this type of setup with Spring.Net and a J2EE implementation so I am sure it is possible. I can just put my custom config sections in the App.config or web.config file, however it would be significantly cleaner for them to exist in their own config file.
Use ConfigurationManager.OpenMappedExeConfiguration(). OpenExeConfiguration relates to a certain exe.

How to open a config file app settings using ConfigurationManager?

My config file is located here:
"~/Admin/Web.config"
I tried opening it via the below code but it didn't work:
var physicalFilePath = HttpContext.Current.Server.MapPath("~/Admin/Web.config");
var configMap = new ConfigurationFileMap(physicalFilePath);
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(configMap);
var appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
when appsettings line runs, it throws the below error message:
Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.
My Web.Config looks like below:
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings>
<add key="AdminUsername" value="Test1"/>
<add key="AdminPassword" value="Test2"/>
</appSettings>
<connectionStrings></connectionStrings>
</configuration>
How could I get the appsettings?
For web-app, you need to use System.Web.Configuration.WebConfigurationManager class and no need to set absolute path.
var web=System.Web.Configuration.WebConfigurationManager
.OpenWebConfiguration("~/admin/web.config");
String appValue=web.AppSettings.Settings["key"].Value;
If you are looking for adding some stuff to the Web.config, and then reading it from the code.
What you need is Custom Configuration Sections in Web.config
Look here:
How do I define custom web.config sections with potential child elements and attributes for the properties?
and here:
Creating Custom Configuration Sections in Web.config - 4GuysFromRolla.com

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.

Categories

Resources