Asp.net code not performing on actual server as localhost - c#

I have the following code that works fine on my localhost using IIS7 but when i upload it to my server it is behaving not the same as it did on my localhost
For example the submit button when clicked should check validation which it does on my localhost and then redirects to a URL if the validation is correct
But when the same is tried on the actual server over here
The not working link
the problem started when i introduced a redirect url (in C# code is Response.Redirect("http://www.google.com");) in to the c# code...if there is a better way to do this all this hassle wont be necessary..tks
this is the code that i used
<%# Page Language="C#" Debug="true" %>
<%# Import Namespace="System.Xml" %>
<script runat="server">
protected void btnSave_Click(object sender, EventArgs e)
{
txtAddress.Text = "";
string xmlPath = MapPath("Books.xml");
XmlDocument doc = new XmlDocument();
//Check if the file already exists or not
if (System.IO.File.Exists(xmlPath))
{
doc.Load(xmlPath);
XmlNode bookNode = CreateBookNode(doc);
//Get reference to the book node and append the book node to it
XmlNode bookStoreNode = doc.SelectSingleNode("bookstore");
bookStoreNode.AppendChild(bookNode);
lblResult.Text = "XML Document has been successfully updated";
txtAddress.Text = ""; Response.Redirect("http://www.google.com");
}
else
{
XmlNode declarationNode = doc.CreateXmlDeclaration("1.0", "", "");
doc.AppendChild(declarationNode);
XmlNode comment = doc.CreateComment("This file represents a fragment of a book store inventory database");
doc.AppendChild(comment);
XmlNode bookstoreNode = doc.CreateElement("bookstore");
XmlNode bookNode = CreateBookNode(doc);
//Append the book node to the bookstore node
bookstoreNode.AppendChild(bookNode);
//Append the bookstore node to the document
doc.AppendChild(bookstoreNode);
lblResult.Text = "XML Document has been successfully created";
txtAddress.Text = "";Response.Redirect("http://www.google.com");
}
doc.Save(xmlPath);
}
XmlNode CreateBookNode(XmlDocument doc)
{
/*
XmlNode bookNode = doc.CreateElement("book");
//Add the genre attribute to the book node
XmlAttribute genreAttribute = doc.CreateAttribute("genre");
genreAttribute.Value = txtGenre.Text;
bookNode.Attributes.Append(genreAttribute);
http://www.java2s.com/Code/ASP/XML/SaveformdatatoXMLfile.htm
*/
XmlNode bookNode = doc.CreateElement("book");
//Declaration of the Main Node (Particulars)
XmlNode particularsnode = doc.CreateElement("Particulars");
//Declaration of Child Nodes in the Main Node(Particulars)
XmlNode nameNode = doc.CreateElement("Name");
XmlNode phoneNode = doc.CreateElement("Phone");
XmlNode emailNode = doc.CreateElement("Email");
XmlNode AddressNode = doc.CreateElement("Address");
//Getting the textvalue from the htmlform
nameNode.InnerText = txtName.Text;
phoneNode.InnerText = txtPhone.Text;
emailNode.InnerText = txtEmail.Text;
AddressNode.InnerText = txtAddress.Text;
//Updating the XML file here the particularsnode has various children and they are being updated
particularsnode.AppendChild(nameNode);
particularsnode.AppendChild(phoneNode);
particularsnode.AppendChild(emailNode);
particularsnode.AppendChild(AddressNode);
bookNode.AppendChild(particularsnode);
//Declaration of the Main Node (BookParticulars)
XmlNode bookparticularsnode = doc.CreateElement("BookParticulars");
//Declaration of Child Nodes in the Main Node(BookParticulars)
XmlNode schoolNode = doc.CreateElement("School");
XmlNode currentlevelNode = doc.CreateElement("CurrentLevel");
XmlNode GABDNode = doc.CreateElement("GiveAwayBookDetails");
XmlNode LRNode = doc.CreateElement("LevelRequired");
//Getting the textvalue from the htmlform
schoolNode.InnerText = txtSchool.Text;
currentlevelNode.InnerText = txtCurrentLevel.Text;
GABDNode.InnerText = txtGABD.Text;
LRNode.InnerText = txtLR.Text;
//Updating the XML file here the particularsnode has various children and they are being updated
particularsnode.AppendChild(schoolNode);
particularsnode.AppendChild(currentlevelNode);
particularsnode.AppendChild(GABDNode);
particularsnode.AppendChild(LRNode);
bookNode.AppendChild(bookparticularsnode);
return bookNode;
}
public static string NewLineToBreak(string input)
{
Regex regEx = new Regex(#"[\n|\r]+");
return regEx.Replace(input, "<br />");
}
protected void txtAddress_Load(object sender, EventArgs e)
{
txtAddress.Text = "Woodlands Drive 14\n Blk";
}
</script>

Try using Server.MapPath as describes in ASP.NET Web Project Paths or try using Page.ResolveUrl

Have you tried using fully qualified paths for the resources you're trying to load?
e.g.:
string xmlPath = MapPath("~/Books.xml");
-or-
string xmlPath = MapPath("~/<some_sub_dir>/Books.xml");
Also, is your production server throwing exceptions? If so, displaying them locally only and using a local http session to see them might help.
example web.config section for customerrors:
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>

Try giving the fully qualified path and see if its picking the XML file. I am sure it might be some path issue that is causing the exception. Also make sure you turn on the Custom Errors mode so that you can see the error.

Related

How to remove unnecessary xmlns attribute in C#?

I'm trying to update an existing XML file, but always when I update it adding new tags the xmlns="" attribute mysteriously appears in all tags and I didn't find a way to remove it.
private static void EditarXML(string path, List<SiteUrl> listaUrls, bool indice, string loc)
{
XmlDocument documentoXML = new XmlDocument();
documentoXML.Load(path);
XmlNode sitemap = documentoXML.CreateElement("sitemap");
XmlNode xloc = documentoXML.CreateElement("loc");
xloc.InnerText = loc;
sitemap.AppendChild(xloc);
XmlNode lastmod = documentoXML.CreateElement("lastmod");
lastmod.InnerText = DateTime.Now.ToShortDateString();
sitemap.AppendChild(lastmod);
documentoXML.DocumentElement.AppendChild(sitemap);
}
Any help or ideas would be appreciated.
This will happen with the parent node you are appending to has a namespace, but you don't specify it in the CreateElement() call.
To handle this, you can get the namespace from the DocumentElement, like this (my sample just creates the document in memory, but the principle is the same), and pass it to CreateElement().
if (x.DocumentElement != null) {
var xmlns = (x.DocumentElement.NamespaceURI);
var sitemap = x.CreateElement("sitemap", xmlns);
var xloc = x.CreateElement("loc", xmlns);
xloc.InnerText = "Hello";
sitemap.AppendChild(xloc);
var lastmod = x.CreateElement("lastmod", xmlns);
lastmod.InnerText = DateTime.Now.ToShortDateString();
sitemap.AppendChild(lastmod);
x.DocumentElement.AppendChild(sitemap);
}
Console.WriteLine(x.InnerXml);
Output
<test xmlns="jdphenix"><sitemap><loc>Hello</loc><lastmod>4/20/2015</lastmod></sitemap></test>
Note that if I did not pass the parent namespace to each CreateElement() call, the children of that call would have the blank xmlns.
// incorrect - appends xmlns=""
if (x.DocumentElement != null) {
var sitemap = x.CreateElement("sitemap");
var xloc = x.CreateElement("loc");
xloc.InnerText = "Hello";
sitemap.AppendChild(xloc);
var lastmod = x.CreateElement("lastmod");
lastmod.InnerText = DateTime.Now.ToShortDateString();
sitemap.AppendChild(lastmod);
x.DocumentElement.AppendChild(sitemap);
}
Console.WriteLine(x.InnerXml);
Output
<test xmlns="jdphenix"><sitemap xmlns=""><loc>Hello</loc><lastmod>4/20/2015</lastmod></sitemap></test>
Related reading: Why does .NET XML append an xlmns attribute to XmlElements I add to a document? Can I stop it?
How to prevent blank xmlns attributes in output from .NET's XmlDocument?

fetch google map data from external website

Is this possible to read or parse google map data(i-e http://www.ukairquality.net/MicrosoftMapFast2.aspx ) from external website
I just want to get data from this and store this data in my sql...
private void button1_Click(object sender, EventArgs e)
{
XmlDocument XmlDoc = new XmlDocument();
XmlNamespaceManager XmlNs = new XmlNamespaceManager(XmlDoc.NameTable);
XmlNs.AddNamespace("def", "http://earth.google.com/kml/2.0");
string url = "http://www.ukairquality.net/MicrosoftMapFast2.aspx ";
XmlDoc.Load(url);
//XmlDoc.Save(MapPath(#"~\xml\test.xml"));
XmlNodeList Nodes = XmlDoc.SelectNodes("//def:coordinates", XmlNs);
foreach (XmlNode Node in Nodes)
{
textBox1.Text= Response.Write(Node.InnerText + "<br />");
}
}
Sure you can load data from other webstes, but the URL you give is not XML. You'll get an error if you try to parse it as XML.
If you want to get the data from this UK site, then you'll need to look at their javascript and use string functions to get the parts you want.

Textbox string to xml issue

I'm having a little problem formatting my xml file using C# code in a Windows Form app. Here is the code i'm using for this project:
private void btnSend_Click(object sender, EventArgs e)
{
string _name = tbName.ToString();
string _st = tbSt.ToString();
string _dx = tbDx.ToString();
string _iq = tbIq.ToString();
string _filename = #"c:\Add.xml";
if (File.Exists(_filename))
{
XDocument xDoc = XDocument.Load(_filename);
xDoc.Root.Add(new XElement("character",
new XElement("name", _name),
new XElement("st", _st),
new XElement("dx", _dx),
new XElement("iq", _iq)
));
xDoc.Save(_filename);
}
else if (!File.Exists(_filename))
{
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode productsNode = doc.CreateElement("characters");
doc.AppendChild(productsNode);
XmlNode productNode = doc.CreateElement("character");
productsNode.AppendChild(productNode);
XmlNode nmNode = doc.CreateElement("name");
nmNode.AppendChild(doc.CreateTextNode(_name));
productNode.AppendChild(nmNode);
XmlNode stNode = doc.CreateElement("st");
stNode.AppendChild(doc.CreateTextNode(_st));
productNode.AppendChild(stNode);
XmlNode dxNode = doc.CreateElement("dx");
dxNode.AppendChild(doc.CreateTextNode(_dx));
productNode.AppendChild(dxNode);
XmlNode iqNode = doc.CreateElement("iq");
iqNode.AppendChild(doc.CreateTextNode(_iq));
productNode.AppendChild(iqNode);
doc.Save(#"c:\Add.xml");//must have to save
}
}
The problem is that my .xml file comes out with the whole TextBox class prefix attached such as this:
...
- <character>
<name>System.Windows.Forms.TextBox, Text: bob</name>
<st>System.Windows.Forms.TextBox, Text: 10</st>
<dx>System.Windows.Forms.TextBox, Text: 12</dx>
<iq>System.Windows.Forms.TextBox, Text: 08</iq>
</character>
I'd like to have it look like this:
- <character>
<name>bob</name>
<st>10</st>
<dx>12</dx>
<iq>08</iq>
</character>
If any of you fine knowledgeable folks could lend a hand (or point me a link) I'd appreciate it. I did comb through the Google but nothing turned up with this specific odd problem. Many thanks for any help you can offer.
The obvious I did not see. Thanks to those who may respond. Now that I post it, it is obvious.
Changing
string _name = tbName.ToString();
simply to
string _name = tbName.Text;
of course fixed the problem. Hope this may help someone else.

Append XML using WCF

WCFService.cs
[AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WCFService : IWCFService{
public Boolean insertUser(String name, String password)
{
Boolean successInsert = false;
XDocument xDoc = XDocument.Load("`http://localhost:57833/DataProvider/XML/User.xml`");
Boolean userExist = (from user in xDoc.Descendants("user")
where (String)user.Attribute("name") == name
select user).Any();
if (!userExist)
{
XElement root = xDoc.Root;
int lastUserId = Convert.ToInt16(root.Elements("user").Last().Attribute("id").Value);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("`http://localhost:57833/DataProvider/XML/User.xml`");
XmlNode xmlElementUser = xmlDoc.CreateNode(XmlNodeType.Element, "user", "");
XmlAttribute xmlAttributeUserID = xmlDoc.CreateAttribute("id");
XmlAttribute xmlAttributeName = xmlDoc.CreateAttribute("name");
XmlAttribute xmlAttributePassword = xmlDoc.CreateAttribute("password");
XmlAttribute xmlAttributeUserType = xmlDoc.CreateAttribute("userType");
xmlAttributeUserID.Value = (lastUserId + 1).ToString();
xmlAttributeName.Value = name;
xmlAttributePassword.Value = password;
xmlAttributeUserType.Value = "borrower";
xmlElementUser.Attributes.Append(xmlAttributeUserID);
xmlElementUser.Attributes.Append(xmlAttributeName);
xmlElementUser.Attributes.Append(xmlAttributePassword);
xmlElementUser.Attributes.Append(xmlAttributeUserType);
xmlDoc.DocumentElement.AppendChild(xmlElementUser);
xmlDoc.Save("`http://localhost:57833/DataProvider/XML/User.xml`");
successInsert = true;
}
return successInsert;
}
}
I'm doing a windows phone 7 app, and i wish to retrieve from and append to XML file by using WCF. And i encounter an error of "URI formats are not supported." when i wish to save the XML which is this line "xmlDoc.Save("http://localhost:57833/DataProvider/XML/User.xml");". It seem like WCF cannot append the XML file in server.
You cannot append to a file on a remote server but only on the local disk.
So if the code above is executed on the machine where you want to save the xml use:
xmlDoc.Save("c:\\User.xml")
If you are not on that server (and it is not accessible via unc) then you need to upload the file to another wcf service on that machine so it will save it locally.

saving webbrowser url to xml and retriving

I am trying to save my webbrowser controler URL to a xml file but I am getting an issue with certain characters preventing the save.
When I open a simple URL like this:
www.saypeople.com
It succesfully saves, however when I want to save webpage url like this:
http://scholar.google.com.pk/scholar?as_q=filetype:pdf +transistor+ AND&num=10&btnG=Search+Scholar&as_epq=&as_oq=unknown+unclear&as_eq=&as_occt=any&as_sauthors=+ &as_publication=+ &as_ylo=&as_yhi=&as_sdt=1.&as_sdtp=on&as_sdtf=&as_sdts=5&hl=en
The save fails.
I have checked a lot things and have discovered that my code only does not save when the url contains any of the two characters &<.
Please help me out.
Here is my code...
public static DialogResult Show(string Title, String url)
{
MsgBox = new addfav();
MsgBox.textBox1.Text = Title;
MsgBox.textBox2.Text = url;
MsgBox.ShowDialog();
return result;
}
const string dataxml = "data.xml";
private void button1_Click(object sender, EventArgs e)
{
//textBox2.Text containing webpage url
//textBox1.Text containing webpage title
try
{
XmlTextReader reader = new XmlTextReader(dataxml);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
XmlNode currNode;
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml = "<fav>" + "<Title>" + textBox1.Text + "</Title>" + "<url>"+ textBox2.Text + "</url>" + "</fav>";
// insert the availability node into the document
currNode = doc.DocumentElement;
currNode.InsertAfter(docFrag, currNode.LastChild);
//save the output to a file
doc.Save(dataxml);
this.DialogResult = DialogResult.OK;
MessageBox.Show("Sucessfully Added");
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.ToString());
this.DialogResult = DialogResult.Cancel;
}
MsgBox.Close();
}
and
how can i retrive url by searching specific title in xml.
<fav>
<Title>hello</Title>
<url><![CDATA[http://scholar.google.com.pk/scholar?as_q=filetype:pdf +hello+ AND&num=10&btnG=Search+Scholar&as_epq=&as_oq=unknown+unclear&as_eq=&as_occt=any&as_sauthors=+ &as_publication=+ &as_ylo=&as_yhi=&as_sdt=1.&as_sdtp=on&as_sdtf=&as_sdts=5&hl=en]]></url>
</fav>
<fav>
<Title>toad</Title>
<url><![CDATA[http://www.sciencedaily.com/search/?keyword=toad+ AND unknown OR unclear]]></url>
</fav>
i want to search and save the url of toad title in string... please help me out...
thx
Wrap the URL in a CDATA section like:
<![CDATA[THE URL CONTENT]]>
Your problems result from the fact that you can not used & and < as XML-data, as they have special meanings in XML: & starts an XML entity, < starts an XML tag. So when you need to add & and < as values, it's easiest to used a CDATA section.
EDIT
You may try the following:
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml = "<fav>";
docFrag.InnerXml += String.Format("<Title>{0}</Title>", textBox1.Text);
docFrag.InnerXml += String.Format("<Url><![CDATA[{0}]]></Url>", textBox2.Text);
docFrag.InnerXml += "</fav>";
You could use HttpUtility.HtmlEncode(url).
Your problem is here:
docFrag.InnerXml = "<fav>" + "<Title>" + textBox1.Text + "</Title>"
+ "<url>"+ textBox2.Text + "</url>" + "</fav>";
<, > and & that caused you problems are markup in XML. InnerXML does not escape markup and those characters get written as they are which would result in an invalid XML fragment. For adding the URL, use InnerText instead. It escapes those characters.
To navigate through an XML file, you have to use a navigator as shown here.
XPathDocument xpathDoc = new XPathDocument([location of the file]);
XPathNavigator Navigator = xpathDoc.CreateNavigator();
String url_nav = "fav/url/text()";
XPathNodeIterator url_iterator = Navigator.Select(url_nav);
String URL_value = url_iterator.Current.Value;
url_iterator.MoveNext();
If the file is too heavily nested, go for XML serialization.

Categories