resolving file path within a function - asp.net

I have a function which works in the development environment but I need to change the path so it resolves properly at the host servers.
This code line;
doc.Load("H:\Website_Sep2012\OtherDataFiles\dataXML.xml") 'this needs to be changed to the server path
within this function
Public Shared Function GetList(ByVal nodestring As String) As List(Of String)
Dim doc As New XmlDocument()
'Load XML from the file into XmlDocument object
doc.Load("H:\Website_Sep2012\OtherDataFiles\dataXML.xml") 'this needs to be changed to the server path
Dim root As XmlNode = doc.DocumentElement
'Select all nodes with the tag paramter indicated by the nodestring variable
Dim nodeList As XmlNodeList = root.SelectNodes(nodestring)
Return (From node As XmlNode In nodeList Select node.InnerText).ToList()
End Function
Replacing the string with Server.MapPath("~/OtherDataFiles\dataXML.xml") does not work as Server is not available in that scope. Any ideas how to resolve this path

You could also try:
System.Web.Hosting.HostingEnvironment.MapPath() No need for HttpContext
OR
using System.Web;
HttpContext.Current.Server.MapPath("~/OtherDataFiles/dataXML.xml");

The Server can always be reached like this:
string filePath = System.Web.HttpContext.Current.Server.MapPath("~/OtherDataFiles/dataXML.xml");
doc.Load(filePath);
If inside a class library project you can just add reference to System.Web assembly.

Related

Using Selenium to scrape from Azure web app

I have successfully used Selenium from the localhost on my PC and retrieved data from the target URL but I need to be able to do this from a web app hosted in Azure. The problem I encounter is the message that ChromeDriver.exe cannot be located. If I look at the results of my build, there is a copy located in the bin folder but I don't know if this is published to the server and how I would tell the server where it was.
If the app could find the ChromeDriver, I anticipate the next error would be 'cannot locate binary'. I have commented out the binary location because I don't know how I would make Chrome available on Azure.
I can't find any examples of anyone else employing the same environment. I include a code extract.
Imports System.Net
Imports OpenQA.Selenium
Imports OpenQA.Selenium.Chrome
Imports OpenQA.Selenium.Support.UI
Public Class Scraper
Inherits System.Web.UI.Page
Public Function ScrapeToChrome(ByVal url As String) As String
Dim LinkList As List(Of String) = New List(Of String)()
Dim options = New ChromeOptions() 'With {
' .BinaryLocation = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
' }
options.AddArguments(New List(Of String)() From {
"headless",
"disable-gpu"
})
Dim browser = New ChromeDriver(options)
Dim wait As WebDriverWait = New WebDriverWait(browser, TimeSpan.FromSeconds(10))
browser.Navigate().GoToUrl(url)
browser.FindElement(By.Id("txtSurname")).SendKeys("Mahony")
browser.FindElement(By.Id("txtPhoenixID")).SendKeys("5258242")
browser.FindElement(By.XPath("//*[#id='divSearchBox']/div/div/div[1]/form")).Submit() 'Id("btnSearch"))
Dim elementToBeDisplayed As IWebElement
wait.Until(Function(condition)
Try
elementToBeDisplayed = browser.FindElement(By.Id("divSearchResults"))
Return elementToBeDisplayed.Displayed
Catch __unusedStaleElementReferenceException1__ As StaleElementReferenceException
Return False
Catch __unusedNoSuchElementException2__ As NoSuchElementException
Return False
End Try
End Function)
Return elementToBeDisplayed.Text
End Function
End Class

adding new child nodes to XML on each function call

I have an XML file and I have a function to which this XML is passed as string. I have loaded this string in Xmldocument and I need to insert few children nodes under one node. This function returns the modified XML string. I want that whenever this function is called, new child nodes are added, currently, It adds child nodes once.
Do I need to overwrite the XML file ? If so, How can I replace the node with new node ( with new child nodes added) so that It has child nodes added before the function is called again ?
My code looks something like this:
Dim doc As New XmlDocument
doc.LoadXml(applicationXml)
Dim parentNode As XmlNode = doc.GetElementsByTagName("prList").Item(0)
Dim newElement As XmlNode = doc.CreateNode(XmlNodeType.Element, "gate.util.persistence.LanguageAnalyserPersistence", Nothing)
Dim runtimeParamsElement As XmlNode = doc.CreateNode(XmlNodeType.Element, "runtimeParams", Nothing)
Dim xa As XmlAttribute = doc.CreateAttribute("class")
xa.Value = "gate.util.persistence.MapPersistence"
runtimeParamsElement.Attributes.Append(xa)
localMapElement = doc.CreateNode(XmlNodeType.Element, "localMap", Nothing)
featuresElement.AppendChild(localMapElement)
newElement.AppendChild(featuresElement)
Return doc.InnerXml
You are not showing enough code to determine the exact problem. Which node are you trying to replace? Where did featuresElement come from? Here are a few answers:
Yes you need to replace the whole file using the new document.
You don't need to replace the node with a new node. Just pass the target node to your function. The function should call appendChild() on the parent node to add a child.
When you write the document to file, example, it will have the new nodes.

