Skip to main content

Microsoft Silverlight

Answered Question Cannot write xml back to host.RSS Feed

(0)

Aledut
Aledut

Member

Member

0 points

4 Posts

Cannot write xml back to host.

   Hello, im new to silverlight and im having a hard time with XML files.

   I wrote an application that loads a XML  like this :

XDocument myXML = XDocument.Load("Settings.xml");

   I can then get the information i want from this object and i insert new items :

myXML.Element("Settings").Add(new XElement("Setting", new XElement("juros", "1000")));

  So i would like to know how i "save" this xml back to the host so when i load the file again it wont lose all the changes ive made...

  Any sugestions (with an example please) ? 

 

SteveWong
SteveWong

Contributor

Contributor

6343 points

1,281 Posts

Re: Cannot write xml back to host.

Read the posts here first:

 http://silverlight.net/forums/t/17847.aspx

PS. you cant write the XML back to FileSystem in Silverlight because of sercrity reason. What you need is the help of Service. You should first save the XDocument into the Isolated Storage and then pass the filestring including the filename back to the WebService, then WebService can do writing and replacing on FileSystem which help you to update the file

Regards,
SteveWong (HongKong)
Please mark post as answer if they help you

Client App Dev

sladapter
sladapter

All-Star

All-Star

17445 points

3,173 Posts

Answered Question

Re: Cannot write xml back to host.

When you do XDocument.Load("Settings.xml"); that tells me your Settings.xml is build in your Xap, is that right?

You can always send the updated xml string back to your server through a WebService call. Have that WebService to save the xml to a file. But I don't think that Web Service can save that file back to your Xap.

The best way is to take out the settings.xml file from your Silverlight project and put it under a folder of your Web project (or your web site). You use a WebClient.downloadString method to get it over to the Silverlight side,  and use a Web Serivice call to send it back to the server if you made change.

You can by pass the isolated storage saving if you do not need it to be saved in the client disk temporarily.

code to download the file:

           WebClient wc = new WebClient();         
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
            wc.DownloadStringAsync(new Uri(Application.Current.Host.Source, "../YourFileFolder/Setting.xml")); // this assume your Setting.xml in under your Web Project/YourFileFolder.

void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
        
            if (e.Error == null)
            {
                XDocument myXML =XDocument.Parse(e.Result);

               ...

           }

 

To Save your File, add a WCF Silverlight Enabled service on your Web Project

[ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class YourService

{

public string SaveFile(ref string filename, string filecontent)
        {
           // save the xml to Setting.xml under YourFileFolder      

         }      

 }

 Add ServiceReference to your Silverlight Project.

Add code to send your new xml back:

var ws = new YourService.YourServiceClient();ws.SaveFileCompleted += new EventHandler<YourService.SaveFileCompletedEventArgs>(ws_SaveFileCompletedCompleted);
ws.SaveFileAsync("Setting.xml", yourXmlString);

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

Aledut
Aledut

Member

Member

0 points

4 Posts

Re: Cannot write xml back to host.

Thats exactly what i need. Do you know anywhere i can find an easy tutorial for that ?

Im almost giving up and going for a simple table in an SQL server and use the WCF + LINQ to SQL services...  (I think the xml would run faster in silverlight, thats why i tried this solution.)

Yi-Lun Luo - MSFT
Yi-Lun L...

All-Star

All-Star

25052 points

2,747 Posts

Answered Question

Re: Cannot write xml back to host.

Hello, I think it's better to use an ASP.NET page to upload files. While the difference is not noticeable for text files, for binary files, such as videos, by using WCF, you'll have to encode the binary content to text, which will make your file 8 times larger! WCF does support stream, which uses binary transfer, unfortunately this feature is not supported in Silverlight yet. However, with ASP.NET, you naturally have access to the input stream:

 protected void Page_Load(object sender, EventArgs e)
 {
string fileName = Request.Params["filename"];
if (!string.IsNullOrEmpty(fileName))
{
Stream inputStream = Request.InputStream;
FileStream fileStream = File.Create(Server.MapPath("~") + "\\" + fileName);
byte[] fileContent = new byte[inputStream.Length];
inputStream.Read(fileContent, 0, fileContent.Length);
fileStream.Write(fileContent, 0, fileContent.Length);
fileStream.Flush();
fileStream.Close();
inputStream.Close();
//No need to respond.
Response.Clear();
Response.End();
}

 

To call this ASP.NET page, you use a WebClient: 

WebClient webClient = new WebClient();
webClient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webClient_OpenWriteCompleted);
webClient.OpenWriteAsync(new Uri("http://localhost:49601/UploadTestWeb/Default.aspx?filename=Settings.xml"));

void webClient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
Stream outputStream = e.Result;
byte[] fileContent = Encoding.UTF8.GetBytes(myXml.ToString());
outputStream.Write(fileContent, 0, fileContent.Length);
//No need to flush.
outputStream.Close();
}

shanaolanxing - I'll transfer to the Windows Azure team, and will have limited time to participate in the Silverlight forum. Apologize if I don't answer your questions in time.

Shaji-mji
Shaji-mji

Participant

Participant

1129 points

260 Posts

Re: Cannot write xml back to host.

 You can create a object with the all the nodes as its properties. Convert the xml to this object that can be used for modification. Similarly you can create a xml from these objects when you save.

 

            XDocument docs = new XDocument();
            docs = XDocument.Parse(e.Result);

            var doc = from doc in docsInBox.Descendants("RootNode")
                        select new Object
                        {
                            ApplicationID = (int)(doc.Element("ApplicationID")),

                            Name= (int)(doc.Element("Name")),......

                       }

The above exlains how to create a object collection from a XML file, you can do the opposite for saving....
 

  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities