Access compilation element in web.config [duplicate] - asp.net

Is there any way to access the <compilation /> tag in a web.config file?
I want to check if the "debug" attribute is set to "true" in the file, but I can't seem to figure out how to do it. I've tried using the WebConfigurationManager, but that doesn't seem to allow me to get to the <compilation /> section.
Update:
I know I could easily just load the file like an XML Document and use XPath, but I was hoping there was already something in the framework that would do this for me. It seems like there would be something since there are already ways to get App Settings and Connection Strings.
I've also tried using the WebConfigurationManager.GetSection() method in a few ways:
WebConfigurationManager.GetSection("compilation")// Name of the tag in the file
WebConfigurationManager.GetSection("CompilationSection") // Name of the class that I'd expect would be returned by this method
WebConfigurationManager.GetSection("system.web") // Parent tag of the 'compilation' tag
All of the above methods return null. I'm assuming there is a way to get to this configuration section since there is a class that already exists ('CompilationSection'), I just can't figure out how to get it.

Use:
using System.Configuration;
using System.Web.Configuration;
...
CompilationSection configSection =
(CompilationSection) ConfigurationManager.GetSection( "system.web/compilation" );
You can then check the configSection.Debug property.
TIP: if you need to know how to get a value from a config file, check the machine.config file in your \Windows\Microsoft.net\Framework\<version>\CONFIG folder. In there you can see how all the configuration section handlers are defined. Once you know the name of the config handler (in this case, CompilationSection), you can look it up in the .Net docs.

The easy way to check if you're running in debug mode is to use the HttpContext.IsDebuggingEnabled property. It gets its answer from the compilation element's debug attribute which is the same thing you're trying to do.

After all, you can always load up the Web.config file into an XmlDocument and use an XPath query to find out!
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/Web.config"));
doc.SelectSingleNode("/configuration/system.web/compilation/#debug");
However, I suggest you use the Configuration.GetSection method for solution.
CompilationSection section =
Configuration.GetSection("system.web/compilation") as CompilationSection;
bool debug = section != null && section.Debug;

You can always check debug option on the compiler level by enclosing your code with
#if (DEBUG)
#endif
in case that was the idea...

Try using:
HttpContext.Current.IsDebuggingEnabled

Cant you just load the file up as a regular XML File and use XPath to get the nodes?

Try using the ConfigurationManager.GetSection method.

Related

How can I change this .NET code to File.Exists?

I am working with a framework written in .NET and I do not know .NET. I just need to change this one line where it checks to see if a variable exists, and I need to change it to instead just check on the server to see if the file itself exists.
Here is what is there now:
#if (!string.IsNullOrEmpty(Model.DrawingLink2){
Is this the correct code to change it to check if the file exists instead?
#if (File.Exists(/Portfolio/#(Model.FileNumber)/Images/Large_#(Model.FileNumber)_1.jpg))
You need to map that file, relative to the root of the web application, to the physical file system. You can use HttpServerUtility.MapPath for that. You also need quotes around string literals. The process running the code also needs read access to the directory (very likely the case, just mentioning it to be complete).
#if (File.Exists(HttpServerUtility.MapPath("/Portfolio/#(Model.FileNumber)/Images/Large_#(Model.FileNumber)_1.jpg"))

Reading ?= arguments to dynamically set debug mode

I was wondering how to read the arguments from a url, ie. localhost:12345?debug=true and be able to set the debug mode. I originally wanted to use the same controller I use by default, however I got an error when I tried to set #define DEBUG because it wasn't at the start of the file, which means I need a separate controller to do this, but how do I check to see if ?debug=true is there, and to check if debug is set to true rather than false?
You are making too much work for yourself. In your web.config, you can set the compilation to be in debug mode (or not)
<compilation debug="true">
If this is set in your web.config, use the framework to tell you if you are in debug mode or not. If the above line (debug="true"), then the HttpContext.Current.IsDebuggingEnabled will return true.
if (HttpContext.Current.IsDebuggingEnabled)
{
DoSomethingDebuggy();
}
else
{
DoSomethingElseCompletely();
}
Now, you no longer need to append a random query string for debug mode (which I am sure will make your routes and links happier). However...if you really really want to keep that query string, then in your controller/action, you can use the following:
public ActionResult Home(){
var debugParam = Request.QueryString["debug"];
//be sure to check for null or empty string before casting to a bool
}
So because in my project, in the .cshtml file, I was using razor to check to see if the debugger was set, I just added an extra argument, || Request.QueryString["string"] == "value" and it solved my problem. A one line fix, where string is the name of the argument you want to look for.

how can get image from a relative path