How to call a node from a xml file within asp.net web page

I am trying to use the value of <Directory> in my following piece of code:
Public Function GetFile() As String
Dim di As New DirectoryInfo(< Directory >)
Dim files As FileSystemInfo() = di.GetFileSystemInfos()
Dim newestFile = files.OrderByDescending(Function(f) f.CreationTime).First
Return newestFile.FullName
End Function
Is there any way i can call the value stored in the xml file in my code?
Andy's answer is good, but in VB it's even easier.
Dim xmlDoc As XDocument
Dim dir as String
xmlDoc = XDocument.Load("XMLFile1.xml")
dir = xmlDoc.<ServerList>.<Server>.<Directory>.First().Value;
Or even easier if the XML file will never have more than one <Directory> element that you care about:
dir = xmlDoc...<Directory>.First().Value;
To answer your comment on Andy's answer:
dir = (From server as XElement in xmlDoc...<Server>
Where server.<ServerName>.First().Value = requiredServer
Select server.<Directory>.First().Value)(0);
As you are clearly familiar with Linq, you can operate on the Xml using System.Xml.Linq.
Apologies, this is in c#.
var xDoc = XDocument.Load("XMLFile1.xml");
var dir = xDoc.Element("ServerList").Elements("Server").Elements("Directory").First().Value;
If you have the Xml stored in a string replace XDocument.Load with XDocument.Parse.
Obviously you'll have to defend against parse errors, file missing and schema inconsistencies in your production code.
You can use this http://support.microsoft.com/kb/301225

Save Xml document in Web-Method in serverpath

How to save XML document in web method in server path in asp.net?
XmlDataDocument doc = new XmlDataDocument(ds);
XmlElement element = doc.DocumentElement;
return ds.GetXml();
string _XMLFileName = HttpContext.Current.Server.MapPath(#"Data\error1.xml");
ds.WriteXml(_XMLFileName);
This should work:
doc.Save(_XMLFileName)
Looking at your comments, can you try using HostingEnvironment.MapPath. Read more on MSDN.
In your case it would be
string _XMLFileName = HostingEnvironment.MapPath("~/App_Data/Data/error1.xml");
HostingEnvironment maps path relative to your hosting location, so you will need to provide ~ for root location. In the example, the file will be inside your root directory of application, under App_Data/Data folder.
Hope this works for you.
This is how I am doing it at the moment..
Dim path As String
path = Server.MapPath("nameOfXMLDoc.xml")
Dim doc As System.Xml.XmlDocument = New System.Xml.XmlDocument()
doc.Load(path)
And it works for me.. found the answer here: http://www.codeproject.com/Articles/165438/Getting-XML-Data-from-Webservice-to-Infopath

System.InvalidOperationException: This document already has a 'DocumentElement' node

I have a trouble on appending new node to xmldocument (created in the memory). I have select the root node with the XmlDocument.SelectSingleNode() method, it work sometimes and in the other time it will give me "System.InvalidOperationException: This document already has a 'DocumentElement' node." error. More information, this xml document is multi level xml document.
By the way, when i try it with unit test it work fine (always), when i implement it in ASP.NET 3.5, it become weird, work sometimes and fail sometimes. Any idea, why this can help? All advise and suggestion are welcome.
Thanks.
You can select the root node of the XmlDocument using the Property "DocumentElement". Or i think you can use the Property "FirstChild" (untested).
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
XmlElement rootNode = doc.DocumentElement;
This worked for me.
xmlOriginFile = New XmlDocument()
xmlTargetFile = New XmlDocument()
xmlOriginFile.Load(readFile) //readFile is a string that hold path to xml document
xmlTargetFile.Load(writeFile) //writeFile is a string that hold path to xml document
Dim fileNav As XPathNavigator = xmlOriginFile.CreateNavigator()
Dim fileItr As XPathNodeIterator = fileNav.Select("//data")
Dim addToDestNodes As List(Of XmlNode) = New List(Of XmlNode)
While (fileItr.MoveNext())
Dim addNode As XmlNode = CType(fileItr.Current, IHasXmlNode).GetNode()
addToDestNodes.Add(addNode)
End While //loop thru nodes
If addToDestNodes.Count > 0 Then
For Each addedNode As XmlNode In addToDestNodes
Dim addTargetNode As XmlNode = xmlTargetFile.ImportNode(addedNode, True)
xmlTargetFile.DocumentElement.AppendChild(addTargetNode)
Next
End If
xmlTargetFile.Save(xmlTarget) //xmlTarget is a string that hold path to xml document
XML has a root element and you have to add new element within this root element.
XmlElement eleParent = docDestn.CreateElement("EleParent");
XmlElement eleChild = docDestn.CreateElement("Item");
eleParent.AppendChild(eleChild);
XMLNode rootNode= xmlDoc.SelectSingleNode("RootEle");
rootNode.AppendChild(eleParent);
Plps. refer the link for detail: http://navinpandit.blogspot.in/2016/12/exception-this-document-already-has.html

Resources