Load Xdocument with RSS feed in MVVM app - c#

I am learning MVVM & Linq to xml by converting a simple wpf RSS app. Originally, I used XmlDataProvider to load local xml files or RSS urls. I am now using the code below which works fine loading local xml files, but throws the "FileNotFoundException" when its a url. During debugging I see the correct url address in (string RSS_URL), yet the file is not found. My initial searching led me to Webclient & HttpWebRequest, but I haven't had any success with them. Am I on the right track? Any code or tutorial links available?
public static List<RSSItem> Load(string RSS_URL)
{
if (!File.Exists(RSS_URL))
{
throw new FileNotFoundException("Datasource file could not be found", RSS_URL);
}
var rssfiles = XDocument.Load(RSS_URL).Descendants("item").Select(
x => new RSSItem(
(string)x.Element("title"),
(string)x.Element("link"),
(string)x.Element("description")));
return rssfiles.ToList();
}
Thank You

XDocument.Load() will accept URLs without any problem. The issue in your code is that you're using File.Exists() to determine whether or not he URL is valid. File.Exists() only accepts a filesystem path, not a uri.
Quick piece of additional info: the Load() method relies on an underlying XmlReader and a call to Create(). If the resource (the URL in this case) doesn't exist, a WebException will be thrown indicating that the resource doesn't exist.
XDocument.Load info:
http://msdn.microsoft.com/en-us/library/bb343181.aspx
XmlReader.Create info:
http://msdn.microsoft.com/en-us/library/w8k674bf.aspx

The XDocument.Load overload you are using is specifically for loading from a file. You would have to download from the RSS feed to get the XML data locally. Look at the MSDN document here for alternatives such as reading from a stream, which might be better suited to what you need.

Related

How to read file in C# from POST data from web

