Модераторы: Partizan, gambit
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Преобразовать из Visual Basic на C#, Преобразовать Программу экзаменатор  
:(
    Опции темы
Fareastaz
Дата 5.4.2012, 08:56 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 4
Регистрация: 3.11.2011

Репутация: нет
Всего: нет



Уважамые разработчики,
у меня возник вопрос с преобразованием программы из Visual Basic в С#.
Программ экзаменатор. Есть XML файл и для него XSD,  из них считываются вопросы ответы и заполняется это все в radiobuttonlist. В конце выводятся результаты. В программе используется таймер я хотел бы отключить. Не могли бы вы помочь преобразовать это дело в C# ? С синтаксисом бэйсика не знаком поэтому пробовал через онлайн конвертер типа http://www.developerfusion.com/tools/convert/vb-to-csharp/ но он делает кучу ошибок...не всю логику разбирает.

Во вложении xml и xsd файлы.
Код файла quiz.aspx:

Код

<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.XPath" %>
 
<script language="VB" runat="server">
 
'Relative file path to XML data
Dim strXmlFilePath as String = Server.MapPath("quiz.xml")
 
Dim xDoc as New XPathDocument(strXmlFilePath)
Dim xNav as XPathNavigator = xDoc.CreateNavigator
Dim xNodeIterator as XPathNodeIterator
 
'Initialize variables
Dim intTotalQuestion as Integer
Dim intQuestionNo as Integer = 1
Dim intScore as Integer = 0
Dim arrAnswerHistory as new ArrayList()
 
Sub Page_Load(src as Object, e as EventArgs)
 
    'Start a new quiz?
    If Not Page.IsPostBack Then
 
        'Yes! Count total question
        intTotalQuestion = xNav.Select("/quiz/mchoice").Count
 
        'Record start time
        ViewState("StartTime") = DateTime.Now
 
        ShowQuestion(intQuestionNo)
    End If
End Sub
 
 
Sub btnSubmit_Click(src as Object, e as EventArgs)
 
    'Retrieve essential variables from state bag
    intTotalQuestion = ViewState("TotalQuestion")
    intQuestionNo = ViewState("QuestionNo")
    intScore = ViewState("Score")
    arrAnswerHistory = ViewState("AnswerHistory")
 
    'Correct answer?
    If rblAnswer.SelectedItem.Value = ViewState("CorrectAnswer") Then
        intScore += 1
        arrAnswerHistory.Add(0)
    Else
        arrAnswerHistory.Add(rblAnswer.SelectedItem.Value)
    End If
 
    'End of quiz?
    If intQuestionNo=intTotalQuestion Then
 
        'Yes! Show the result...
        QuizScreen.Visible = False
        ResultScreen.Visible = True
 
        'Render result screen
        ShowResult()
 
    Else
 
        'Not yet! Show another question...
        QuizScreen.Visible = True
        ResultScreen.Visible = False
        intQuestionNo += 1
    
        'Render next question
        ShowQuestion(intQuestionNo)
    End If
End Sub
 
 
Sub ShowQuestion(intQuestionNo as Integer)
    Dim strXPath as String
    Dim intLoop as Integer
    Dim objTimeSpent as TimeSpan
 
    strXPath = "/quiz/mchoice[" & intQuestionNo.ToString() & "]"
 
    'Extract question
    xNodeIterator = xNav.Select(strXPath & "/question")
    xNodeIterator.MoveNext()
    lblQuestion.Text = intQuestionNo.ToString() & ". " & xNodeIterator.Current.Value
 
    'Extract answers
    xNodeIterator = xNav.Select(strXPath & "/answer")
 
    'Clear previous listitems
    rblAnswer.Items.Clear
 
    intLoop = 0
    While xNodeIterator.MoveNext()
    
        intLoop += 1
 
        'Add item to radiobuttonlist
        rblAnswer.Items.Add(new ListItem(xNodeIterator.Current.Value, intLoop))
 
        'Extract correct answer
        If xNodeIterator.Current.GetAttribute("correct","") = "yes" Then
            ViewState("CorrectAnswer") = intLoop
        End If
 
    End While
 
    'Output Total Question
    lblTotalQuestion.Text = intTotalQuestion
 
    'Output Time Spent
    objTimeSpent = DateTime.Now.Subtract(ViewState("StartTime"))
    lblTimeSpent.Text = objTimeSpent.Minutes.ToString() & ":" & objTimeSpent.Seconds.ToString()
 
    'Store essential data to state bag
    ViewState("TotalQuestion") = intTotalQuestion
    ViewState("Score") = intScore
    ViewState("QuestionNo") = intQuestionNo
    ViewState("AnswerHistory") = arrAnswerHistory
 
End Sub
 
Sub ShowResult()
    Dim strResult as String
    Dim intCompetency as Integer
    Dim intLoop as Integer
    Dim strXPath as String
    Dim objTimeSpent as TimeSpan
    
    objTimeSpent = DateTime.Now.Subtract(ViewState("StartTime"))
 
    strResult  = "<center>"
    strResult += "<h3>Quiz Result</h3>"
    strResult += "<p>Points: " & intScore.ToString() & " of " & intTotalQuestion.ToString()
    strResult += "<p>Your Competency: " & int(intScore/intTotalQuestion*100).ToString() & "%"
    strResult += "<p>Time Spent: " & objTimeSpent.Minutes.ToString() & ":" & objTimeSpent.Seconds.ToString()
    strResult += "</center>"
 
    strResult += "<h3>Quiz Breakdown:</h3>"
    For intLoop = 1 to intTotalQuestion
        strXPath = "/quiz/mchoice[" & intLoop.ToString() & "]"
        xNodeIterator = xNav.Select(strXPath & "/question")
        xNodeIterator.MoveNext()
        strResult += "<b>" & intLoop.ToString() & ". " & xNodeIterator.Current.Value & "</b><br>"
        If arrAnswerHistory.Item(intLoop-1)=0 Then
            strResult += "<font color=""green""><b>Correct</b></font><br><br>"
        Else
            xNodeIterator = xNav.Select(strXPath & "/answer[" & arrAnswerHistory.Item(intLoop-1).ToString() & "]")
            xNodeIterator.MoveNext()
            strResult += "<b>You answered:</b> " & xNodeIterator.Current.Value & "<br>"
            strResult += "<font color=""red""><b>Incorrect</b></font><br><br>"
        End If
    Next
 
    lblResult.Text = strResult
End Sub
 
</script>
<html>
<head>
<title>Australian Geography Quiz</title>
</head>
 
<style>
body {
  font-size: 10pt;
  font-family: verdana,helvetica,arial,sans-serif;
  color:#000000;
  background-color:#eeeedd;
}
 
tr.heading {
  background-color:#900B08;
}
 
.button {
    border: 1px solid #000000;
    background-color: #ffffff;
}
 
</style>
 
<body>
<span id="QuizScreen" runat="server">
<form runat="server">
<table width="100%" border="0" cellpadding="2" cellspacing="0">
  <tr class="heading">
    <td width="50%"><font color="white"><b>Australian Geography Quiz</b></font></td>
    <td width="50%" align="right"><font color="white"><b>www.codeproject.com</b></font></td>
  </tr>
  <tr>
    <td colspan="2">
      <b><asp:label id="lblQuestion" runat="server" /></b><br>
      <asp:radiobuttonlist
         id="rblAnswer"
         RepeatDirection="vertical"
         TextAlign="right"
         RepeatLayout="table"
         runat="server" /><br>
      <asp:requiredfieldvalidator
         ControlToValidate="rblAnswer"
         ErrorMessage="Please pick an answer!"
         runat="server" /><br>
      <asp:button id="btnSubmit" class="button" text="  Next  " onClick="btnSubmit_Click" runat="server" />
    </td>
  </tr>
  <tr class="heading">
    <td width="50%"><font color="white"><b>Total <asp:label id="lblTotalQuestion" runat="server" /> questions</b></font></td>
    <td width="50%" align="right"><font color="white"><b>Time spent <asp:label id="lblTimeSpent" runat="server" /></b></font></td>
  </tr>
</table>
</form>
</span>
<span id="ResultScreen" runat="server">
<asp:label id="lblResult" runat="server" />
</span>
</body>
</html>


Добавлено через 6 минут и 22 секунды
Почемуто не прикрепились XML , XSD...
Код

<?xml version="1.0" encoding="UTF-8"?>
<!-- 10 question quiz about Australian Geography -->
<quiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="quiz.xsd">
    <mchoice>
        <question>What is the capital city of Australia?</question>
        <answer>Sydney</answer>
        <answer correct="yes">Canberra</answer>
        <answer>Melbourne</answer>
        <answer>Gold Coast</answer>
    </mchoice>
    <mchoice>
        <question>Launceston is the second largest city in which Australian state?</question>
        <answer>Victoria</answer>
        <answer>New South Wales</answer>
        <answer correct="yes">Tasmania</answer>
        <answer>Western Australia</answer>
    </mchoice>
    <mchoice>
        <question>Which state has the famous 'Twelve Apostles' ?</question>
        <answer correct="yes">Victoria</answer>
        <answer>South Australia</answer>
        <answer>New South Wales</answer>
        <answer>Western Australia</answer>
    </mchoice>
    <mchoice>
        <question>Which is a popular ski resort in NSW?</question>
        <answer correct="yes">Perisher Blue</answer>
        <answer>Mt. Buller</answer>
        <answer>Mt. Baw-Baw</answer>
        <answer>Lake Mountain</answer>
    </mchoice>
    <mchoice>
        <question><![CDATA[Which of the following is <u>NOT</u> Australian native animals?]]></question>
        <answer>Kangaroo</answer>
        <answer correct="yes">Penguin</answer>
        <answer>Koala</answer>
        <answer>Wombat</answer>
    </mchoice>
    <mchoice>
        <question>Which city has an extensive tram network?</question>
        <answer>Sydney</answer>
        <answer correct="yes">Melbourne</answer>
        <answer>Adelaide</answer>
        <answer>Ballarat</answer>
    </mchoice>
    <mchoice>
        <question>What is known as 'The Silver City' in Australia?</question>
        <answer>Alice Springs</answer>
        <answer correct="yes">Broken Hill</answer>
        <answer>Ballarat</answer>
        <answer>Silverton</answer>
    </mchoice>
    <mchoice>
        <question>In which location the war movie 'Thin Red Line' was taken?</question>
        <answer>Anglesea</answer>
        <answer>Apollo Bay</answer>
        <answer>Margaret River</answer>
        <answer>Monkey Mia</answer>
        <answer correct="yes">Townsville</answer>
    </mchoice>
    <mchoice>
        <question><![CDATA[Which is <u>NOT</u> true about Uluru ?]]></question>
        <answer>It is the world biggest monolith located in the centre of Australian continent</answer>
        <answer>It was named 'Ayers Rock' by European explorer William Gosse in 1873</answer>
        <answer correct="yes">Aboriginal people encourage tourists to climb Uluru</answer>
        <answer>The area contains carvings and paintings by Aboriginal people</answer>
    </mchoice>
    <mchoice>
        <question>What is so special about Longreach?</question>
        <answer>The place where a blacksmith named Thomas Hiscock found the first gold that triggerred gold rush</answer>
        <answer>The town has an expansive, well-preserved penal colony of Australia's early history</answer>
        <answer correct="yes">The first commercial flight by Qantas took from this town in 1921</answer>
        <answer>None of these answers are correct</answer>
    </mchoice>
</quiz>

PM MAIL   Вверх
diadiavova
Дата 5.4.2012, 11:11 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Доктор Зло(диагност, настоящий, с лицензией и полномочиями)
****


Профиль
Группа: Модератор
Сообщений: 5821
Регистрация: 14.8.2008
Где: В Коньфпольте

Репутация: 31
Всего: 142



Fareastaz, Конвертеры всегда делают кучу ошибок. А "помочь" в смысле сделать это за тебя могут только фрилансеры, очень сильно сомневаюсь, что кто-то будет делать это из любви к искусству. Кинь вопрос сюда, может помогут
http://vingrad.ru/


--------------------
Хочешь получить мудрый совет - читай подписи участников форумов.
Злой доктор Щасзаболит smile
PM   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
mr.DUDA
THandle

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.
Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)? Пишите сюда, или отправляйте репорт. Поставим :)
Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, THandle.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Общие вопросы по .NET и C# | Следующая тема »


 




[ Время генерации скрипта: 0.0753 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.