C# check if handler is present in Web.Config - c#

In my Web.Config file I have the following:
<system.webServer>
<handlers>
<add name="HANDLERNAME" verb="*" path="PATH.axd" type="HANDLERTYPE">
</handlers>
</system.webServer>
Before I run a particular bit of code, I want to check to see if the handler is present in my Web.Config file.
Is this something I'm able to do?
I've tried: ConfigurationManager.GetSection("system.webServer/handlers") with no success, as this returns null.
Any help would be greatly appreciated!

I found two way to check for the handlers in the web.config
XmlDocument doc = new XmlDocument();
doc.Load(path); *//path is the location of the web.config file*
XmlElement root = doc.DocumentElement;
XmlNode nodes = root.SelectSingleNode("/system.webServer");
XmlNodeList childnotes = nodes.ChildNodes;
bool isExist = false;;
foreach (XmlNode node in childnotes)
{
if (node.Name.Contains("handlers"))
{
isExist = node.OuterXml.Contains("HANDLERNAME");
}
}
you can check the value of isExist
The other way is to get entire web.config as a string and check if it contains HANDLERNAME

Related

How to save a New Xml file using app.config?

I have to save a file with the help of app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appsetting>
<add key ="filename" value ="abc.xml"></add>
<add key="filepath" value ="C:\\Users\\saket.parasar.jha"></add>
</appsetting>
</configuration>
My code for saving the xml file to the prescribed path-:
XmlDocument doc = new XmlDocument();
//XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
//doc.AppendChild(docNode);
XmlNode productsNode = doc.CreateElement("products");
doc.AppendChild(productsNode);
{
XmlNode productNode = doc.CreateElement("product");
XmlAttribute productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "1";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
XmlNode nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("Java"));
productNode.AppendChild(nameNode);
XmlNode priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
AddUpdateAppSettings("filename", "abc.xml");
}
}
static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
I have to write that xml file to C:\Users\saket.parasar.jha" using c#...pls help me out, I am new to this topic.I tried a lot but was nt able to save that file.
First of all, you can never modify app.config file programmatically. The settings inside are never to be changed while your app is running. These settings are like "pre-launch". If you need any settings modificable by a user, use Settings File (Add > New Item > General > Settings File), the one with the extension *.settings. Also, I don't see you trying to get your settings from your configuration file, you're only saving them there (but you can't do that, the reason is above).
After you get your path properly, you can save your file there.
P.S.: App.config is not allowed to be modified, because it sits in the same directory as the app (with modified name like MyApplication.exe.config); when you app is installed on a destination system, the destination directory will most likely be "Program Files". As you understand, any attempt to modify the config will require elevated privileges (like an administrator's). That means your app is VERY user unfriendly.
Why don't you save your XmlDocument? something like
doc.Save("C:\\Users\\saket.parasar.jha\\abc.xml");

Read a connection string from a XML file

I've read about all I could get on how to read from an XML file, but I can't get anything done. I want to read a connectionstring from an XML file, plain and simple, nothing more.
My XML looks like
<?xml version="1.0" standalone="yes"?>
<connectionString>
<conn>"adsf"</conn>
</connectionString>
And I've tried varios way with
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(xmlLoc);
while (reader.MoveToNextAttribute())
{
XmlNode a = doc.ReadNode(reader);
textBox1.Text = Text + a.Name;
}
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlLoc); //myXmlString is the xml file in string //copying xml to string: string myXmlString = xmldoc.OuterXml.ToString();
XmlNodeList xnList = xml.SelectNodes("/connectionString");
foreach (XmlNode xn in xnList)
{
XmlNode example = xn.SelectSingleNode("conn");
if (example != null)
{
string na = example["Name"].InnerText;
string no = example["NO"].InnerText;
}
}
I'm missing something and I'm not sure what, this should be a very simple task, but I can't get it done. Any help?
I'm trying to do it in a WIndows form application program.
I'm missing something?
Yes. .NET has a built in mechanism for storing your connection string, inside an App.config file, there is no reason to manually store it and parse it yourself.
Right click your project, go to Add -> New Item
Then, add a "Application Configuration File":
Once it opens, add a connectionStrings node to it, as follows:
// This is an example of a connectionString node. You may add child
// values to it as follows
<connectionStrings>
<add name="YourConnectionStringKey"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=YourDB;Trusted_Connection=Yes" />
</connectionStrings>
Then, you access it using ConfigurationManager.ConnectionStrings:
string connectionString =
ConfigurationManager.ConnectionStrings["YourConnectionStringKey"].ConnectionString;
You can use linq to xml.
var xmlStr = File.ReadAllText("fileName.xml");
var str = XElement.Parse(xmlStr);
var result = str.Elements("word").
Where(x => x.Element("connectionString").Value.Equals("conn"));
Console.WriteLine(result);
This might work (or may be some changes you need to make.
var x = XElement.Parse(#"<?xml version=""1.0"" standalone=""yes""?><connectionString><conn>adsf</conn></connectionString>");
// or var x = XElement.Load(#"c:\temp\my.xml");
var s = x.Element("conn").Value;
If you still have not found your answer then try this (a bit old school but it worked for me)
public class Common
{
public Common()
{
}
// public static string GetXML()
// {
// return #"C:\MyLocation\Connections.xml";
// }
public static string GetXMLconn(string strConn)
{
string xmlConStr = "";
//
string XMLconn = #"C:\Mylocation\Connections.xml";
// Get the Connection String from the XML file.
XmlTextReader textReader = new XmlTextReader(XMLconn);
textReader.Read();
while (textReader.Read())
{
// Read the currect element in the loop
textReader.MoveToElement();
// If the element name is correct then read and assign the connection string
if (textReader.Name == strConn)
{
xmlConStr = textReader.ReadString();
}
}
textReader.Close();
return xmlConStr;
}
}

how to read external app.config as xml file in winforms?

How to read app.config file as normal xml and read the connectionString Key/value
from configuration ->connectionStrings node
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="appConnStr" connectionString="Data Source=DEV6-PC;Initial Catalog=ireg.est;Persist Security Info=True;User ID=sa;Password=sa#123" providerName=".NET Framework Data Provider for SQL Server"/>
</connectionStrings>
<configuration>
var element = XDocument.Load("filepath")
.Descendants("connectionStrings")
.FirstOrDefault();
var connStrings = new Dictionary<string,string>();
if(element != null)
{
foreach(var item in element.Elements("add"))
{
var name = (string)item.Attribute("name");
var connString = (string)item.Attribute("connectionString");
connStrings.Add(name,connString);
}
}
try this: here im reading the file as an xml document and retrieving the connection string attribute.
string connString=null;
XmlDocument xmldoc = new XmlDocument();
xmldoc.load("yourconfigfielpath"); // add your file path here.
XmlNodeList nodeList = xmlDoc.SelectNodes("/xml/configuration/connectionstrings");
foreach (XmlNode node in nodeList)
{
connString=node["add"].GetAttribute("connectionString");
}
hope this helps.

Select xml file part with xpath and xdocument - C#/Win8

I am building a Windows 8 app, and I need to extract the whole XML node and its children as string from a large xml document, and the method that does that so far looks like this:
public string GetNodeContent(string path)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.ConformanceLevel = ConformanceLevel.Auto;
settings.IgnoreComments = true;
using (XmlReader reader = XmlReader.Create("something.xml", settings))
{
reader.MoveToContent();
reader.Read();
XmlDocument doc = new XmlDocument();
doc.LoadXml(reader.ReadOuterXml());
IXmlNode node = doc.SelectSingleNode(path);
return node.InnerText;
}
}
When I pass any form of xpath, node gets the value of null. I'm using the reader to get the first child of root node, and then use XMLDocument to create one from that xml. Since it's Windows 8, apparently, I can't use XPathSelectElements method and this is the only way I can't think of. Is there a way to do it using this, or any other logic?
Thank you in advance for your answers.
[UPDATE]
Let's say XML has this general form:
<nodeone attributes...>
<nodetwo attributes...>
<nodethree attributes... />
<nodethree attributes... />
<nodethree attributes... />
</nodetwo>
</nodeone >
I expect to get as a result nodetwo and all of its children in the form of xml string when i pass "/nodeone/nodetwo" or "//nodetwo"
I've come up with this solution, the whole approach was wrong to start with. The problematic part was the fact that this code
reader.MoveToContent();
reader.Read();
ignores the namespace by itself, because it skips the root tag. This is the new, working code:
public static async Task<string> ReadFileTest(string xpath)
{
StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("NameOfFolderWithXML");
StorageFile xmlFile = await folder.GetFileAsync("filename.xml");
XmlDocument xmldoc = await XmlDocument.LoadFromFileAsync(xmlFile);
var nodes = doc.SelectNodes(xpath);
XmlElement element = (XmlElement)nodes[0];
return element.GetXml();
}

How to check if the System.webServer/Security/requestFiltering section exists programmatically?

I want to be able to determine programmatically if the System.webServer/Security/requestFiltering section exists inside the the web.config file of my application.
I am able to do it for other sections like system.web using the code below, but so far no luck with system.WebServer.
var config = WebConfigurationManager.OpenWebConfiguration("~");
HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
Label1.Text = section.MaxRequestLength.ToString();
Why don't you read the web.config just like any XML file and find the nodes that way? You could do something like this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("~/Web.config"));
XmlNode n = xmlDoc.SelectSingleNode("/configuration/System.webServer/Security/requestFiltering");
if (n != null)
{
// Do whatever you want...
}

Categories

Resources