Basically, I'm building a website that allows user to upload file.
From the front end (JavaScript), the user will browse a file, I can get the site to send POST data (the parameter "UploadInput" and it's value, which the value is the file)
In the backend (C#), I want to make a copy of the file and save it in a specific path.
Below is the way I did it.
var files = Request.Files;
file[0].SaveAs("\temp\\" + file[0].FileName);
The problem I ran into is that I got the error message saying index out of range. I tried Response.Write(files.Count) and it gives me 0 instead of 1.
I'm wondering where I did wrong and how to fix it, or if there's a better way of doing it.
Thanks!
Edit:
I am using HttpFox to debug. From HttpFox, I can see that under POST data, parameter is "UploadInput" and the value is "test.txt"
Edit 2:
So I tried the way Marc provides, and I have a different problem.
I am able to create a new file, however, the content is not copied over. I tried opening the new created file in notepad and all it says is "UploadInput = test.txt"
If they simply posted the file as the body content, then there will be zero "files" involved here, so file[0] will fail. Instead, you need to look at the input-stream, and simply read from that stream. For example:
using(var file = File.Create(somePath)) {
Request.InputStream.CopyTo(file);
}

How to create a component by providing the XML source file as input

I want to create a component by giving XML source input directly using core service 2011, in SDL Tridion 2011.
I want to write code to create a component by uploading source XML. Using the core service 2011.
Say name of the xml file is helloworld.xml and location is D:\abcd\cdef\all\helloworld.xml.
I have written the code like this, but its not working.
XmlDocument contentxml = new XmlDocument();
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
Response.Write("<BR>" + contentxml.ToString());
component.Content = contentxml.ToString();
ComponentData comp = (ComponentData)client.Create(component, new ReadOptions());
The Response.write is displaying nothing. Correct me if I missed any thing.
It's not creating any component and error is coming.
When i tried this:
XmlDocument contentxml = new XmlDocument();
try
{
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
}
catch (XmlException exp)
{
Console.WriteLine(exp.Message);
}
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
contentxml.WriteTo(xw);
Response.Write("<BR>" + sw.ToString());
component.Content = sw.ToString();
ComponentData comp = (ComponentData)client.Create(component, new ReadOptions());
This time it's showing unable to find UUId: some thing like that.
My helloworld.xml looks like this.
<Content xmlns="uuid:1111eb85-0X11-11f9-1e2X-1X82X78fX920">
<first>Hello World.This is Fisrt field</first>
<second>Hello World.This is second field</second>
</Content>
It would be great if some one share some sample code to do it.
Loading any XML from a a file and trying to create a component won't work unless the XML uses the format the CMS is expecting.
The XML structure of a component in SDL Tridion has some fixed parts (Example Nodes Content, Metadata) plus some flexible parts
(The way you define the fields).
First you need to have the XML with the same structure that the CMS is expecting.
Typically the nodes that should be in your xml are the CONTENT and METADATA, load those in an XML Document and use the Core Service API to
create a component using the content contained in those nodes.
The best way to know how which is the structure of a component based on an schema is to create a sample component using the Tridion UI and
see how the XML is constructed. After that you need to create your XML Sources using that structure.
I posted recently an example of how to create a component using the Core Service, please have a look at that.
Faulted State error while creating component with Core Service
Following this code, you can access the nodes Content and Metadata
componentData.Content = xmlUtil.GetNewXmlNode("Content", schemaData.NamespaceUri);
componentData.Metadata = xmlUtil.GetNewXmlNode("Metadata", schemaData.NamespaceUri);
And replace those with your content
The general outline:
Load the XML from the file into an XDocument / XmlDocument.
Create a new Component by calling GetDefaultData on the client.
Set the Content property of the Component to the XML.
Save the Component by calling Save on the client.
If you haven't already, please have a look at the Core Service API documentation available on SDL Tridion World.
If you have trouble implementing this, please post the code that you have and what you have tried in order to make it work.
Using XmlDocument.LoadXML() expects an XML string as input, as commented by Peter you should use XMLDocument.Load() instead, see here for more details http://msdn.microsoft.com/en-us/library/a8ta6tz4.aspx
When you have passed that hurdle you will need the information Miguel gave in his answer to continue.

loading xml document error in c#

I'm trying to load a document with xml in c#
the name of xml file is variable, here is problem...
string filename="test01.xml";
XmlDocument root = new XmlDocument();
root.Load(filename);
the above code give me error: unable to connect to remote server or unable to load
but the following code works
XmlDocument root = new XmlDocument();
root.Load("test01.xml");
why is that?
You can try to specify the whole path (absolute path) to the file (not only the filename).
So instead of writing "test01.xml" you can try to write "C:\[... path to the file here]\test01.xml" and it should work as intended.
If you specify only the file name, the application will probably look for the file in the current directory (value in Environment.CurrentDirectory). I just tested this in a sample application.
It's worth mentioning that if you use FileName property from OpenFileDialog class as a case with 'using variable', it contains PATH to the file (despite its name ;)).
Does your XML contains DTD declaration with URL? Most probably parser tries to resolve it, and fails, because, say, automatic proxy does not accept its request.

User Permissions issue

I am using Visual Studio C# to parse an XML document for a file location from a local search tool I am using. Specifically I am using c# to query if the user has access to certain files and hide those to which it does not have access. I seem to have files that should return access is true however because not all files are local (IE some are web files without proper names) it is not showing access to files it should be showing access to. The error right now is caused by a url using .aspx?i=573, is there a work around or am I going to have to just remove all of these files... =/
Edit: More info...
I am using right now....
foreach (XmlNode xn in nodeList)
{
string url = xn.InnerText;
//Label1.Text = url;
try
{ using (FileStream fs = File.OpenRead(url)) { }
}
catch { i++; Label2.Text = i.ToString(); Label1.Text = url; }
}
The issue is, when it attempts to open files like the ....aspx?i=573 it puts them in the catch stack. If I attempt to open the file however the file opens just fine. (IE I have read access but because of either the file type or the append of the '?=' in the file name it tosses it into the unreadable stack.
I want everything that is readable either via url or local access to display else it will catch the error files for me.
I'm not sure exactly what you are trying to do, but if you only want the path of a URI, you can easily drop the query string portion like this:
Uri baseUri = new Uri("http://www.domain.com/");
Uri myUri = new Uri(baseUri, "home/default.aspx?i=573");
Console.WriteLine(myUri.AbsolutePath); // ie "home/default.aspx"
You cannot have ? in file names in Windows, but they are valid in URIs (that is why IE can open it, but Windows cannot).
Alternatively, you could just replace the '?' with some other character if you are converting a URL to a filename.
In fact thinking about it now, you could just check to see if your "document" was a URI or not, and if it isn't then try to open the file on the file system. Sounds like you are trying to open any and everything that is supplied, but it wouldn't hurt to performs some checks on the data.
private static bool IsLocalPath(string p)
{
return new Uri(p).IsFile;
}
This is from Check if the path input is URL or Local File it looks like exactly what you are looking for.
FileStream reads and writes local files. "?" is not valid character for local file name.
It looks like you want to open local and remote files. If it is what you are trying to do you should use approapriate metod of downloading for each type - i.e. for HTTP you WebRequest or related classes.
Note: it would be much easier to answer if you'd say: when url is "..." File.OpenRead(url) failes with exception, mesasge "...".

.NET Exception Handling Application Configuration File

I apologize as this question is somewhat basic; however, after a great deal of searching, I have not found a suitable answer. I am building a windows forms application and need to reference an app.config file for the location to a data file. Before calling
XElement xml = XElement.Load(ConfigurationManager.AppSettings["EntityData"].ToString());
I want to ensure that the app.config file exists. I have tried multiple methods but it seems that it is a lot more work then it should be. For example I have been trying to use the following code to determine the path for the file
Uri uri = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
string fullConfigurationFilename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(uri.AbsolutePath), configurationFilename);
but I run into issues with spaces in the path. Is there a better way to check for the existence of the app.config, do I even need to check?
Thank you
I don't think you need to verify that the config file exists. The following code should work without exceptions:
string temp = ConfigurationManager.AppSettings["EntityData"];
if (temp != null)
{
XElement xml = XElement.Load(temp);
}
Note that AppSettings will return a string if the key is found, so you don't need to call ToString to convert it. If the key does not exist, you should instead get a null reference that you can test for.
System.Configuration should do all of this work for you. There shouldn't be a need to manually load a config file.

Categories