i am working in asp .net mvc3.
i want to get a image which exist in this location in my project
G:\projects\CalcoWoms\CalcoWOMS\Content\pictures\calcologo.png
CalcoWOMS is my project name. i want to fetch this calcologo.png in following line please check following line and tell me how should write this following line in correct way.?
iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance("~/calcologo.png");
means in place of ("~/calcologo.png"); what path i should write ?
You could use MapPath
var physicalPath = Server.MapPath("~/Content/pictures/calcologo.png");
You could try "%~dp0calcologo.png".
%~dp0 means current directory.
You could use the HostingEnvironment object along with Path.Combine
Path.Combine(#HostingEnvironment.ApplicationPhysicalPath, "calcologo.png");
Of course, #HostingEnvironment.ApplicationPhysicalPath will only take you to the root of your application, so you might need to use "Content/picturescalcologo.png".

web.config, configSource, and "The 'xxx' element is not declared" warning

I have broken down the horribly unwieldy web.config file into individual files for some of the sections (e.g. connectionStrings, authentication, pages etc.) using the configSource attribute.
This is working fine, but the individual xml files that hold the section 'snippets' cause warnings in VS.
For example, a file named roleManager.config is used for the role manager section, and looks like this:
<roleManager enabled="false">
</rolemanager>
However I get a blue squiggle under the roleManager element in VS, and the following warning: The 'roleManager' element is not declared
I guess this is something to do with valid xml and schemas etc. Is there an easy way to fix this? Something I can add to the individual files?
Thanks
P.S. I have heard that it is bad practice to break the web.config file out like this. But don't really understand why - can anyone illuminate me?
Searching a workaround to this matter using Custom Config Files, I found this solution. Dont know if is the correct one.
The problem is that VS cant find a schema to validate your .config (xml). If you are using "native" configuration elements or when you create your custom .config files you must set to every xml document a schema.
By default (in VS9 for example) all xml files use \Microsoft Visual Studio 9.0\Xml\Schemas\DotNetConfig.xsd
but you can add more schemas to use.
Before assigning a schema you must create it.
To create a new Schema based on your own custom.config:
open your custom config file
in menubar XML->Create Schema
save it
To assign your schema:
open your custom config file
in properties panel: click on the browse button [..]
set the 'Use' column to your recently created schema
you can assign as many you want. or have one schema for all your different custom .config files
(Sorry, but my English is not so good)
I think that you get the blue squiggles since the schema of your web.config file doesn't declare these custom config sections that you've 'broken out' into individual files.
In investigating this, I see that some of my solutions have the same issue, but the config sections that are provided from microsoft DON'T have the squiggles. eg: we have extracted the appsettings and connectionstrings out into their own files, and they don't get the squiggles, but our custom ones do.
I tried to view the microsoft schema at schemas.microsoft.com/.netconfiguration/v2.0, but I get a 404 when trying to download it.
What I'm trying to say is if you get a copy of the MS schema and alter it to include your external config files, you should be able to get rid of the dreaded squiggles!
HTH,
Lance

Resource file for a Custom ASP.net control (.ascx) InvalidOperationException

I have a control containing some text which I want to get from a resx file, I thought I could just create a file called ControlName.ascx.resx but that doesn't seem to be working.
I'm using
label1.InnerText = (string)GetLocalResourceObject("default");
To get the value from the resource file but it keeps throwing up an InvalidOperation Exception.
Am I right about how resx files work or does it only work for Pages?
I have the same code working on an aspx page.
When you call GetLocalResourceObject from within a user control, you are actually calling TemplateControl.GetLocalResourceObject, which will look in the wrong place for the resource file. You need to call HttpContext.GetLocalResourceObject instead.
protected string HttpContextGetLocalResourceObjectAsString(string message)
{
string path = HttpContext.Current.Request.Path;
return (HttpContext.GetLocalResourceObject(path, message) as string);
}
Now you can do
label1.InnerText = HttpContextGetLocalResourceObjectAsString("default");
Per the documentation:
Gets a page-level resource
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.getlocalresourceobject.aspx
Edit- added
It may be less work to just add the string to the web.config and grab it from there.
<configuration>
<appSettings>
<add key="LoggingSystemId" value="B2F085A9-6EC1-4CBF-AF8B-B17BFA75AD81"/>
<appSettings>
...
referenced as follows:
logger.SystemId = System.Configuration.ConfigurationManager.AppSettings["LoggingSystemId"];
Of course, you'll need a reference to the System.Configuration dll.
A year or so later, but i think this is what you're after?
var resource = HttpContext.GetLocalResourceObject(TemplateControl.AppRelativeVirtualPath, termType.ToString());
Mark answer if that's the one!

Resources