Exemple #1
0
        public void Setup()
        {
            var workingDirectory = Environment.CurrentDirectory;
            var projectDirectory = Directory.GetParent(workingDirectory).Parent?.Parent?.FullName;
            var originPath       = $"{projectDirectory}/../Divinity2DETranslator/Assets/english.xml";
            var translationPath  = $"{projectDirectory}/../Divinity2DETranslator/Output/update_fixed.xml";
            var xmlLoader        = new XmlLoader();

            _origin = xmlLoader.Load(originPath)
                      .SelectNodes("contentList/content")
                      .Cast <XmlNode>()
                      .OrderBy(x => x.Attributes["contentuid"].Value)
                      .ToList();

            var allTranslation = xmlLoader.Load(translationPath)
                                 .SelectNodes("contentList/content")
                                 .Cast <XmlNode>()
                                 .OrderBy(x => x.Attributes["contentuid"].Value)
                                 .ToList();

            _translation = allTranslation
                           .Intersect(_origin, new TranslationNodeComparer())
                           .OrderBy(x => x.Attributes["contentuid"].Value)
                           .ToList();
        }
        private void ClickModify(object sender, EventArgs arg)
        {
            FormParamNew form = new FormParamNew();

            form.Entity = this.myGridView1.FindFirstSelect <Param>();
            form.ShowDialog();
            xmlBll.Load();
            this.myGridView1.LoadData(this.xmlBll.ActionList, base.ignoreFields);
        }
Exemple #3
0
 private void LoadGuiXml(string filename)
 {
     try
     {
         _gui.Clear();
         _guiLoader.Load(filename, _gui.Desktop);
         _filename = filename;
     }
     catch (Exception e)
     {
         StaticConsole.Console.AddLine(string.Format("Failed to load `{0}`", filename));
         StaticConsole.Console.AddException(e);
     }
 }
        private void LoadXmlComponents(ILoggerFactory loggerFactory, string[] directories, SearchOption searchOption, XmlLoader xmlLoader)
        {
            var logger = loggerFactory.CreateLogger <DirectoryComponentDescriptionLookup>();

            foreach (string location in directories)
            {
                foreach (string file in Directory.GetFiles(location, "*.xml", searchOption))
                {
                    using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        if (xmlLoader.Load(fs, loggerFactory.CreateLogger <XmlLoader>(), out var description))
                        {
                            description.Metadata.Location = ComponentDescriptionMetadata.LocationType.Installed;
                            description.Source            = new ComponentDescriptionSource(file);

                            foreach (var type in description.GetComponentTypes())
                            {
                                internalLookup.AddDescription(type, description);
                            }
                        }
                        else
                        {
                            logger.LogError($"Failed to load {file}");
                        }
                    }
                }
            }
        }
        public void XmlValidTest()
        {
            var xmlLoader = new XmlLoader();
            var xml = xmlLoader.Load("http://www.ad.nl/home/rss.xml");

            Assert.IsNotNull(xml);
        }
        public void XmlInvalidTypeTest()
        {
            var xmlLoader = new XmlLoader();
            var xml = xmlLoader.Load("http://jsonplaceholder.typicode.com/posts");

            Assert.IsNull(xml);
        }
        public CompileResult CompileOne(string inputFile, PreviewGenerationOptions previewOptions, IDictionary <IOutputGenerator, string> formats)
        {
            logger.LogInformation(inputFile);

            var loader = new XmlLoader();

            using (var fs = File.OpenRead(inputFile))
            {
                if (!loader.Load(fs, logger, out var description))
                {
                    Environment.Exit(1);
                }

                var outputs = Generate(fs, description, Path.GetFileNameWithoutExtension(inputFile), formats, previewOptions);

                return(new CompileResult(description.Metadata.Author,
                                         description.ComponentName,
                                         description.Metadata.GUID,
                                         true,
                                         description.Metadata.AdditionalInformation,
                                         inputFile,
                                         description.Metadata.Entries.ToImmutableDictionary(),
                                         outputs.ToImmutableDictionary()));
            }
        }
