How to do my Silverlight project read my xml file?

346 views Asked by At

I have a big problem. I have to do a quiz in Silverlight with different level of difficulty. I never use this framework and now I try to learn. First, I tried to read my xml file with this framework and I used c# as programming language. I wrote this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Data;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace quiz4
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            var quizzes = new List<Quiz>();
            var objSettings = new XmlReaderSettings();
            objSettings.IgnoreWhitespace = true;
            objSettings.IgnoreComments = true;
            const string booksFile = @"D:\quiz.xml";
            string element = "";

            using (XmlReader objReader = XmlReader.Create(booksFile, objSettings))
            {
                bool isLastElement = false;
                var quiz = new Quiz();
                var dx = new List<Answers>();

                while (objReader.Read())
                {

                    if (objReader.NodeType == XmlNodeType.Element)
                    {
                        element = objReader.Name;
                        if (element == "question")
                        {
                            quiz = new Quiz();
                            dx = new List<Answers>();
                            isLastElement = true;
                        }
                    }
                    else if (objReader.NodeType == XmlNodeType.Text)
                    {
                        switch (element)
                        {
                            case "questionText":
                                quiz.QuestionText = objReader.Value;
                                //Console.WriteLine("questionText: " + objReader.Value);
                                break;
                            case "LEVEL":
                                quiz.Level = objReader.Value;
                                //Console.WriteLine("LEVEL  " + objReader.Value);
                                break;
                            case "correct":
                                dx.Add(new Answers() { IsCorrect = true, AnswerName = objReader.Value });
                                //Console.WriteLine("correct: " + objReader.Value);
                                break;
                            case "incorrect":
                                dx.Add(new Answers() { IsCorrect = false, AnswerName = objReader.Value });
                                //Console.WriteLine("incorrect: " + objReader.Value);
                                break;
                        }
                    }

                    if (isLastElement)
                    {
                        quiz.AnswerList = dx;
                        quizzes.Add(quiz);
                        isLastElement = false;
                    }

                }
            }

        }

        class Quiz
        {
            public string QuestionText;
            public string Level;
            public List<Answers> AnswerList;//lista de raspunsuri
        }

        public class Answers
        {
            public bool IsCorrect;//raspuncul poate fi adevarat(true) sau false.
            public string AnswerName;//raspunsul
        }

XML file:

<?xml version="1.0" encoding="utf-8" ?>
<quiz>
<question>
<questionText>In Oracle SQL * PLUS, functia LOWER (col/value) permite:</questionText>
<LEVEL>2</LEVEL> 
<correct>fortarea caracterelor scrise cu litere mari sau mixte, in caractere scrise cu litere mici</correct>
<incorrect>fortarea caracterelor scrise cu litere mici in caractere scrise cu litere maric)</incorrect>
<incorrect>returnarea numarului de caractere din coloana sau valoarea literalad)</incorrect>
<incorrect>translatarea lungimii caracterelor dintr-o coloana/valoare la o lungime specificata</incorrect>
</question>

<question>
<questionText>In Oracle SQL * PLUS, functia INITCAP permite:</questionText>
<LEVEL>1</LEVEL> 
<incorrect>transformarea oricarei litere a unui cuvant, in litera mare</incorrect>
<correct>transformarea primei litere a fiecarui cuvant/coloana in litera mare</correct>
<incorrect>transformarea unei litere specificate a unui cuvant , intr-o litera mare </incorrect>
<incorrect>este o similitudine cu alte SGBD si nu exista specificata in SQL*PLYS</incorrect>
</question>
</quiz>

When I press F5 nothing happends. Why? Can someone help me? Thanks!

2

There are 2 answers

1
Håkan Fahlstedt On BEST ANSWER

As stated in an earlier answer, you can't access files directly from the local files structure in Silverlight. The way you usally do this is to host the file (in your case the quiz.xml) on the web server and let Silverlight do a call to the web server to fetch the file. You can host the file on the same web server that is hosting the silverlight application. This is done asynchronously, and you could initiate this call in the constructor. Another thing is the way you read the xml-file, it looks a bit strange to me, I would prefer to use Linq to XML. So here is what I would do:

public partial class MainPage : UserControl
{
        private List<Quiz> quizzes;

        public MainPage()
        {
            InitializeComponent();

            var xmlUri = new Uri("http://yoursite.com/quiz.xml");
            var downloader = new WebClient();

            downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
            downloader.OpenReadAsync(xmlUri);
        }


        void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
           if (e.Error == null)
           {
              Stream responseStream = e.Result;

               using (var reader = XmlReader.Create(responseStream))
               {
                  var doc = XDocument.Read(reader);

                  quizzes = doc.Descendants("question")
                            .Select(q => new Quiz 
                            {
                               QuestionText = q.Element("questionText").Value, 
                               Level = q.Element("LEVEL").Value,
                               AnswerList = q.Descendants("incorrect")
                                             .Select(i => new Answers 
                                             { 
                                                IsCorrect = false, 
                                                AnswerName = i.Value 
                                             })
                                             .Union(
                                                q.Descendants("correct")
                                                 .Select(i => new Answers 
                                                 { 
                                                    IsCorrect = true, 
                                                    AnswerName = i.Value 
                                             })).ToList()

                            }).ToList();      
               }
           }
        }         
    }
0
Martin Liversage On

Silverlight is running in a sandbox in the browser your application does not have access to the local file system (e.g. D:\quiz.xml). You will have to install your Silverlight application as a trusted application to get full access to the local file system.

If you manage to get around this restriction in Silverlight you should make another change to your application. Right now you are reading the XML in the constructor of the MainPage class (and because of the restriction I have described an exception is thrown). You should move this code into and event handler (e.g. for the Loaded event) but you should also make sure that any file system or network access is done using asynchronous methods. E.g., the UI is updated in asynchronous callbacks.

If you are learning C# you will discover that writing a Silverlight application will move focus away from simply learning the language because of the additional restrictions imposed by Silverlight.