Example #1
0
        public void DocumentOtherTypes()
        {
            object[] nodeset = { " ", new XProcessingInstruction("pi", "data"), new XProcessingInstruction("pi2", "data2"), new XComment("comm"), new XDocumentType("root", null, null, null), new XElement("single"), new XElement("complex", new XElement("a1"), new XElement("a2")) };

            XDocument doc = ((bool)Variation.Param) ? new XDocument(new XDeclaration("1.0", null, null)) : new XDocument();

            int pos = ((bool)Param) ? 0 : nodeset.Length - 1;

            foreach (var combination in nodeset.PositionCombinations(pos))
            {
                if (combination.Select(c => new ExpectedValue(false, c)).IsXDocValid())
                {
                    continue;
                }
                doc.Add(combination);
                XNode ret = ((bool)Param) ? doc.FirstNode : doc.LastNode;

                if (combination[pos] is string)
                {
                    TestLog.Compare(ret is XText, "text node");
                    TestLog.Compare((ret as XText).Value, combination[pos], "text node value");
                }
                else
                {
                    TestLog.Compare(ret.Equals(combination[pos]), "Node not OK");
                }
                doc.RemoveNodes();
            }
        }
Example #2
0
 /// <summary>
 /// Сохранить все данные в файле XML
 /// </summary>
 /// <returns>Errors</returns>
 static string SaveToXml()
 {
     try
     {
         XDocument xdoc = new XDocument();
         if (File.Exists(FilePath))
         {
             xdoc = XDocument.Load(FilePath);
             xdoc.RemoveNodes();
         }
         XElement rootNode = new XElement("Applications");
         foreach (var app in Apps)
         {
             XElement currApp = new XElement("App");
             currApp.Add(new XElement("Name", app.Name));
             currApp.Add(new XElement("ReleaseFolderPath", app.ReleasePath));
             currApp.Add(new XElement("WorkFolderPath", app.WorkingReleasePath));
             currApp.Add(new XElement("ReestrFolderPath", app.ReestrPath));
             rootNode.Add(currApp);
         }
         xdoc.Add(rootNode);
         xdoc.Save(FilePath);
         return("OK");
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
        public void ValidAddIntoXDocument(TestedFunction testedFunction, CalculateExpectedValues calculateExpectedValues)
        {
            runWithEvents = (bool)Params[0];
            var isConnected = (bool)Variation.Params[0];
            var combCount   = (int)Variation.Params[1];

            object[] nodes = { new XDocumentType("root", "", "", ""), new XDocumentType("roo2t", "", "", ""), new XProcessingInstruction("PI", "data"), new XComment("Comment"), new XElement("elem1"), new XElement("elem2", new XElement("C", "nodede")), new XText(""), new XText(" "), new XText("\t"), new XCData(""), new XCData("<A/>"), " ", "\t", "", null };

            object[] origNodes = { new XProcessingInstruction("OO", "oo"), new XComment("coco"), " ", new XDocumentType("root", null, null, null), new XElement("anUnexpectedlyLongNameForTheRootElement") };

            if (isConnected)
            {
                new XElement("foo", nodes.Where(n => n is XNode && !(n is XDocumentType)));
                foreach (XNode nn in nodes.Where(n => n is XDocumentType))
                {
                    new XDocument(nn);
                }
            }

            foreach (var origs in origNodes.NonRecursiveVariations(2))
            {
                if (origs.Select(o => new ExpectedValue(false, o)).IsXDocValid())
                {
                    continue;
                }
                foreach (var o in nodes.NonRecursiveVariations(combCount))
                {
                    var   doc = new XDocument(origs);
                    XNode n   = doc.FirstNode;

                    List <ExpectedValue> expNodes = Helpers.ProcessNodes(calculateExpectedValues(doc, 0, o)).ToList();
                    bool shouldFail = expNodes.IsXDocValid();

                    try
                    {
                        if (runWithEvents)
                        {
                            eHelper = new EventsHelper(doc);
                        }
                        testedFunction(n, o);
                        TestLog.Compare(!shouldFail, "should fail - exception expected here");
                        TestLog.Compare(expNodes.EqualAll(doc.Nodes(), XNode.EqualityComparer), "nodes does not pass");
                    }
                    catch (InvalidOperationException ex)
                    {
                        TestLog.Compare(shouldFail, "Unexpected exception : " + ex.Message);
                    }
                    catch (ArgumentException ex)
                    {
                        TestLog.Compare(shouldFail, "Unexpected exception : " + ex.Message);
                    }
                    finally
                    {
                        doc.RemoveNodes();
                    }
                }
            }
        }
Example #4
0
                /// <summary>
                /// Runs test for valid cases
                /// </summary>
                /// <param name="nodeType">XElement/XAttribute</param>
                /// <param name="name">name to be tested</param>
                public void RunValidTests(string nodeType, string name)
                {
                    XDocument xDocument = new XDocument();
                    XElement  element   = null;

                    try
                    {
                        switch (nodeType)
                        {
                        case "XElement":
                            element = new XElement(name, name);
                            xDocument.Add(element);
                            IEnumerable <XNode> nodeList = xDocument.Nodes();
                            TestLog.Compare(nodeList.Count(), 1, "Failed to create element { " + name + " }");
                            xDocument.RemoveNodes();
                            break;

                        case "XAttribute":
                            element = new XElement(name, name);
                            XAttribute attribute = new XAttribute(name, name);
                            element.Add(attribute);
                            xDocument.Add(element);
                            XAttribute x = element.Attribute(name);
                            TestLog.Compare(x.Name.LocalName, name, "Failed to get the added attribute");
                            xDocument.RemoveNodes();
                            break;

                        case "XName":
                            XName xName = XName.Get(name, name);
                            TestLog.Compare(xName.LocalName.Equals(name), "Invalid LocalName");
                            TestLog.Compare(xName.NamespaceName.Equals(name), "Invalid Namespace Name");
                            TestLog.Compare(xName.Namespace.NamespaceName.Equals(name), "Invalid Namespace Name");
                            break;

                        default:
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        TestLog.WriteLine(nodeType + "failed to create with a valid name { " + name + " }");
                        throw new TestFailedException(e.ToString());
                    }
                }
Example #5
0
        public void Document1()
        {
            object[] content = new object[]
            {
                new object[] { new string[] { " ", null, " " }, "  " },
                new object[] { new string[] { " ", " \t" }, new XText("  \t") },
                new object[] { new XText[] { new XText(" "), new XText("\t") }, new XText(" \t") },
                new XDocumentType("root", "", "", ""), new XProcessingInstruction("PI1", ""), new XText("\n"),
                new XText("\t"), new XText("       "), new XProcessingInstruction("PI1", ""), new XElement("myroot"),
                new XProcessingInstruction("PI2", "click"),
                new object[]
                {
                    new XElement("X", new XAttribute("id", "a1"), new XText("hula")),
                    new XElement("X", new XText("hula"), new XAttribute("id", "a1"))
                },
                new XComment(""),
                new XComment("comment"),
            };

            foreach (object[] objs in content.NonRecursiveVariations(4))
            {
                XDocument doc1 = null;
                XDocument doc2 = null;
                try
                {
                    object[] o1 = ExpandAndProtectTextNodes(objs, 0).ToArray();
                    object[] o2 = ExpandAndProtectTextNodes(objs, 1).ToArray();
                    if (o1.Select(x => new ExpectedValue(false, x)).IsXDocValid() ||
                        o2.Select(x => new ExpectedValue(false, x)).IsXDocValid())
                    {
                        continue;
                    }
                    doc1 = new XDocument(o1);
                    doc2 = new XDocument(o2);
                    VerifyComparison(true, doc1, doc2);
                }
                catch (InvalidOperationException)
                {
                    // some combination produced from the array are invalid
                    continue;
                }
                finally
                {
                    if (doc1 != null)
                    {
                        doc1.RemoveNodes();
                    }
                    if (doc2 != null)
                    {
                        doc2.RemoveNodes();
                    }
                }
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            if (args.Length < 0)
            {
                return;
            }

            if (!args.All(i => i.EndsWith(".meta")) && !args.All(i => i.EndsWith(".xml")))
            {
                return;
            }

            try
            {
                for (int i = 0; i < args.Length; i++)
                {
                    var arg = args[i];
                    Console.WriteLine("Enter a string value:");
                    var userInput = Console.ReadLine();

                    XDocument doc = XDocument.Load(arg);
                    doc.RemoveNodes(userInput, "Entry", "SlotNavigateOrder", "Item", "WeaponSlots", "Item");
                    doc.RemoveNodes(userInput, "Entry", "SlotBestOrder", "WeaponSlots", "Item");
                    doc.ClearNode("TintSpecValues");
                    doc.ClearNode("FiringPatternAliases");
                    doc.ClearNode("UpperBodyFixupExpressionData");
                    doc.ClearNode("AimingInfos");
                    doc.RemoveNodes(userInput, "Name", "Infos", "Item", "Infos", "Item");
                    doc.ClearNode("VehicleWeaponInfos");
                    doc.Save(arg + ".new.xml");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
                Console.ReadLine();
            }

            Console.WriteLine("Press [Enter] to exit...");
            Console.ReadLine();
        }
Example #7
0
        private void TestReplacement(XDocument e, object[] nodes, int numOfNodes)
        {
            for (int i = 0; i < e.Nodes().Count(); i++)
            {
                object[] allowedNodes = e.Nodes().ElementAt(i) is XElement?nodes.Where(o => !(o is XElement)).ToArray() : nodes;

                foreach (var replacement in nodes.NonRecursiveVariations(numOfNodes))
                {
                    bool shouldFail = false;

                    var   doc                   = new XDocument(e);
                    XNode toReplace             = doc.Nodes().ElementAt(i);
                    XNode prev                  = toReplace.PreviousNode;
                    XNode next                  = toReplace.NextNode;
                    bool  isReplacementOriginal = replacement.Where(o => o is XNode).Where(o => (o as XNode).Document != null).IsEmpty();

                    IEnumerable <ExpectedValue> expValues = ReplaceWithExpValues(doc, toReplace, replacement).ProcessNodes().ToList();

                    // detect invalid states
                    shouldFail = expValues.IsXDocValid();

                    try
                    {
                        if (_runWithEvents)
                        {
                            _eHelper = new EventsHelper(doc);
                        }
                        toReplace.ReplaceWith(replacement);

                        TestLog.Compare(!shouldFail, "Should fail ... ");
                        TestLog.Compare(toReplace.Parent == null, "toReplace.Parent == null");
                        TestLog.Compare(toReplace.Document == null, "toReplace.Document == null");
                        TestLog.Compare(expValues.EqualAll(doc.Nodes(), XNode.EqualityComparer), "expected values");
                        if (isReplacementOriginal)
                        {
                            TestLog.Compare(replacement.Where(o => o is XNode).Where(o => (o as XNode).Document != doc.Document).IsEmpty(), "replacement.Where(o=>o is XNode).Where(o=>(o as XNode).Document!=doc.Document).IsEmpty()");
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        TestLog.Compare(shouldFail, "Exception not expected here");
                    }
                    catch (ArgumentException)
                    {
                        TestLog.Compare(shouldFail, "Exception not expected here");
                    }
                    finally
                    {
                        doc.RemoveNodes();
                    }
                }
            }
        }
Example #8
0
        private void VerifyRemoveNodes(XDocument doc)
        {
            IEnumerable <XNode> nodesBefore = doc.Nodes().ToList();
            XDeclaration        decl        = doc.Declaration;

            doc.RemoveNodes();

            TestLog.Compare(doc.Nodes().IsEmpty(), "e.Nodes().IsEmpty()");
            TestLog.Compare(nodesBefore.Where(n => n.Parent != null).IsEmpty(), "nodesBefore.Where(n=>n.Parent!=null).IsEmpty()");
            TestLog.Compare(nodesBefore.Where(n => n.Document != null).IsEmpty(), "nodesBefore.Where(n=>n.Parent!=null).IsEmpty()");
            TestLog.Compare(doc.Declaration == decl, "doc.Declaration == decl");
        }
Example #9
0
        public void DocumentXmlDeclaration()
        {
            XDocument doc = new XDocument();

            Assert.Null(doc.Declaration);

            XDeclaration dec  = new XDeclaration("1.0", "utf-16", "yes");
            XDocument    doc2 = new XDocument(dec);

            Assert.Same(dec, doc2.Declaration);

            doc2.RemoveNodes();
            Assert.NotNull(doc2.Declaration);
        }
Example #10
0
                /// <summary>
                /// Tests the Parent property on Node.
                /// </summary>
                /// <param name="context"></param>
                /// <returns></returns>
                //[Variation(Desc = "NodeParent")]
                public void NodeParent()
                {
                    // Only elements are returned as parents from the Parent property.
                    // Documents are not returned.
                    XDocument document = new XDocument();

                    XNode[] nodes = new XNode[]
                    {
                        new XComment("comment"),
                        new XElement("element"),
                        new XProcessingInstruction("target", "data"),
                        new XDocumentType("name", "publicid", "systemid", "internalsubset")
                    };

                    foreach (XNode node in nodes)
                    {
                        Validate.IsNull(node.Parent);
                        document.Add(node);
                        Validate.IsReferenceEqual(document, node.Document);
                        // Parent element is null.
                        Validate.IsNull(node.Parent);
                        document.RemoveNodes();
                    }

                    // Now test the cases where an element is the parent.
                    nodes = new XNode[]
                    {
                        new XComment("abcd"),
                        new XElement("nested"),
                        new XProcessingInstruction("target2", "data2"),
                        new XText("text")
                    };

                    XElement root = new XElement("root");

                    document.ReplaceNodes(root);

                    foreach (XNode node in nodes)
                    {
                        Validate.IsNull(node.Parent);

                        root.AddFirst(node);

                        Validate.IsReferenceEqual(node.Parent, root);

                        root.RemoveNodes();
                        Validate.IsNull(node.Parent);
                    }
                }
Example #11
0
                /// <summary>
                /// Validate behavior of the XDocument XmlDeclaration property.
                /// </summary>
                /// <returns>true if pass, false if fail</returns>
                //[Variation(Desc = "DocumentXmlDeclaration")]
                public void DocumentXmlDeclaration()
                {
                    XDocument doc = new XDocument();

                    Validate.IsNull(doc.Declaration);

                    XDeclaration dec  = new XDeclaration("1.0", "utf-16", "yes");
                    XDocument    doc2 = new XDocument(dec);
                    XDeclaration dec2 = doc2.Declaration;

                    Validate.IsReferenceEqual(dec2, dec);

                    doc2.RemoveNodes();
                    Validate.IsNotNull(doc2.Declaration);
                }
Example #12
0
        public void DocumentRoot()
        {
            XDocument doc = new XDocument();

            Assert.Null(doc.Root);

            XElement e = new XElement("element");

            doc.Add(e);
            Assert.Same(e, doc.Root);

            doc.RemoveNodes();
            doc.Add(new XComment("comment"));
            Assert.Null(doc.Root);
        }
Example #13
0
        /// <summary>
        /// Runs test for valid cases
        /// </summary>
        /// <param name="nodeType">XElement/XAttribute</param>
        /// <param name="name">name to be tested</param>
        private static void RunValidTests(string nodeType, string name)
        {
            XDocument xDocument = new XDocument();
            XElement  element   = null;

            switch (nodeType)
            {
            case "XElement":
                element = new XElement(name, name);
                xDocument.Add(element);
                IEnumerable <XNode> nodeList = xDocument.Nodes();
                Assert.True(nodeList.Count() == 1, "Failed to create element { " + name + " }");
                xDocument.RemoveNodes();
                break;

            case "XAttribute":
                element = new XElement(name, name);
                XAttribute attribute = new XAttribute(name, name);
                element.Add(attribute);
                xDocument.Add(element);
                XAttribute x = element.Attribute(name);
                Assert.Equal(name, x.Name.LocalName);
                xDocument.RemoveNodes();
                break;

            case "XName":
                XName xName = XName.Get(name, name);
                Assert.Equal(name, xName.LocalName);
                Assert.Equal(name, xName.NamespaceName);
                Assert.Equal(name, xName.Namespace.NamespaceName);
                break;

            default:
                break;
            }
        }
Example #14
0
        public void ExecuteXDocumentVariation(XNode[] content)
        {
            XDocument xDoc         = new XDocument(content);
            XDocument xDocOriginal = new XDocument(xDoc);

            using (UndoManager undo = new UndoManager(xDoc))
            {
                undo.Group();
                using (EventsHelper docHelper = new EventsHelper(xDoc))
                {
                    xDoc.RemoveNodes();
                    docHelper.Verify(XObjectChange.Remove, content);
                }
                undo.Undo();
                Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!");
            }
        }
Example #15
0
                /// <summary>
                /// Validate behavior of the XDocument Root property.
                /// </summary>
                /// <returns>true if pass, false if fail</returns>
                //[Variation(Desc = "DocumentRoot")]
                public void DocumentRoot()
                {
                    XDocument doc = new XDocument();

                    Validate.IsNull(doc.Root);

                    XElement e = new XElement("element");

                    doc.Add(e);
                    XElement e2 = doc.Root;

                    Validate.IsReferenceEqual(e2, e);

                    doc.RemoveNodes();
                    doc.Add(new XComment("comment"));
                    Validate.IsNull(doc.Root);
                }
Example #16
0
                /// <summary>
                /// Tests the Document property on Node.
                /// </summary>
                /// <param name="context"></param>
                /// <returns></returns>
                //[Variation(Desc = "NodeDocument")]
                public void NodeDocument()
                {
                    XDocument document = new XDocument();

                    XNode[] topLevelNodes = new XNode[]
                    {
                        new XComment("comment"),
                        new XElement("element"),
                        new XProcessingInstruction("target", "data"),
                    };

                    XNode[] nestedNodes = new XNode[]
                    {
                        new XText("abcd"),
                        new XElement("nested"),
                        new XProcessingInstruction("target2", "data2")
                    };

                    // Test top-level cases.
                    foreach (XNode node in topLevelNodes)
                    {
                        Validate.IsNull(node.Document);
                        document.Add(node);
                        Validate.IsReferenceEqual(document, node.Document);
                        document.RemoveNodes();
                    }

                    // Test nested cases.
                    XElement root = new XElement("root");

                    document.Add(root);

                    foreach (XNode node in nestedNodes)
                    {
                        Validate.IsNull(node.Document);
                        root.Add(node);
                        Validate.IsReferenceEqual(document, root.Document);
                        root.RemoveNodes();
                    }
                }
Example #17
0
        public ERR_RESULT XML_Free()
        {
            ERR_RESULT result = new ERR_RESULT();

            try
            {
                m_Xroot.RemoveAll();
                m_xDoc.RemoveNodes();

                m_Xroot = null;
                m_xDoc  = null;
                return(result);
            }
            catch (_XmlException err)
            {
                result = ErrProcess.SetErrResult(err);
                return(result);
            }
            catch (Exception err)
            {
                result = ErrProcess.SetErrResult(err);
                return(result);
            }
        }
Example #18
0
        public static string BodyConverter(string[] ttesterFiles, System.Windows.Controls.ProgressBar ProgBar, bool CheckIsOneFile)

        {
            //возвращает сообщение с логом выполнения функции
            string Result = "";

            //если не создана папка для сохранения в my documents, создаём её
            string saveFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Ttester To Moodle Converter\\";

            if (!Directory.Exists(saveFolder))
            {
                Directory.CreateDirectory(saveFolder);
            }
            //Создаем логфайл
            StreamWriter Logfile = new StreamWriter(saveFolder + "LogErrors.txt", false, System.Text.Encoding.Default);

            //массив путей .txt файлов
            if (ttesterFiles.Length == 0)
            {
                Console.WriteLine("Нет файлов для обработки"); Logfile.WriteLine("Нет файлов для обработки");
            }

            //создаем xml-документ, главный xml-тэг и список остальных тэгов
            XDocument       XMLFile       = new XDocument();
            XElement        quiz          = new XElement("quiz");
            List <XElement> quizChildrens = new List <XElement>();

            //конвертируем каждый xml-файл
            foreach (var ttesterFileName in ttesterFiles)
            {
                //какая-то магия для прогрессбара
                Application.Current.Dispatcher.BeginInvoke(new ThreadStart(delegate { ProgBar.Value += 1; }));


                //создаем список строк из исходного ttester-файла
                StreamReader  ttesterTxt  = new StreamReader(ttesterFileName, System.Text.Encoding.Default);
                List <string> listOfLines = textToList(ttesterTxt);
                ttesterTxt.Close();

                //создаем элемент класса с содержанием теста
                TtesterClass TestInfo = new TtesterClass();


                bool flagTheme     = false;
                bool flagThemeEnds = false;

                bool flagQuestion = false;

                bool flagTitle     = false;
                bool flagTitleEnds = false;

                //разбираем каждую строчку
                for (int i = 0; i < listOfLines.Count; i++)
                {
                    //разбираем ##THEMES
                    if (flagThemeEnds == false)
                    {
                        if (String.IsNullOrWhiteSpace(listOfLines[i]) & flagTheme == true)
                        {
                            flagTheme = false; flagThemeEnds = true;
                        }                                                                                                                   //относятся к темам
                        if (flagTheme == true)
                        {
                            TestInfo.themes.Add(listOfLines[i]);                                                                            //относятся к темам
                        }
                        if (listOfLines[i].Contains("###THEMES###"))
                        {
                            flagTheme = true;                                                                                               //относятся к темам
                        }
                    }

                    //разбираем ###TITLE###
                    if (flagTitleEnds == false)
                    {
                        if (String.IsNullOrWhiteSpace(listOfLines[i]) & flagTitle == true)
                        {
                            flagTitle = false; flagTitleEnds = true;
                        }
                        if (flagTitle == true)
                        {
                            TestInfo.title = System.Text.RegularExpressions.Regex.Replace(listOfLines[i], @"[^\w\.\s@-]", "");                      //чистим TITLE непонятно от чего                                               //относятся к темам
                        }
                        if (listOfLines[i].Contains("###TITLE###"))
                        {
                            flagTitle = true;
                        }
                    }


                    //разбираем вопросы(все вопросы начинаются с темы вопроса)
                    if (listOfLines[i].Contains("##theme ") || flagQuestion == true)
                    {
                        if (String.IsNullOrWhiteSpace(listOfLines[i]))
                        {
                            flagQuestion = false;
                        }

                        flagQuestion = true;

                        //создаем элемент класса "Вопрос" и записываем тему вопроса
                        if (listOfLines[i].Contains("##theme "))
                        {
                            TestInfo.questions.Add(new QuestionClass());
                            TestInfo.questions[TestInfo.questions.Count - 1].theme = int.Parse(listOfLines[i].Substring(8));
                        }

                        //записываем вес вопроса
                        if (listOfLines[i].Contains("##score "))
                        {
                            TestInfo.questions[TestInfo.questions.Count - 1].score = listOfLines[i].Substring(8);
                        }

                        //записываем тип вопроса
                        if (listOfLines[i].Contains("##type "))
                        {
                            TestInfo.questions[TestInfo.questions.Count - 1].type = listOfLines[i].Substring(7);
                        }

                        //время, отведенное на вопрос (в мудле этого нет) - не используется
                        //выдираем вопросы
                        if (listOfLines[i].Contains("##time "))
                        {
                            TestInfo.questions[TestInfo.questions.Count - 1].time     = listOfLines[i].Substring(7);
                            TestInfo.questions[TestInfo.questions.Count - 1].question = listOfLines[i + 1].Substring(0);
                        }
                        //записываем ответы
                        if (!String.IsNullOrWhiteSpace(listOfLines[i]) && TestInfo.questions[TestInfo.questions.Count - 1].question != null && (listOfLines[i].Substring(0, 1) == "+" || listOfLines[i].Substring(0, 1) == "-" || listOfLines[i].Substring(0, 1) == "*"))
                        {
                            TestInfo.questions[TestInfo.questions.Count - 1].answers.Add(listOfLines[i]);
                        }
                    }
                }

                //записываем лог ошибок
                if (TestInfo.title == null)
                {
                    Result += "Отсутсвует название теста (TITLE): " + ttesterFileName + "\r\n"; Console.WriteLine("Отсутсвует название теста (TITLE): " + ttesterFileName); Logfile.WriteLine("Отсутсвует название теста (TITLE): " + ttesterFileName);
                }
                if (TestInfo.themes.Count == 0)
                {
                    Result += "Отсутсвует Тема для тестов (THEMES): " + ttesterFileName + "\r\n";  Console.WriteLine("Отсутсвует Тема для тестов (THEMES): " + ttesterFileName); Logfile.WriteLine("Отсутсвует Тема для тестов (THEMES): " + ttesterFileName);
                }
                if (TestInfo.questions.Count == 0)
                {
                    Result += "Отсутсвуют вопросы для обработки в тесте: " + ttesterFileName + "\r\n"; Console.WriteLine("Отсутсвуют вопросы для обработки в тесте: " + ttesterFileName); Logfile.WriteLine("Отсутсвуют вопросы для обработки в тесте: " + ttesterFileName);
                }


                //сортируем экземпляр класса теста по темам(по возрастанию)
                TestInfo.questions.Sort(delegate(QuestionClass q1, QuestionClass q2) {
                    return(q1.theme.CompareTo(q2.theme));
                });


                //пробегаемся по всем вопросам и, в зависимости от типа вопроса, вызываем необходимую функцию генерации xml-элемента

                int  FlagTheme = 0;
                bool flagtemp  = false;

                foreach (var foreachQuestion in TestInfo.questions)
                {
                    // try
                    //  {
                    if (FlagTheme != foreachQuestion.theme)
                    {
                        FlagTheme = foreachQuestion.theme; quizChildrens.Add(questionCategory(TestInfo.themes[foreachQuestion.theme - 1], CheckIsOneFile, TestInfo.title));
                    }

                    switch (foreachQuestion.type)
                    {
                    case "1":
                        //quizChildrens.Add(multiQuestion(foreachQuestion.type, foreachQuestion.score, foreachQuestion.question, foreachQuestion.answers));
                        quizChildrens.Add(singleQuestion(foreachQuestion.score, foreachQuestion.question, foreachQuestion.answers));
                        break;

                    case "2":
                        quizChildrens.Add(multiQuestion(foreachQuestion.score, foreachQuestion.question, foreachQuestion.answers));
                        break;

                    case "3":
                        quizChildrens.Add(openQuestion(foreachQuestion.score, foreachQuestion.question, foreachQuestion.answers));
                        break;

                    case "4":
                        quizChildrens.Add(crossQuestion(foreachQuestion.score, foreachQuestion.question, foreachQuestion.answers));
                        break;

                    default:

                        if (flagtemp == false)
                        {
                            Result += "Вопросы в которые не вошли в тест " + TestInfo.title + "\r\n"; Console.WriteLine("Вопросы в которые не вошли в тест " + TestInfo.title + ":"); flagtemp = true; Logfile.WriteLine("Вопросы в которые не вошли в тест ####" + TestInfo.title + "####:");
                        }

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine(foreachQuestion.question);
                        Logfile.WriteLine("--- " + foreachQuestion.question);
                        Console.ResetColor();
                        break;
                        //   }
                    }

                    /*    catch (Exception)
                     *  {
                     *      Result += "\r\nПри составлении теста возникли ошибки!\r\n";
                     *     Console.WriteLine("При составлении теста возникли ошибки!");
                     *  }
                     */
                }

                //если нужно сохранить тесты в разные файлы
                if (CheckIsOneFile == false)
                {
                    try
                    {
                        quiz.Add(quizChildrens);
                        XMLFile.Add(quiz);
                        //проверяем, создана ли папка, если нет - создаем
                        //добавляем основной xml-узел, сохраняем файл с именем TITLE теста
                        if (Directory.Exists(saveFolder + "Moodle"))
                        {
                            XMLFile.Save(saveFolder + "Moodle\\" + TestInfo.title + ".xml");
                        }
                        else
                        {
                            Directory.CreateDirectory(saveFolder + "Moodle"); XMLFile.Save(saveFolder + "Moodle\\" + TestInfo.title + ".xml");
                        }

                        //очистка quizChildrens
                        foreach (var item in quizChildrens)
                        {
                            item.RemoveAll();
                        }
                        quizChildrens.Clear();
                        //и полностью чистим оставшиеся xml-узлы
                        quiz.RemoveAll();
                        XMLFile.RemoveNodes();
                    }
                    catch (ArgumentException e)
                    {
                        MessageBox.Show("Ошибка в тесте." + TestInfo.title + " Программа завершила свою работу в аварийном режиме! \r\n Техническая информация " + e.Message);
                    }

                    finally
                    {
                        //очистка quizChildrens
                        foreach (var item in quizChildrens)
                        {
                            item.RemoveAll();
                        }
                        quizChildrens.Clear();
                        //и полностью чистим оставшиеся xml-узлы
                        quiz.RemoveAll();
                        XMLFile.RemoveNodes();
                    }
                }
            }

            //если сохраняем всё в один файл
            if (CheckIsOneFile == true)
            {
                try
                {
                    //добавляем узлы
                    quiz.Add(quizChildrens);
                    XMLFile.Add(quiz);

                    //проверяем, создана ли папка, если нет - создаем
                    //добавляем основной xml-узел, сохраняем файл в "Все тесты.xml"
                    if (Directory.Exists(saveFolder + "Moodle"))
                    {
                        XMLFile.Save(saveFolder + "Moodle\\Все тесты.xml");
                    }
                    else
                    {
                        Directory.CreateDirectory(saveFolder + "Moodle"); XMLFile.Save(saveFolder + "Moodle\\Все тесты.xml");
                    }

                    //очистка asd
                    foreach (var item in quizChildrens)
                    {
                        item.RemoveAll();
                    }
                    quizChildrens.Clear();
                }
                catch (ArgumentException e)
                {
                    MessageBox.Show("Ошибка в тесте. Программа завершила свою работу в аварийном режиме! \r\n Техническая информация " + e.Message);
                }
            }


            Logfile.Close();

            Result += "\r\n ########################## \r\n Обработка тестов завершина";
            return(Result);
        }
Example #19
0
 /// <summary>
 /// Runs test for valid cases
 /// </summary>
 /// <param name="nodeType">XElement/XAttribute</param>
 /// <param name="name">name to be tested</param>
 public void RunValidTests(string nodeType, string name)
 {
     XDocument xDocument = new XDocument();
     XElement element = null;
     switch (nodeType)
     {
         case "XElement":
             element = new XElement(name, name);
             xDocument.Add(element);
             IEnumerable<XNode> nodeList = xDocument.Nodes();
             Assert.True(nodeList.Count() == 1, "Failed to create element { " + name + " }");
             xDocument.RemoveNodes();
             break;
         case "XAttribute":
             element = new XElement(name, name);
             XAttribute attribute = new XAttribute(name, name);
             element.Add(attribute);
             xDocument.Add(element);
             XAttribute x = element.Attribute(name);
             Assert.Equal(name, x.Name.LocalName);
             xDocument.RemoveNodes();
             break;
         case "XName":
             XName xName = XName.Get(name, name);
             Assert.Equal(name, xName.LocalName);
             Assert.Equal(name, xName.NamespaceName);
             Assert.Equal(name, xName.Namespace.NamespaceName);
             break;
         default:
             break;
     }
 }
Example #20
0
        public void Document1()
        {
            object[] content = new object[]
            {
                new object[] { new string[] { " ", null, " " }, "  " },
                new object[] { new string[] { " ", " \t" }, new XText("  \t") },
                new object[] { new XText[] { new XText(" "), new XText("\t") }, new XText(" \t") },
                new XDocumentType("root", "", "", ""), new XProcessingInstruction("PI1", ""), new XText("\n"),
                new XText("\t"), new XText("       "), new XProcessingInstruction("PI1", ""), new XElement("myroot"),
                new XProcessingInstruction("PI2", "click"),
                new object[]
                {
                    new XElement("X", new XAttribute("id", "a1"), new XText("hula")),
                    new XElement("X", new XText("hula"), new XAttribute("id", "a1"))
                },
                new XComment(""),
                new XComment("comment"),
            };

            foreach (object[] objs in content.NonRecursiveVariations(4))
            {
                XDocument doc1 = null;
                XDocument doc2 = null;
                try
                {
                    object[] o1 = ExpandAndProtectTextNodes(objs, 0).ToArray();
                    object[] o2 = ExpandAndProtectTextNodes(objs, 1).ToArray();
                    if (o1.Select(x => new ExpectedValue(false, x)).IsXDocValid()
                        || o2.Select(x => new ExpectedValue(false, x)).IsXDocValid()) continue;
                    doc1 = new XDocument(o1);
                    doc2 = new XDocument(o2);
                    VerifyComparison(true, doc1, doc2);
                }
                catch (InvalidOperationException)
                {
                    // some combination produced from the array are invalid
                    continue;
                }
                finally
                {
                    if (doc1 != null) doc1.RemoveNodes();
                    if (doc2 != null) doc2.RemoveNodes();
                }
            }
        }