Exemple #8
0
        public static void LoadCombatState()
        {
            try
            {
                CombatState state = XmlLoader <CombatState> .Load("CombatState.xml", true);

                if (state != null)
                {
                    _CombatState.Copy(state);
                    _CombatState.SortCombatList(false, false, true);

                    _CombatState.FixInitiativeLinksList(new List <Character>(_CombatState.Characters));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Failure loading combat state: " + ex.ToString());
            }

            if (_CombatState == null)
            {
                _CombatState = new CombatState();
            }
            _CombatState.CharacterAdded   += Handle_CombatStateCharacterAdded;
            _CombatState.CharacterRemoved += Handle_CombatStateCharacterRemoved;
        }
Exemple #9
0
        public IManifestEntry CompileOne(string inputFile, PreviewGenerationOptions previewOptions, bool allConfigurations, IDictionary <IOutputGenerator, string> formats)
        {
            logger.LogInformation(inputFile);

            var loader = new XmlLoader();

            using (var fs = File.OpenRead(inputFile))
            {
                if (!loader.Load(fs, logger, out var description))
                {
                    Environment.Exit(1);
                }

                var baseName = Path.GetFileNameWithoutExtension(inputFile);
                var outputs  = outputRunner.Generate(fs, description, null, baseName, formats, previewOptions, SourceFileType.ComponentDescription).ToList();

                Dictionary <string, IReadOnlyDictionary <string, string> > configurationOutputs = new Dictionary <string, IReadOnlyDictionary <string, string> >();
                if (allConfigurations)
                {
                    foreach (var configuration in description.Metadata.Configurations)
                    {
                        var renderOptions = new PreviewGenerationOptions
                        {
                            Center        = previewOptions.Center,
                            Crop          = previewOptions.Crop,
                            DebugLayout   = previewOptions.DebugLayout,
                            Width         = previewOptions.Width,
                            Height        = previewOptions.Height,
                            Horizontal    = previewOptions.Horizontal,
                            Size          = previewOptions.Size,
                            Configuration = configuration.Name,
                        };

                        var configurationOutput = outputRunner.Generate(fs, description, configuration, baseName, formats, renderOptions, SourceFileType.ComponentDescriptionConfiguration);
                        configurationOutputs[configuration.Name] = configurationOutput.ToImmutableDictionary();
                    }
                }

                var metadata = description.Metadata.Entries.ToDictionary(x => x.Key, x => x.Value);
                var svgIcon  = GetSvgIconPath(Path.GetDirectoryName(inputFile), description);
                if (svgIcon != null)
                {
                    metadata["org.circuit-diagram.icon-svg"] = svgIcon;
                }

                return(new ComponentDescriptionManifestEntry
                {
                    Author = description.Metadata.Author,
                    ComponentName = description.ComponentName,
                    ComponentGuid = description.Metadata.GUID,
                    Success = true,
                    Description = description.Metadata.AdditionalInformation,
                    Version = description.Metadata.Version.ToString(),
                    InputFile = CleanPath(inputFile),
                    Metadata = metadata,
                    OutputFiles = outputs.ToImmutableDictionary(),
                    ConfigurationOutputFiles = configurationOutputs,
                });
            }
        }
Exemple #10
0
        static void Testing()
        {
            XmlLayer rootLayer = XmlLoader.Load(FILE_TEST);

            XmlLayer newLayer = rootLayer.GoTo("Child", "InnerChild");
            XmlLayer layer    = XmlLayer.CreateRootLayer(FILE_TEST);

            XmlLayer serverConfigRootLayer = XmlLayer.CreateRootLayer(FILE_SERVER_CONFIG);
            XmlLayer consoleFilterLayer    = serverConfigRootLayer.GoTo("Logging", "Console", "Filters");
            XmlLayer jsonFilterLayer       = serverConfigRootLayer.GoTo("Logging", "Json", "Filters");

            Extraction consoleExtraction = Extraction.OnMany((() => new List <string>()),
                                                             (list, data) => list.Add($"From: {data[0].Source}. {data[0].Data}"),
                                                             (list =>
            {
                foreach (string filter in list)
                {
                    Console.WriteLine(filter);
                }
            }))
                                           .OnOne(data => Console.WriteLine($"One Filter was found, {data[0].Source}. {data[0].Data}"))
                                           .OnNone((() => Console.WriteLine("No filters detected.")));

            consoleFilterLayer.ExtractIntoFromElements(consoleExtraction);

            ExtractionRaw raw = ExtractionRaw.OnOne(data => Console.WriteLine($"From {data[0].Source}. {data[0].Data}"))
                                .OnNone(() => Console.WriteLine("No raw data found."));

            serverConfigRootLayer.ExtractIntoFromRaw(raw, "General.Port");

            layer.Dispose();

            layer = XmlLoader.Load(FILE_TEST);
            layer = layer.CreateRootLayer();
        }
Exemple #11
0
 public void TestMethod1()
 {
     var test5 = JsonLoader.Load <dynamic>("json1.json");
     var test1 = XmlLoader.Load <Test>("XMLFile1.xml");
     var test2 = XmlLoader.Load <XElement>("XMLFile1.xml");
     //var test3 = XmlLoader.Load<object[]>("XMLFile1.xml");
     var test4 = Conv(test2);
 }
Exemple #12
0
        public void TranspileElementsTest(string xml)
        {
            XPathNodeIterator nodes = XmlLoader.Load(xml);

            var commands = Transpilator.TranspileElements(nodes);

            Assert.IsType <List <Command> >(commands);
            Assert.NotNull(commands);
            Assert.True(commands.Count > 0);
        }
        public void LoadTest(string xml, int equalExpected, string firstNodeNotNull, int equalExpected_b, string equalNodesAtuals_b, string secondNodeNotNull, string textExpected_c, string equalNodeAtual_c)
        {
            var result = XmlLoader.Load(xml);

            Assert.Equal(equalExpected, result.Current.SelectChildren(XPathNodeType.All).Count);
            Assert.NotNull(result.Current.SelectSingleNode(firstNodeNotNull));
            Assert.Equal(equalExpected_b, result.Current.Select(equalNodesAtuals_b).Count);

            Assert.NotNull(result.Current.SelectSingleNode(secondNodeNotNull));
            Assert.Equal(textExpected_c, result.Current.SelectSingleNode(equalNodeAtual_c).Value);
        }
        //+-----------------------------------------------------------------------------
        //
        //  Function:  LoadDocument
        //
        //------------------------------------------------------------------------------

        private static XmlDocument LoadDocument(string xmlFile, string schemaFile)
        {
            XmlDocument document = XmlLoader.Load(xmlFile, schemaFile);

            if (document == null)
            {
                throw new ApplicationException(String.Format("Could not load data file."));
            }

            return(document);
        }
Exemple #15
0
        private static void StartApp(string inputPath, string outputPath)
        {
            var loader   = new XmlLoader();
            var document = loader.Load(inputPath);
            var fixer    = new UpdateMistakesFixer(document);

            Console.WriteLine("Fixing update translation mistakes");
            fixer.FixAll();

            loader.Save(outputPath, document);
            Console.WriteLine("Finished...");
        }
Exemple #16
0
 /// <summary>
 /// Loads a component description from the stream and adds it to the component descriptions store.
 /// </summary>
 /// <param name="stream">The stream to load from.</param>
 /// <param name="type">The type to find within the description.</param>
 /// <returns>A configuration with the loaded component description if it was available, null if it could not be loaded.</returns>
 private static ComponentIdentifier LoadDescription(EmbedComponentData data, IOComponentType type)
 {
     if (data.ContentType == IO.CDDX.ContentTypeNames.BinaryComponent)
     {
         // Binary component
         var reader = new CircuitDiagram.IO.Descriptions.BinaryDescriptionReader();
         if (reader.Read(data.Stream))
         {
             var descriptions = reader.ComponentDescriptions;
             if (descriptions.Count > 0)
             {
                 return(FindIdentifier(type, descriptions[0]));
             }
             else
             {
                 return(null);
             }
         }
         else
         {
             // Load failed
             return(null);
         }
     }
     else if (data.ContentType == "application/xml")
     {
         // XML component
         XmlLoader loader = new XmlLoader();
         loader.Load(data.Stream);
         if (loader.LoadErrors.Count() == 0)
         {
             var descriptions = loader.GetDescriptions();
             if (descriptions.Length > 0)
             {
                 return(FindIdentifier(type, descriptions[0]));
             }
             else
             {
                 return(null);
             }
         }
         else
         {
             // Load failed
             return(null);
         }
     }
     else
     {
         // Unknown type
         return(null);
     }
 }
        private static async Task StartApp(string inputPath, string outputPath, string manualTranslationsPath)
        {
            var loader                    = new XmlLoader();
            var document                  = loader.Load(inputPath);
            var manualTranslations        = loader.Load(manualTranslationsPath);
            var translator                = new Translator();
            var localizationManager       = new DivinityLocalizationTranslator(translator, document);
            var manualTranslationsApplier = new ManualTranslationsApplier(translator, manualTranslations, document);
            var fixer = new GeneralTranslationMistakesFixer(document);

            Console.WriteLine("Translating...");
            await localizationManager.TranslateAll(() => loader.Save(outputPath, document));

            Console.WriteLine("Applying manual translations...");
            await manualTranslationsApplier.Apply(() => loader.Save(outputPath, document));

            Console.WriteLine("Fixing general translation mistakes");
            fixer.FixAll();

            loader.Save(outputPath, document);
            Console.WriteLine("Finished...");
        }
Exemple #18
0
        /// <summary>
        /// Метод загрузки игры.
        /// </summary>
        public override void Load()
        {
            try
            {
                string resfile = @"..\..\res\res.xml"; //XML файл с данными о ресурсах игры
                if (File.Exists(resfile))              //Проверка наличия заданного файла
                {
                    base.Load();

                    loader = new XmlLoader(resfile);
                    loader.Load(); //Загрузка ресурсов игры

                    objs.Add(new Background(new Point(0, 0), new Point(-1, 0), new Size(Width, Height),
                                            Image.FromFile(@"..\..\res\img\background.jpeg"), Buffer.Graphics, new Size(Width, Height))); //Создание заднего фона

                    for (int i = 0; i < 100; i++)                                                                                         //Добавление в список игровых объектов звезд. Положение, размер и скорость движения звезды выбираются случайным образом в некотором диапазоне
                    {
                        objs.Add(new Star(
                                     new Point(rand.Next(10, Width + 650), rand.Next(0, Height)),                                                //Координаты звезды
                                     new Point(rand.Next(-30, -15), 0),                                                                          //Направление и скорость движения звезды
                                     new Size(rand.Next(3, 10), 0),                                                                              //Размеры звезды
                                     loader.ResList.Where(t => t.resType == "star").OrderBy(arg => Guid.NewGuid()).Take(1).FirstOrDefault().img, //Изображение каждой звезды выбирается случайным образом из загруженных ресурсов
                                     Buffer.Graphics,
                                     new Size(Width, Height),
                                     rand.Next(-2, 2) //Пульсация звезды
                                     ));
                    }

                    PlayerObj = new Player(
                        new Point(10, Height / 2), //Начальные координаты
                        new Point(0, 0),           //Направление и скорость движения
                        new Size(200, 50),         //Размеры
                        Image.FromFile(@"..\..\res\img\ship1.png"),
                        Buffer.Graphics,
                        new Size(Width, Height),
                        100,   //Здоровье
                        20     // Максимальная скорость
                        );
                    objs.Add(PlayerObj);
                }
                else
                {
                    throw new FileNotFoundException();
                }
            }
            catch (Exception ex)
            {
                exp.PutMessage("Game.Load()", ex);
            }
        }
        private static async Task StartApp(string englishPath, string translatedPath, string outputPath)
        {
            Console.WriteLine("Initializing update...");
            var loader                = new XmlLoader();
            var englishDoc            = loader.Load(englishPath);
            var translatedDoc         = loader.Load(translatedPath);
            var needingTranslationDoc = CreateNeedingTranslationOnlyDoc(englishDoc, translatedDoc);
            var translator            = new Translator();
            var localizationManager   = new DivinityLocalizationTranslator(translator, needingTranslationDoc);
            var fixer = new UpdateMistakesFixer(needingTranslationDoc);

            Console.WriteLine("Translating new lines...");
            await localizationManager.TranslateAll(() => {});

            Console.WriteLine("Fixing general translation mistakes");
            fixer.FixAll();

            Console.WriteLine("Building final artifact...");
            var finalArtifact = CreateDocumentWithUnionOfTwo(needingTranslationDoc, translatedDoc);

            loader.Save(outputPath, finalArtifact);
            Console.WriteLine("Finished...");
        }
Exemple #20
0
        private static bool CompileComponent(string inputPath, CompileOptions compileOptions)
        {
            List <ComponentDescription> componentDescriptions = new List <ComponentDescription>();
            List <BinaryResource>       binaryResources       = new List <BinaryResource>();

            XmlLoader loader = new XmlLoader();

            loader.Load(new FileStream(inputPath, FileMode.Open));

            if (loader.LoadErrors.Count(e => e.Category == LoadErrorCategory.Error) > 0)
            {
                foreach (var error in loader.LoadErrors)
                {
                    Console.WriteLine(error.ToString());
                }
                return(false);
            }

            ComponentDescription description = loader.GetDescriptions()[0];

            description.ID = "C0";
            componentDescriptions.Add(description);

            SetIcons(compileOptions, description);

            string output = compileOptions.Output;

            if (!Path.HasExtension(output))
            {
                if (!Directory.Exists(output))
                {
                    Directory.CreateDirectory(output);
                }
                output += "\\" + description.ComponentName.ToLowerInvariant() + ".cdcom";
            }
            FileStream stream = new FileStream(output, FileMode.Create, FileAccess.Write);

            X509Certificate2 certificate = SelectCertificate(compileOptions);

            CircuitDiagram.IO.BinaryWriter.BinaryWriterSettings settings = new CircuitDiagram.IO.BinaryWriter.BinaryWriterSettings();
            settings.Certificate = certificate;
            CircuitDiagram.IO.BinaryWriter writer = new CircuitDiagram.IO.BinaryWriter(stream, settings);
            writer.Descriptions.AddRange(componentDescriptions);
            writer.Resources.AddRange(binaryResources);
            writer.Write();
            stream.Flush();

            return(true);
        }
Exemple #21
0
        public void Run(CompileContext context)
        {
            XmlLoader loader = new XmlLoader();

            // TODO: Add errors to context
            if (!loader.Load(context.Input, out var description))
            {
                return;
            }

            // The component XML format doesn't provide an ID, so make one now
            description.ID = "C0";

            context.Description = description;
        }
Exemple #22
0
        private void ClickDelete(object sender, EventArgs arg)
        {
            Channel entity = this.myGridView1.FindFirstSelect <Channel>();

            if (entity != null)
            {
                if (MessageBox.Show("是否删除数据?", "确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    xmlBll.ChannelList.Remove(entity);
                    xmlBll.SaveChannels();
                    xmlBll.Load();
                    this.myGridView1.LoadData(this.xmlBll.ChannelList, base.ignoreFields);
                }
            }
        }
Exemple #23
0
        public static int Run(Options options)
        {
            if (!File.Exists(options.Input))
            {
                Console.WriteLine("Input file does not exist.");
                return(1);
            }

            var loader = new XmlLoader();

            loader.UseDefinitions();

            using (var fs = File.OpenRead(options.Input))
            {
                if (!loader.Load(fs, out var description))
                {
                    Console.WriteLine("Component is invalid.");
                    return(1);
                }

                var outline = new ComponentOutline
                {
                    Configurations = description.Metadata.Configurations.Select(x => new OutlineConfiguration
                    {
                        Name = x.Name,
                    }).ToList(),
                    Properties = description.Properties.Select(x => new OutlineProperty
                    {
                        Name        = x.Name,
                        Type        = x.Type.ToString(),
                        EnumOptions = x.EnumOptions,
                    }).ToList(),
                };

                using (var output = Console.OpenStandardOutput())
                {
                    var writer      = new Utf8JsonWriter(output);
                    var jsonOptions = new JsonSerializerOptions
                    {
                        WriteIndented        = true,
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    };
                    JsonSerializer.Serialize(writer, outline, jsonOptions);
                }
            }

            return(0);
        }
Exemple #24
0
        public override bool Execute()
        {
            var tobascoFilePaths      = TobascoFiles?.Select(x => x.ItemSpec).ToList() ?? new List <string>();
            var tobascoConfigFilePath = TobascoConfigFile?.ItemSpec ?? string.Empty;

            var tobascoConfig = XmlLoader.Load <EntityInformation>(tobascoConfigFilePath);

            new DapperCodeGenerator().ResolveDapperCodeFiles(new CustomBuilderResolver(), tobascoConfig, tobascoFilePaths, Log);

            GeneratedFiles = new List <ITaskItem> {
                new TaskItem {
                    ItemSpec = "Test"
                }
            }.ToArray();
            return(true);
        }
    public Scheme LoadScheme(string schemeName)
    {
        Scheme             scheme = new Scheme();
        List <XmlDocument> xmls   = new List <XmlDocument>();

        foreach (AppPath schemePath in GetSchemePaths(schemeName))
        {
            XmlDocument xml = xmlLoader.Load(schemePath.GetExisted(), true);
            if (xml != null)
            {
                xmls.Add(xml);
            }
        }
        scheme.ParseXml(xmls);
        return(scheme);
    }
Exemple #26
0
        private void InitUI()
        {
            xmlBll.Load();
            this.comboBox1.DataSource    = xmlBll.ActionList;
            this.comboBox1.DisplayMember = "Name";

            this.comboBox2.DataSource    = xmlBll.ParamsList;
            this.comboBox2.DisplayMember = "Name";

            this.comboBox3.DataSource    = xmlBll.ChannelList;
            this.comboBox3.DisplayMember = "AgentName";
            if (this.ScriptEntity != null)
            {
                this.comboBox4.DataSource    = this.ScriptEntity.StepList;
                this.comboBox4.DisplayMember = "Name";
            }
        }
Exemple #27
0
        protected override void LoadParser(ref XmlDocument model, XmlDocument template)
        {
            string hcPath = HcInputPath;

            File.Delete(hcPath);             // In case we don't produce one successfully, don't keep an old one.
            // Check for errors that will prevent the transformations working.
            foreach (var affix in m_cache.ServiceLocator.GetInstance <IMoAffixAllomorphRepository>().AllInstances())
            {
                string form = affix.Form.VernacularDefaultWritingSystem.Text;
                if (string.IsNullOrEmpty(form) || !form.Contains("["))
                {
                    continue;
                }
                string environment = "/_" + form;
                // A form containing a reduplication expression should look like an environment
                var validator = new PhonEnvRecognizer(
                    m_cache.LangProject.PhonologicalDataOA.AllPhonemes().ToArray(),
                    m_cache.LangProject.PhonologicalDataOA.AllNaturalClassAbbrs().ToArray());
                if (!validator.Recognize(environment))
                {
                    string msg = string.Format(ParserCoreStrings.ksHermitCrabReduplicationProblem, form,
                                               validator.ErrorMessage);
                    m_cache.ThreadHelper.Invoke(() =>                     // We may be running in a background thread
                    {
                        MessageBox.Show(Form.ActiveForm, msg, ParserCoreStrings.ksBadAffixForm,
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    });
                    m_loader.Reset();           // make sure nothing thinks it is in a useful state
                    return;                     // We can't load the parser, hopefully our caller will realize we failed.
                }
            }

            var transformer = new M3ToHCTransformer(m_projectName, m_taskUpdateHandler);

            transformer.MakeHCFiles(ref model);

            m_patr.LoadGrammarFile(HcGrammarPath);
            m_loader.Load(hcPath);

            XmlNode delReappsNode = model.SelectSingleNode("/M3Dump/ParserParameters/HC/DelReapps");

            if (delReappsNode != null)
            {
                m_loader.CurrentMorpher.DelReapplications = Convert.ToInt32(delReappsNode.InnerText);
            }
        }
Exemple #28
0
        static CompileResult Run(string inputFile,
                                 IResourceProvider resourceProvider,
                                 PreviewGenerationOptions previewOptions,
                                 IDictionary <IOutputGenerator, string> formats)
        {
            Log.LogInformation(inputFile);

            var loader = new XmlLoader();

            using (var fs = File.OpenRead(inputFile))
            {
                loader.Load(fs);

                if (loader.LoadErrors.Any())
                {
                    foreach (var error in loader.LoadErrors)
                    {
                        switch (error.Category)
                        {
                        case LoadErrorCategory.Error:
                            Log.LogError(error.Message);
                            break;
                        }
                    }

                    if (loader.LoadErrors.Any(x => x.Category == LoadErrorCategory.Error))
                    {
                        Environment.Exit(1);
                    }
                }

                var description = loader.GetDescriptions()[0];

                var outputs = Generate(fs, description, Path.GetFileNameWithoutExtension(inputFile), resourceProvider, formats, previewOptions);

                return(new CompileResult(description.Metadata.Author,
                                         description.ComponentName,
                                         description.Metadata.GUID,
                                         true,
                                         description.Metadata.AdditionalInformation,
                                         inputFile,
                                         description.Metadata.Entries.ToImmutableDictionary(),
                                         outputs.ToImmutableDictionary()));
            }
        }
        void ShowImportDialog(String filename)
        {
            try
            {
                ExportData data = XmlLoader <ExportData> .Load(filename);


                ImportExportDialog ied = new ImportExportDialog(this, data, true);
                ied.Show();
                ied.DialogComplete += (sender, e) =>
                {
                    foreach (Monster m in e.Data.Monsters)
                    {
                        m.DBLoaderID = 0;
                        MonsterDB.DB.AddMonster(m);
                        Monster.Monsters.Add(m);
                    }
                    foreach (Spell s in e.Data.Spells)
                    {
                        s.DBLoaderID = 0;
                        Spell.AddCustomSpell(s);
                    }
                    foreach (Feat s in e.Data.Feats)
                    {
                        s.DBLoaderID = 0;
                        Feat.AddCustomFeat(s);
                    }
                    foreach (Condition s in e.Data.Conditions)
                    {
                        Condition.CustomConditions.Add(s);
                    }
                    if (e.Data.Conditions.Count > 0)
                    {
                        Condition.SaveCustomConditions();
                    }

                    RefreshForImport(e.Data);
                };
            }
            catch (Exception ex)
            {
                DebugLogger.WriteLine(ex.ToString());
            }
        }
Exemple #30
0
        protected override void LoadParser(ref XmlDocument model, XmlDocument template, TaskReport task, ParserScheduler.NeedsUpdate eNeedsUpdate)
        {
            try
            {
                M3ToHCTransformer transformer = new M3ToHCTransformer(m_database);
                transformer.MakeHCFiles(ref model, task, eNeedsUpdate);
            }
            catch (Exception error)
            {
                if (error.GetType() == Type.GetType("System.Threading.ThreadInterruptedException") ||
                    error.GetType() == Type.GetType("System.Threading.ThreadAbortException"))
                {
                    throw error;
                }

                task.EncounteredError(null);                    // Don't want to show message box in addition to yellow crash box!
                throw new ApplicationException("Error while generating files for the Parser.", error);
            }

            try
            {
                string gramPath = Path.Combine(m_outputDirectory, m_database + "gram.txt");
                m_patr.LoadGrammarFile(gramPath);
                string hcPath = Path.Combine(m_outputDirectory, m_database + "HCInput.xml");
                m_loader.Load(hcPath);

                XmlNode delReappsNode = model.SelectSingleNode("/M3Dump/ParserParameters/HC/DelReapps");
                if (delReappsNode != null)
                {
                    m_loader.CurrentMorpher.DelReapplications = Convert.ToInt32(delReappsNode.InnerText);
                }
            }
            catch (Exception error)
            {
                if (error.GetType() == Type.GetType("System.Threading.ThreadInterruptedException") ||
                    error.GetType() == Type.GetType("System.Threading.ThreadAbortException"))
                {
                    throw error;
                }
                ApplicationException e = new ApplicationException("Error while loading the Parser.", error);
                task.EncounteredError(null);                    // Don't want to show message box in addition to yellow crash box!
                throw e;
            }
        }
        public void Run(CompileContext context)
        {
            XmlLoader loader = new XmlLoader();

            loader.Load(context.Input);

            context.Errors.AddRange(loader.LoadErrors.Select(e => new CompileError(e)));
            if (loader.LoadErrors.Count(e => e.Category == LoadErrorCategory.Error) > 0)
            {
                return;
            }

            var description = loader.GetDescriptions()[0];

            // The component XML format doesn't provide an ID, so make one now
            description.ID = "C0";

            context.Description = description;
        }
Exemple #32
0
        private void LoadCombatState()
        {
            CombatState state = XmlLoader <CombatState> .Load("CombatState.xml", true);

            if (state == null)
            {
                _CombatState = new CombatState();
            }
            else
            {
                _CombatState = state;
            }
            _CombatState.SortCombatList(false, false, true);
            _CombatState.FixInitiativeLinksList(new List <Character>(_CombatState.Characters));

            ISharedPreferences sp = Activity.GetSharedPreferences("CombatManager", 0);

            CombatState.use3d6 = sp.GetBoolean("use3d6", false);
        }
 public static HelpDocument Load(string fileName)
 {
     var xmlLoader = new XmlLoader();
     xmlLoader.SetXmlSchemaFromResource("EPuzzleHelpDocument.xsd");
     return Create(xmlLoader.Load(fileName));
 }