Wednesday, April 27, 2011

Access/Edit files inside Silverlight XAP

While developing Silverlight applications, there were times where we might need to change the contents of a file that resides inside the Silverlight XAP from our ASP.Net hosting application. The ASP.Net (hosting application) holds the XAP file in the ClientBin folder.

One way of editing includes following steps:

  • Since XAP file is nothing but a ZIP file, we need to use any .net library for manipulating zip files. One such library is DotNetZip. Use it to retrieve the contents of XAP file.
  • Access and do related modifications of the file you need to update and save it in the application folder temporarily.
  • Remove the original file from the XAP file.
  • Add the temporary file into the XAP file.
  • Finaly, delete the temporary file.

Consider XAP file consists of xml file of format that we need to update :


<ConfigData>
  <Id>
    InitialTestId1
  </Id>
  <CategoryList>
    <Category ID="01">
      <MainCategory>Category 1</MainCategory>
      <Description>Description 1.</Description>
      <Active>true</Active>
    </Category>
  </CategoryList>
...........................
</ConfigData>


Snippet

In order to change the value of "Id" and remove all "CategoryList" element:
private void EditXAP(string xapFileName, string xmlFileToBeEdited)
{

    string clientBinPath = Server.MapPath(Request.ApplicationPath) + "/ClientBin/";
    string xapFilePath = clientBinPath + xapFileName;
    string templConfigFilePath = clientBinPath + xmlFileToBeEdited;
    Stream configXmlStream = new MemoryStream();
    ZipFile zipFile;

    zipFile = ZipFile.Read(xapFilePath);

    if (zipFile.EntryFileNames.Contains(xmlFileToBeEdited))
    {
        ZipEntry zipEntry = zipFile[xmlFileToBeEdited];
        zipEntry.Extract(configXmlStream);
        configXmlStream.Seek(0, 0);
        XDocument xDocument = XDocument.Load(configXmlStream);

        xDocument.Element("ConfigData").Element("Id").SetValue("AlteredId1");
        xDocument.Element("ConfigData").Elements("CategoryList").Remove();

        xDocument.Save(templConfigFilePath);

        zipFile.RemoveEntry(zipEntry);
        zipFile.AddFile(templConfigFilePath, "");
        zipFile.Save();

        FileInfo tempFile = new FileInfo(templConfigFilePath);
        if (tempFile.Exists)
        {
            tempFile.Delete();
        }
    }
}

Above specified snippet will update the XML file inside the Silvelight XAP.

References
http://dotnetzip.codeplex.com/ 

No comments:

Post a Comment

Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.