コード例 #1
1
        public string GetXml(bool validate)
        {
            XNamespace ns = "http://sd.ic.gc.ca/SLDR_Schema_Definition_en";

            var spectrum_licences = getLicences();

            XDocument doc = new XDocument(new XElement("spectrum_licence_data_registry", spectrum_licences));

            foreach (XElement e in doc.Root.DescendantsAndSelf())
            {
                if (e.Name.Namespace == "")
                    e.Name = ns + e.Name.LocalName;
            }

            var errors = new StringBuilder();

            if (validate)
            {
                XmlSchemaSet set = new XmlSchemaSet();
                var schema = getMainSchema();
                set.Add(null, schema);

                doc.Validate(set, (sender, args) => { errors.AppendLine(args.Message); });
            }

            //return errors.Length > 0 ? errors.ToString() : doc.ToString();
            var  result = errors.Length > 0 ? "Validation Errors: " + errors.ToString() : getDocumentAsString(doc);
            return result;
        }
コード例 #2
0
        //------------------------------------------------------------------------------------------------
        //Xmlデータを初期化する
        //------------------------------------------------------------------------------------------------
        public void XmlAllDelete()
        {
            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);

            //Xmlファイル内を検索
            //ぜんぶけす
            try
            {
                var query = from y in XmlDoc.Descendants("Chord")
                            select y;

                foreach (XElement item in query.ToList())
                {
                    item.Remove();
                    XmlDoc.Save(createConfigXML.CurrentPath_database());
                }
            }
            catch (Exception ex)
            {
            }

            MessageBox.Show("更新が完了しました。",
                            "Infomation", MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
        }
コード例 #3
0
ファイル: XMLProcess.cs プロジェクト: thachgiasoft/qAustfeed
    public void Update(string fileName, MathRule mathRule)
    {
        System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(fileName);
        var node = (from t in document.Descendants("Column")
                    where t.Element("DataBase").Value == mathRule.ColumnInDB
                    select t).FirstOrDefault();

        // check exist element excel
        string[]      arr  = node.Element("Excel").Value.Split(';');
        List <string> list = new List <string>();

        for (int i = 0; i < arr.Length; i++)
        {
            list.Add(arr[i].Trim());
        }
        if (!list.Contains(mathRule.ColumnInExcel.Trim()))
        {
            node.Element("Excel").Value += ";" + mathRule.ColumnInExcel;
        }
        // end check
        //node.Attribute("AllowBlank").Value = mathRule.AllowBlank;
        //node.Attribute("DataType").Value = mathRule.DataType;
        //node.Attribute("DisplayOnGrid").Value = mathRule.DisplayOnGrid.ToString();
        //if (!string.IsNullOrEmpty(mathRule.DefaultValue))
        //    node.Attribute("DefaultValue").Value = mathRule.DefaultValue;
        //else
        //    node.Attribute("DefaultValue").Value = "";
        document.Save(fileName);
    }
コード例 #4
0
ファイル: LocalConfigService.cs プロジェクト: RyanFu/shoperp
        static LocalConfigService()
        {
            if (xDoc != null)
            {
                return;
            }
            if (System.IO.File.Exists(CONFIG_PATH) == false)
            {
                try
                {
                    System.IO.File.WriteAllText(CONFIG_PATH, DEFAULT_CONFIG_CONTENT);
                }
                catch (Exception ex)
                {
                    Logger.Log("生成默认配置文件出错", ex);
                    throw new Exception("生成默认配置文件出错");
                }
            }

            xDoc = XDocument.Load(CONFIG_PATH);

            if (xDoc.Root.Element(SystemNames.CONFIG_WEB_IMAGE_DIR) == null)
            {
                UpdateValue(SystemNames.CONFIG_WEB_IMAGE_DIR, @"\\host-bjc\images");
            }
        }
コード例 #5
0
        //------------------------------------------------------------------------------------------------
        //DataGridviewにXmlデータを反映する(起動時)
        //------------------------------------------------------------------------------------------------
        public void InitDataSet()
        {
            XElement query;

            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);


            //Xmlファイル内を検索
            for (int i = 0; i < XmlDoc.Descendants("Chord").Count(); i++)
            {
                //ServiceNameをチェック
                try
                {
                    query = (from y in XmlDoc.Descendants("Chord")
                             where y.Attribute("ID").Value == Convert.ToString(i + 1)
                             select y).Single();

                    dataGridView1.Rows.Add();
                    dataGridView1.Rows[i].Cells[0].Value = query.Attribute("ID").Value;
                    dataGridView1.Rows[i].Cells[1].Value = query.Element("Root").Value;
                    dataGridView1.Rows[i].Cells[2].Value = query.Element("Degree").Value;
                    dataGridView1.Rows[i].Cells[3].Value = query.Element("Position1").Value;
                    dataGridView1.Rows[i].Cells[4].Value = query.Element("Position2").Value;
                    dataGridView1.Rows[i].Cells[5].Value = query.Element("Position3").Value;
                    dataGridView1.Rows[i].Cells[6].Value = query.Element("Position4").Value;
                    dataGridView1.Rows[i].Cells[7].Value = query.Element("BarreFlg").Value;
                    dataGridView1.Rows[i].Cells[8].Value = query.Element("Barre").Value;
                    dataGridView1.Rows[i].Cells[9].Value = query.Element("High").Value;
                }
                catch (Exception ex)
                {
                }
            }
        }
コード例 #6
0
ファイル: AssetManagement.cs プロジェクト: EmiiFont/Azureoid
        public static X509Certificate2 GetCertificate(XDocument xdoc)
        {
            var profile = xdoc.Descendants("PublishProfile").Single();
            var managementCertbase64String = profile.Attribute("ManagementCertificate").Value;

            return new X509Certificate2(Convert.FromBase64String(managementCertbase64String));
        }
コード例 #7
0
ファイル: XmlLoggerFacts.cs プロジェクト: hackmp/kudu
        public void XmlLoggerBasicTest()
        {
            var path = @"x:\deployments\1234\log.xml";
            var fileSystem = new Mock<IFileSystem>();
            var file = new Mock<FileBase>();
            var id = Guid.NewGuid().ToString();
            var message = Guid.NewGuid().ToString();
            var doc = new XDocument(new XElement("entries", 
                new XElement("entry",
                    new XAttribute("time", "2013-12-08T01:58:24.0247841Z"),
                    new XAttribute("id", id),
                    new XAttribute("type", "0"),
                    new XElement("message", message)
                )
            ));
            var mem = new MemoryStream();
            doc.Save(mem);

            // Setup
            fileSystem.SetupGet(f => f.File)
                      .Returns(file.Object);
            file.Setup(f => f.Exists(path))
                .Returns(true);
            file.Setup(f => f.OpenRead(path))
                .Returns(() => { mem.Position = 0; return mem; });

            // Test
            var logger = new XmlLogger(fileSystem.Object, path, Mock.Of<IAnalytics>());
            var entries = logger.GetLogEntries();

            // Assert
            Assert.Equal(1, entries.Count());
            Assert.Equal(id, entries.First().Id);
            Assert.Equal(message, entries.First().Message);
        }
        public void Initialize()
        {
            Motor.Instance.Configuration = new Configuration.DefaultConfiguration();
            ChromeDriverService service = ChromeDriverService.CreateDefaultService();

            service.HideCommandPromptWindow = true;

            var options = new ChromeOptions();

            //options.AddArgument("--window-position=-32000,-32000");
            options.LeaveBrowserRunning = false;

            this._driver = new ChromeDriver(service, options);
            this._driver.Manage().Window.Maximize();

            if (!string.IsNullOrEmpty(Properties.Settings.Default.XML_PATH))
            {
                this._document = XDocument.Load(Properties.Settings.Default.XML_PATH);
            }
            else
            {
                this._document = XDocument.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream("Boissonnot.Framework.Tests.UnitTester.Selenium.TestPageList.xml"));
            }

            Motor.Instance.Configuration.Load(this._document);
        }
コード例 #9
0
        public SXL.XDocument CreateDocument()
        {
            var doc  = new SXL.XDocument();
            var root = new SXL.XElement("methodCall");

            doc.Add(root);

            var method = new SXL.XElement("methodName");

            root.Add(method);

            method.Add(this.Name);

            var params_el = new SXL.XElement("params");

            root.Add(params_el);

            foreach (var p in this.Parameters)
            {
                var param_el = new SXL.XElement("param");
                params_el.Add(param_el);

                p.AddXmlElement(param_el);
            }

            return(doc);
        }
コード例 #10
0
 public static XDocument GetXDocument(this OpenXmlPart part)
 {
     try
     {
         XDocument partXDocument = part.Annotation<XDocument>();
         if (partXDocument != null)
             return partXDocument;
         using (Stream partStream = part.GetStream())
         {
             if (partStream.Length == 0)
             {
                 partXDocument = new XDocument();
                 partXDocument.Declaration = new XDeclaration("1.0", "UTF-8", "yes");
             }
             else
                 using (XmlReader partXmlReader = XmlReader.Create(partStream))
                     partXDocument = XDocument.Load(partXmlReader);
         }
         part.AddAnnotation(partXDocument);
         return partXDocument;
     }
     catch (Exception e)
     {
         throw e;
     }
 }
コード例 #11
0
ファイル: ParseLessons.cs プロジェクト: Mexahoid/CSF
 //Возвращает список текстов класса если DataType = text и дат если date
 public static List<string> DelParse(XDocument Lessons, string Class, string LessonType, string DataType)
 {
     List<string> Data = new List<string>();
       foreach (string Text in Lessons.Descendants(Class).Elements(LessonType).Elements(DataType)) //Можно получить Class и lesson
     Data.Add(TextDeriver(Text));  //Мы получаем одну строку, поэтому однострочный дерайвер
       return Data;
 }
コード例 #12
0
        public static void Save(string path)
        {
            var document = new XDocument();
            var root = new XElement("PrettyCheckoutDatabase", new XAttribute("Version", DataReaderFileVersion));

            foreach (var product in Program.Environment.Products)
            {
                var element = new XElement("Product");
                element.Add(new XAttribute("ID", product.Index));
                element.Add(new XAttribute("Name", product.Name));
                element.Add(new XAttribute("Price", product.Price));
                element.Add(new XAttribute("PriceN", product.PriceN));
                element.Add(new XAttribute("Vat", product.Vat));
                element.Add(new XElement("Description", new XCData(product.Description == null ? string.Empty : product.Description)));

                root.Add(element);
            }

            document.Add(root);

            try
            {
                document.Save(path);
            }
            catch (Exception)
            {
                MessageBox.Show("Data file could not be saved - " + path);
            }
        }
コード例 #13
0
 public XDocument GetXDocument()
 {
     List<PortSetting> list = new List<PortSetting>()
     {
         new PortSetting()
         {
             Name ="InputPort",
             Value=""
         },
         new PortSetting()
         {
             Name ="OutputPort",
             Value=""
         },
     };
   
     XDocument xDoc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XComment("System Setting"),
                new XElement("Settings",
                    list.Select(x => (new XElement("Setting",
                                          new XElement("Name", x.Name),
                                          new XElement("Value", x.Value))))
              ));
     return xDoc;
 }
コード例 #14
0
        private void LoadMenuItem_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter     = "XML files (.xml) | *.xml";
            ofd.DefaultExt = ".xml";
            Nullable <bool> result = ofd.ShowDialog();

            if (result == true)
            {
                System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load(ofd.FileName);
                //List<XNode> tempList = xdoc.Root.Elements("Item").Select(el => el.Nodes().ToList()[0]).ToList();
                var res = from myItem in xdoc.Root.Elements("Item")
                          select new Item((string)myItem.Element("ItemName"), (string)myItem.Element("ItemDescription"),
                                          (Category)Enum.Parse(typeof(Category), (string)myItem.Element("ItemCategory")), (double)myItem.Element("ItemPrice"));
                //{
                //    Name = (string)myItem.Element("ItemName"),
                //    Description = (string)myItem.Element("ItemDescription"),
                //    Category = (Category)Enum.Parse(typeof(Category), (string)myItem.Element("ItemCategory")),
                //    Price = (double)myItem.Element("ItemPrice")
                //};
                foreach (var el in res.ToList())
                {
                    itemList.Add(el);
                }
            }
        }
コード例 #15
0
 private static void Project_WixSourceGenerated(System.Xml.Linq.XDocument doc)
 {
     doc.FindAll("Custom")
     .Where(x => x.HasAttribute("Action", "Set_ARPNOMODIFY"))
     .First()
     .SetAttribute("After", "InstallInitialize");
 }
コード例 #16
0
        private async void setimg()
        {
            try
            {
                System.Xml.Linq.XDocument xmlDoc  = XDocument.Load("http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US");
                IEnumerable <string>      strTest = from node in xmlDoc.Descendants("url") select node.Value;
                string strURL       = "http://www.bing.com" + strTest.First();
                Uri    source       = new Uri(strURL);
                var    bitmapImage  = new BitmapImage();
                var    httpClient   = new HttpClient();
                var    httpResponse = await httpClient.GetAsync(source);

                byte[] b = await httpResponse.Content.ReadAsByteArrayAsync();

                using (var stream = new InMemoryRandomAccessStream())
                {
                    using (DataWriter dw = new DataWriter(stream))
                    {
                        dw.WriteBytes(b);
                        await dw.StoreAsync();

                        stream.Seek(0);
                        bitmapImage.SetSource(stream);
                        Image1.Source = bitmapImage;
                        var storageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("CGPA_Bing.jpg", CreationCollisionOption.ReplaceExisting);

                        using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0));
                        }
                    }
                }
            }
            catch (Exception) { readimg(); }
        }
コード例 #17
0
        /// <summary>
        /// Creates the XML data.
        /// </summary>
        /// <param name="dtRow">The dt row.</param>
        /// <returns></returns>
        public int CreateXMLData(DataRow dtRow)
        {
            try
            {
                if (File.Exists(Datacontext.GetInstance().CorporateFavoriteFile))
                {
                    System.Xml.Linq.XDocument resultsDoc = System.Xml.Linq.XDocument.Parse((System.Xml.Linq.XDocument.Load(Datacontext.GetInstance().CorporateFavoriteFile)).ToString());
                    var query = resultsDoc.Root;
                    query.Add(new System.Xml.Linq.XElement("Favorites", (new System.Xml.Linq.XElement("Category", dtRow["Category"].ToString())),
                                                           (new System.Xml.Linq.XElement("DisplayName", dtRow["DisplayName"])),
                                                           (new System.Xml.Linq.XElement("UniqueIdentity", dtRow["UniqueIdentity"])),
                                                           (new System.Xml.Linq.XElement("FirstName", dtRow["FirstName"])),
                                                           (new System.Xml.Linq.XElement("LastName", dtRow["LastName"])),
                                                           (new System.Xml.Linq.XElement("PhoneNumber", dtRow["PhoneNumber"])),
                                                           (new System.Xml.Linq.XElement("EmailAddress", dtRow["EmailAddress"])),
                                                           (new System.Xml.Linq.XElement("Type", dtRow["Type"]))));

                    resultsDoc.Save(Datacontext.GetInstance().CorporateFavoriteFile);
                    return(1);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error in creating favorite XML Data : " + ex.Message.ToString());
            }
            return(0);
        }
コード例 #18
0
        public VersionedModel(XDocument model, string version = null)
        {
            DebugCheck.NotNull(model);

            _model = model;
            _version = version;
        }
コード例 #19
0
        public static void Main()
        {
            var context = new GeographyEntities();
            var countries = context.Countries;

            var countriesQuery = countries
                .Where(c => c.Monasteries.Any())
                .OrderBy(c => c.CountryName)
                .Select(c => new
                {
                    c.CountryName,
                    Monasteries = c.Monasteries
                        .OrderBy(m => m.Name)
                        .Select(m => m.Name)
                });

            // Build the output XML
            var xmlMonasteries = new XElement("monasteries");
            foreach (var country in countriesQuery)
            {
                var xmlCountry = new XElement("country");
                xmlCountry.Add(new XAttribute("name", country.CountryName));

                foreach (var monastery in country.Monasteries)
                {
                    xmlCountry.Add(new XElement("monastery", monastery));
                }

                xmlMonasteries.Add(xmlCountry);
            }
            Console.WriteLine(xmlMonasteries);

            var xmlDoc = new XDocument(xmlMonasteries);
            xmlDoc.Save(@"..\..\monasteries.xml");
        }
コード例 #20
0
ファイル: UtilityController.cs プロジェクト: beardeddev/briar
        public ContentResult SiteMap()
        {
            List<Page> pages = Page.Collection.Find(Page.ActiveScope).ToList();
            List<Post> posts = Post.Collection.Find(Post.ActiveScope)
                .SetSortOrder(Post.DefaultSortByScope)
                .ToList();

            var sitemap = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                new XElement(AppSettings.SiteMapNamespace + "urlset",
                        from p in pages
                        select
                          new XElement(AppSettings.SiteMapNamespace + "url",
                            new XElement(AppSettings.SiteMapNamespace + "loc", string.Format(AppSettings.PageUrlFormat, Request.Url.Host, p.Url)),
                                new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", p.UpdatedOn))
                                ),
                            new XElement("changefreq", "monthly"),
                            new XElement("priority", "0.5"),
                        from p in posts
                        select
                            new XElement(AppSettings.SiteMapNamespace + "url",
                            new XElement(AppSettings.SiteMapNamespace + "loc", string.Format(AppSettings.PostUrlFormat, Request.Url.Host, p.TitleTransliterated)),
                                new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", p.UpdatedOn))
                                ),
                            new XElement("changefreq", "monthly"),
                            new XElement("priority", "0.5")
                        )
                );

            return Content(sitemap.ToString(), "text/xml");
        }
コード例 #21
0
        /// <remarks>Internal for testing.</remarks>
        internal static void RetargetWithMetadataConverter(XDocument xdoc, Version targetSchemaVersion, MetadataConverterDriver converter)
        {
            Debug.Assert(xdoc != null, "xdoc != null");
            Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid target schema version");

            var inputXml = new XmlDocument { PreserveWhitespace = true };
            using (var reader = xdoc.CreateReader())
            {
                inputXml.Load(reader);
            }

            var outputXml = converter.Convert(inputXml, targetSchemaVersion);
            if (outputXml != null)
            {
                // Dev10 Bug 550594: There is a bug in XmlEditor that prevents from deleting the root node
                // unless the root node has previous sibling (like a comment or Xml declaration).
                if (xdoc.Root.PreviousNode == null)
                {
                    xdoc.Root.AddBeforeSelf(new XComment(""));
                }

                // update xml document with new root element
                xdoc.Root.Remove();
                using (var reader = new XmlNodeReader(outputXml))
                {
                    var newDoc = XDocument.Load(reader);
                    xdoc.Add(newDoc.Root);
                }

                // Do not reload artifact here
                // Until the transaction is commited, the XLinq representation of the parsed xml tree hasn't been generated yet.
            }
        }
コード例 #22
0
        protected override void ProcessRecord()
        {
            string path = null;

            XDocument document = null;

                // check for existing configuration, if not existing, create it
                string appDataFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string configFolder = System.IO.Path.Combine(appDataFolder, "Contoso.PSOnline.PowerShell");
                if (!Directory.Exists(configFolder))
                {
                    Directory.CreateDirectory(configFolder);
                }
                path = System.IO.Path.Combine(configFolder, "configuration.xml");

            if (!File.Exists(path))
            {
                document = new XDocument(new XDeclaration("1.0", "UTF-8", string.Empty));
                var configElement = new XElement("items");
                var siteProvisionServiceUrlElement = new XElement("item", new XAttribute("key", "RelativeSiteProvisionServiceUrl"));
                siteProvisionServiceUrlElement.Value = "/_vti_bin/contoso.services.sitemanager/sitemanager.svc";
                configElement.Add(siteProvisionServiceUrlElement);
                document.Add(configElement);

                document.Save(path);
            }
            else
            {
                document = XDocument.Load(path);
            }
            var itemsElement = document.Element("items");
            if (Value != null)
            {
                var items = from item in document.Descendants("item")
                            where item.Attribute("key").Value == Key
                            select item;
                if(items.Count() > 0)
                {
                    items.FirstOrDefault().Value = Value;
                }
                else
                {
                    var itemElement = new XElement("item", new XAttribute("key", Key));
                    itemElement.Value = Value;
                    itemsElement.Add(itemElement);
                }
            }
            else
            {
                var items = from item in document.Descendants("item")
                            where item.Attribute("key").Value == Key
                            select item;
                if(items.Count() > 0)
                {
                    items.FirstOrDefault().Remove();
                }
            }

            document.Save(path);
        }
コード例 #23
0
ファイル: Utility.cs プロジェクト: vpechev/PersonalIdProvider
        public static XDocument ConvertPersonalDocumentEntityToXml(PersonalDocument entity)
        {
            XDocument xmlDocumentEntity = new XDocument
                                          (
                                                new XElement("personalDocument",
                                                    new XElement("person",
                                                        new XElement("firstName", entity.Person.FirstName),
                                                        new XElement("lastName", entity.Person.LastName),
                                                        new XElement("isMale", entity.Person.IsMale),
                                                        new XElement("personalNumber", entity.Person.PersonalNumber),
                                                        new XElement("age", entity.Person.Age),
                                                        new XElement("birthDate", entity.Person.BirthDate),
                                                        new XElement("height", entity.Person.Height),
                                                        new XElement("address",
                                                               new XElement("country", entity.Person.Address.Country),
                                                               new XElement("town", entity.Person.Address.Town),
                                                               new XElement("streetName", entity.Person.Address.StreetName),
                                                               new XElement("streetNumber", entity.Person.Address.StreetNumber)
                                                                     )
                                                                ),
                                                    new XElement("document",
                                                        new XElement("documentNumber", entity.Document.DocumentNumber),
                                                        new XElement("dateOfIssue", entity.Document.DateOfDocumentIssue),
                                                        new XElement("dateOfExpiration", entity.Document.DateOfDocumentExpiration)
                                                                 )
                                                    )
                                            );

            return xmlDocumentEntity;
        }
コード例 #24
0
        private Route CreateGpx_1_1_Route(XDocument routeDocument, XNamespace ns)
        {
            XElement track = routeDocument.Root.Element(ns + "trk");
            string name = track.Element(ns + "name").Value;

            Route newRoute = new Route {Name = name, DateCreated = DateTime.Now};
            List<RoutePoint> routePoints = new List<RoutePoint>();
            var trackPoints = track.Descendants(ns + "trkpt");
            foreach (XElement trackPoint in trackPoints)
            {
                RoutePoint routePoint = new RoutePoint();
                routePoint.Latitude = double.Parse(trackPoint.Attribute("lat").Value);
                routePoint.Longitude = double.Parse(trackPoint.Attribute("lon").Value);
                routePoint.Elevation = double.Parse(trackPoint.Element(ns + "ele").Value);
                routePoint.TimeRecorded = DateTime.Parse(trackPoint.Element(ns + "time").Value);
                routePoints.Add(routePoint);
            }
            routePoints = routePoints.OrderBy(rp => rp.TimeRecorded).ToList();
            int index = 0;
            foreach (RoutePoint routePoint in routePoints)
            {
                routePoint.SequenceIndex = index;
                index++;
            }
            newRoute.RoutePoints = routePoints;
            newRoute.Distance = CalculateDistance(newRoute.RoutePoints);
            Tuple<double, double> ascentDescent = CalculateAscentDescent(newRoute.RoutePoints);
            newRoute.TotalAscent += ascentDescent.Item1;
            newRoute.TotalDescent += ascentDescent.Item2;
            return newRoute;
        }
コード例 #25
0
ファイル: Resultado.cs プロジェクト: dprolongo/PBioService
        public static Resultado LoadFromXML(XDocument xml)
        {
            Resultado resultado = new Resultado();

            try
            {
                if (xml.Root.Element("IdResultado") != null && xml.Root.Element("IdResultado").Value != "")
                    resultado.IdResultado = Guid.Parse(xml.Root.Element("IdResultado").Value);
                else
                    resultado.IdResultado = Guid.NewGuid();

                resultado.NombreGenesSolucion = xml.Root.Element("NombreGenesSolucion").Value;
                resultado.IdGenesSolucion = xml.Root.Element("IdGenesSolucion").Value;
                resultado.NumGenes = int.Parse(xml.Root.Element("NumGenes").Value);
                resultado.Accuracy_Media = double.Parse(xml.Root.Element("Accuracy_Media").Value);
                resultado.Accuracy_Std = double.Parse(xml.Root.Element("Accuracy_Std").Value);
                resultado.Sensitivity_Media = double.Parse(xml.Root.Element("Sensitivity_Media").Value);
                resultado.Sensitivity_Std = double.Parse(xml.Root.Element("Sensitivity_Std").Value);
                resultado.Specificity_Media = double.Parse(xml.Root.Element("Specificity_Media").Value);
                resultado.Specificity_Std = double.Parse(xml.Root.Element("Specificity_Std").Value);
                resultado.NombreGenes = xml.Root.Element("NombreGenes").Value;
                resultado.IdGenes = xml.Root.Element("IdGenes").Value;
                resultado.AccuracyXGenes = xml.Root.Element("AccuracyXGenes").Value;
                resultado.IdSimulacion = Guid.Parse(xml.Root.Element("IdSimulacion").Value);
                resultado.FechaLanzamiento = DateTime.Parse(xml.Root.Element("FechaLanzamiento").Value);
                resultado.FechaFinalizacion = DateTime.Parse(xml.Root.Element("FechaFinalizacion").Value);

            }
            catch (Exception e)
            {
                throw e;
            }

            return resultado;
        }
コード例 #26
0
 static bool GetIsSilverlight(XDocument xDocument)
 {
     var targetFrameworkIdentifier = xDocument.BuildDescendants("TargetFrameworkIdentifier")
         .Select(c => c.Value)
         .FirstOrDefault();
     return (string.Equals(targetFrameworkIdentifier, "Silverlight", StringComparison.OrdinalIgnoreCase));
 }
コード例 #27
0
        public ActionResult SiteMap()
        {
            var _Pages = PageService.GetSitemap(APP._SiteID, Request.Url.Authority);
            XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
            var _Q = from i in _Pages.Pages
                     select
                     new XElement(ns + "url",
                         new XElement(ns + "loc", Request.Url.Scheme + "://" + Request.Url.Authority + "/" + i.FriendlyUrl)
                         , new XElement(ns + "changefreq", "always"));

            if (_Pages.Blog)
            {
                _Q = _Q.Union((from i in _Pages.Posts
                               select
                               new XElement(ns + "url",
                                   new XElement(ns + "loc", Url.Action("detail", "blog", new { BlogPostID = i.BlogPostID, FriendlyUrl = i.FriendlyUrl }, Request.Url.Scheme))
                                   , new XElement(ns + "changefreq", "always"))))
                                   .Union((from i in _Pages.BlogCategories
                                           select
                                           new XElement(ns + "url",
                                               new XElement(ns + "loc", Url.Action("index", "blog", new { BlogCategoryFriendlyUrl = i.FriendlyUrl }, Request.Url.Scheme))
                                               , new XElement(ns + "changefreq", "always"))))
                                               .Union((from i in _Pages.BlogTags
                                                       select
                                                       new XElement(ns + "url",
                                                           new XElement(ns + "loc", Url.Action("tag", "blog", new { BlogTagName = i.BlogTagName }, Request.Url.Scheme))
                                                           , new XElement(ns + "changefreq", "always"))));
            }
            var sitemap = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement(ns + "urlset", _Q));
            return Content("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + sitemap.ToString(), "text/xml");
        }
コード例 #28
0
        void Compiler_WixSourceGenerated(System.Xml.Linq.XDocument document)
        {
            var product = document.Root.Select("Product");

            product.AddElement("Icon", "Id=app_icon.ico;SourceFile=" + TestData.Path(@"app_icon.ico"));
            product.AddElement("Property", "Id=ARPPRODUCTICON;Value=app_icon.ico");
        }
コード例 #29
0
 /// <summary>
 /// 获取XDocument转换后的IResponseMessageBase实例(通常在反向读取日志的时候用到)。
 /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常
 /// </summary>
 /// <returns></returns>
 public static IResponseMessageBase GetResponseEntity(XDocument doc)
 {
     ResponseMessageBase responseMessage = null;
     ResponseMsgType msgType;
     try
     {
         msgType = MsgTypeHelper.GetResponseMsgType(doc);
         switch (msgType)
         {
             case ResponseMsgType.Text:
                 responseMessage = new ResponseMessageText();
                 break;
             case ResponseMsgType.Image:
                 responseMessage = new ResponseMessageImage();
                 break;
             case ResponseMsgType.Voice:
                 responseMessage = new ResponseMessageVoice();
                 break;
             case ResponseMsgType.Video:
                 responseMessage = new ResponseMessageVideo();
                 break;
             case ResponseMsgType.News:
                 responseMessage = new ResponseMessageNews();
                 break;
             default:
                 throw new UnknownRequestMsgTypeException(string.Format("MsgType:{0} 在ResponseMessageFactory中没有对应的处理程序!", msgType), new ArgumentOutOfRangeException());
         }
         EntityHelper.FillEntityWithXml(responseMessage, doc);
     }
     catch (ArgumentException ex)
     {
         throw new WeixinException(string.Format("ResponseMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex);
     }
     return responseMessage;
 }
コード例 #30
0
ファイル: Program.cs プロジェクト: thistuna/schLauncher
        static void Main(string[] args)
        {
            Config config = new Config();

            if (args.Length == 0)
            {
                config.ShowDialog();
            }
            else
            {
                bool isEagle = false;
                try
                {
                    Xml.XDocument xDocument = Xml.XDocument.Load(args[0]);
                    Xml.XElement  xEagle    = xDocument.Element("eagle");
                    if (xEagle.Name == "eagle")
                    {
                        isEagle = true;
                    }
                }
                catch { }

                if (isEagle)
                {
                    //System.Windows.Forms.MessageBox.Show("Eagle" + config.EagleFilePath + "\n" + "\"" + args[0] + "\"");
                    System.Diagnostics.Process.Start(config.EagleFilePath, "\"" + args[0] + "\"");
                }
                else
                {
                    //System.Windows.Forms.MessageBox.Show("KiCad" + config.KiCadFilePath + "\n" + "\"" + args[0] + "\"");
                    System.Diagnostics.Process.Start(config.KiCadFilePath, "\"" + args[0] + "\"");
                }
            }
        }
コード例 #31
0
    static void Compiler_WixSourceGenerated(System.Xml.Linq.XDocument document)
    {
        XElement aspxFileComponent = (from e in document.FindAll("File")
                                      where e.Attribute("Source").Value.EndsWith("Default.aspx")
                                      select e)
                                     .First()
                                     .Parent;

        string dirID = aspxFileComponent.Parent.Attribute("Id").Value;

        XNamespace ns = WixExtension.IIs.ToXNamespace();

        aspxFileComponent.Add(new XElement(ns + "WebVirtualDir",
                                           new XAttribute("Id", "MyWebApp"),
                                           new XAttribute("Alias", "MyWebApp"),
                                           new XAttribute("Directory", dirID),
                                           new XAttribute("WebSite", "DefaultWebSite"),
                                           new XElement(ns + "WebApplication",
                                                        new XAttribute("Id", "TestWebApplication"),
                                                        new XAttribute("Name", "Test"))));

        document.Root.Select("Product")
        .Add(new XElement(ns + "WebSite",
                          new XAttribute("Id", "DefaultWebSite"),
                          new XAttribute("Description", "Default Web Site"),
                          new XAttribute("Directory", dirID),
                          new XElement(ns + "WebAddress",
                                       new XAttribute("Id", "AllUnassigned"),
                                       new XAttribute("Port", "80"))));
    }
コード例 #32
0
        public void UpdateInstrumentTest()
        {
            Instrument testInstrument = Instrument.GetInstrumentByID(-1);

            if (testInstrument.IsNew)
            {
                testInstrument.InstrumentID = -1;
            }
            testInstrument.Instrument1 = "Adage";
            BsoArchiveEntities.Current.Save();

            var instrumentID = Helper.CreateXElement(Constants.Artist.artistInstrumentIDElement, "-1");
            var instrument1  = Helper.CreateXElement(Constants.Artist.artistInstrumentElement, "Test");

            var artistItem = new System.Xml.Linq.XElement(Constants.Artist.artistElement, instrumentID, instrument1);
            var eventItem  = new System.Xml.Linq.XElement(Constants.Event.eventElement, artistItem);
            var doc        = new System.Xml.Linq.XDocument(eventItem);

            Instrument instrument = Instrument.NewInstrument();

            instrument.UpdateData(doc, "Instrument1", Constants.Artist.artistInstrumentElement);

            Assert.IsTrue(testInstrument.Instrument1 == "Test");
            BsoArchiveEntities.Current.DeleteObject(testInstrument);
            BsoArchiveEntities.Current.DeleteObject(instrument);
            BsoArchiveEntities.Current.Save();
        }
コード例 #33
0
        public List <EmployeeDetailsModel> GetEmpolyeeDetailsByXmlString(string xmlString, int Id)
        {
            List <EmployeeDetailsModel> employeeDetailsModel = new List <EmployeeDetailsModel>();


            System.Xml.Linq.XDocument xmlDoc = XDocument.Parse(xmlString);


            employeeDetailsModel = (from x in xmlDoc.Root.Elements("Employee")
                                    select
                                    new EmployeeDetailsModel
            {
                EmployeeId = Convert.ToInt32(x.Element("Id").Value),
                EmployeeName = (string)x.Element("Name").Value,
                EmployeeDesignation = (string)x.Element("Designation").Value,
                EmployeeAddress = (string)x.Element("Address").Value
            }).ToList();

            if (Id != 0)
            {
                List <EmployeeDetailsModel> agencyDetailsModelResult = employeeDetailsModel.Where(s => s.EmployeeId == Id).ToList <EmployeeDetailsModel>();
                return(agencyDetailsModelResult);
            }
            else
            {
                return(employeeDetailsModel);
            }



            //return agencyDetailsModel;
        }
コード例 #34
0
 public void SendMessage(XDocument message)
 {
     // Send the message across the wire to somewhere
     // This message mutates state in another system, which is bad for unit testing the MessageCreator
     // for now, just add the message to an in-memory queue
     messageQueue.Enqueue (message);
 }
コード例 #35
0
ファイル: AnswerFileHelper.cs プロジェクト: lycurgus/Infiniti
        public static string GetAnswerFile(string formId, Dictionary <Guid, string> providedData)
        {
            XDocument xDocument = new System.Xml.Linq.XDocument();

            XElement answerFile   = new XElement("AnswerFile");
            XElement headerInfo   = new XElement("HeaderInfo");
            XElement templateInfo = new XElement("TemplateInfo");

            templateInfo.Add(new XAttribute("TemplateGroupId", formId.ToString()));
            templateInfo.Add(new XAttribute("RunId", Guid.NewGuid().ToString().ToString()));
            templateInfo.Add(new XAttribute("FirstLaunchTimeUtc", DateTime.UtcNow));
            headerInfo.Add(templateInfo);

            answerFile.Add(headerInfo);
            xDocument.Add(answerFile);

            if (providedData.Count > 0)
            {
                XElement providedDataElm = new XElement("ProvidedData");

                foreach (Guid key in providedData.Keys)
                {
                    XElement dataElm = new XElement("Data");
                    dataElm.Add(new XAttribute("Id", key.ToString()));
                    dataElm.Add(new XCData(providedData[key]));
                    providedDataElm.Add(dataElm);
                }

                answerFile.Add(providedDataElm);
            }

            return(answerFile.ToString());
        }
コード例 #36
0
        private void ImportTexturesFromXml(XDocument xml)
        {
            var texData = xml.Root.Elements("ImportTexture");
            foreach (var tex in texData)
            {
                string name = tex.Attribute("filename").Value;
                string data = tex.Value;

                // The data is gzip compressed base64 string. We need the raw bytes.
                //byte[] bytes = ImportUtils.GzipBase64ToBytes(data);
                byte[] bytes = ImportUtils.Base64ToBytes(data);

                // Save and import the texture asset
                {
                    string pathToSave = GetTextureAssetPath(name);
                    ImportUtils.ReadyToWrite(pathToSave);
                    File.WriteAllBytes(pathToSave, bytes);
                    AssetDatabase.ImportAsset(pathToSave, ImportAssetOptions.ForceSynchronousImport);
                }

                // Create a material if needed in prepartion for the texture being successfully imported
                {
                    string materialPath = GetMaterialAssetPath(name);
                    Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
                    if (material == null)
                    {
                        // We need to create the material afterall
                        // Use our custom shader
                        material = new Material(Shader.Find("Tiled/TextureTintSnap"));
                        ImportUtils.ReadyToWrite(materialPath);
                        AssetDatabase.CreateAsset(material, materialPath);
                    }
                }
            }
        }
コード例 #37
0
ファイル: ParseLessons.cs プロジェクト: Mexahoid/CSF
 //Возвращает список предметов
 public static string[] LessonParse(XDocument Lessons, string Class)
 {
     string[] New = new string[0];
       foreach (string Lesson in Lessons.Element("Lessons").Elements(Class).Elements("LessIds"))
     New = HelpDeriver(Lesson);
       return New;
 }
コード例 #38
0
 private XDocument GenerateXML()
 {
     XDocument xml = new XDocument(
         new XDeclaration("1.0", "windows-1250", "true"),
         new XElement("Zadost",
             new XAttribute("Verze", "01"),
             new XAttribute("Kod", this.smlouvaID),
             new XAttribute("Typ", "Z"),
             new XAttribute("Timestamp", this.smlouvaCreateDate.ToString()),
             new XElement("NazevFilmu", tbNazevFilmu.Text),
             new XElement("NazevSkladby", tbNazevSkladby.Text),
             new XElement("AutoriHudby", tbAutoriHudby.Text),
             new XElement("AutoriTextu", tbAutoriTextu.Text),
             new XElement("Nakladatel", tbNakladatel.Text),
             new XElement("Label", tbLabel.Text),
             new XElement("ZpracovatelHudby", tbZpracovatelHudby.Text),
             new XElement("Subtextar", tbSubtextar.Text),
             new XElement("VyrobceReklamnihoSpotu", tbVyrobceReklamy.Text),
             new XElement("Zadavatel", tbZadavatel.Text),
             new XElement("HudebniStopaz", tbHudebniStopaz.Text),
             new XElement("DruhUziti", tbDruhUziti.Text),
             new XElement("ZpusobUziti", tbZpusobUziti.Text),
             new XElement("SouhlasUdelil", tbSouhlasUdelil.Text),
             new XElement("DobaTrvaniLicence", tbDobaTrvaniLicence.Text),
             new XElement("Poznamky", tbPoznamka.Text),
             new XElement("EmailProPotvrzeni", tbEmailProPotvrzeni.Text)
                     ));
     return xml;
 }
コード例 #39
0
        static void Main(string[] args)
        {
            var db = new GeographyEntities();
            var countries = db.Countries
            .OrderBy(c => c.CountryName)
            .Select(c => new
            {
                coutryName = c.CountryName,
                monasteries = c.Monasteries.OrderBy(m => m.Name).Select(m => m.Name)
            }).ToList();

            XElement root = new XElement("monasteries");
            foreach (var country in countries)
            {
                if (country.monasteries.Count() != 0)
                {
                    var xmlCountry = new XElement("country");
                    xmlCountry.Add(new XAttribute("name", country.coutryName));
                    foreach (var xmlMonasteries in country.monasteries)
                    {
                        xmlCountry.Add(new XElement("monastery", xmlMonasteries));
                    }
                    root.Add(xmlCountry);   
                }
            }

            var xmlDoc = new XDocument(root);
            xmlDoc.Save("../../monasteries.xml");
        }
コード例 #40
0
ファイル: ParseLessons.cs プロジェクト: Mexahoid/CSF
 //Возвращает список названий
 public static List<string> GetLessonNames(XDocument Lessons, string Class)
 {
     List<string> Names = new List<string>();
       foreach (string Lesson in Lessons.Element("Lessons").Elements(Class).Elements("name"))
     Names.Add(TextDeriver(Lesson));
       return Names;
 }
コード例 #41
0
ファイル: PLCInformation.cs プロジェクト: snJustice/YSMS_SZSK
        public int Load(string path, ref string exMessage)
        {
            int result = 0;

            try
            {
                System.Xml.Linq.XDocument xDoc = System.Xml.Linq.XDocument.Load(path);
                XElement root = xDoc.Root;
                //尺寸
                XElement PLCFaults = root.Element("PLCFaults");
                PLCFaultDic.Clear();
                foreach (var v in PLCFaults.Elements())
                {
                    PLCFault f = XmlSerializer.Deserialize(v, typeof(PLCFault)) as PLCFault;
                    PLCFaultDic.Add(f.ID, f);
                }
            }
            catch (System.Exception ex)
            {
                SoftwareInfo.getInstance().WriteLog("Load:\n" + ex.ToString());
                exMessage = ex.Message;
                result    = 1;
            }
            return(result);
        }
コード例 #42
0
		/// <summary>
		/// Writes the results of XSLT transformation into the specified TextWriter.
		/// </summary>
		public static void WriteProcessed(string templateName, XsltArgumentList argumentList, XDocument data, TextWriter outStream)
		{
			using (XmlReader reader = data.CreateReader())
			{
				GetCompiledTransform(templateName).Transform(reader, argumentList, outStream);
			}
		}
コード例 #43
0
        /// <summary>
        /// Adds a digital signature to the outgoing request message, before sending it to Acquirer.
        /// </summary>
        /// <param name="requestXml">
        /// The unsigned request XML message.
        /// </param>
        /// <returns>
        /// The request message, including digital signature.
        /// </returns>
        public string SignRequestXml(XDocument requestXml)
        {
            XmlDocument document = ToXmlDocument(requestXml);

            RSACryptoServiceProvider key = ExtractPrivateKeyFrom(acceptantPrivateCertificate);

            var signedXml = new SignedXml(document) { SigningKey = key };
            signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";

            // Add a signing reference, the uri is empty and so the whole document is signed. 
            var reference = new Reference { DigestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256" };
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.Uri = "";
            signedXml.AddReference(reference);

            // Add the certificate as key info. Because of this, the certificate 
            // with the public key will be added in the signature part. 
            var keyInfo = new KeyInfo();
            keyInfo.AddClause(new KeyInfoName(acceptantPrivateCertificate.Thumbprint));
            signedXml.KeyInfo = keyInfo;

            // Generate the signature. 
            signedXml.ComputeSignature();

            XmlElement xmlSignature = signedXml.GetXml();
            document.DocumentElement.AppendChild(document.ImportNode(xmlSignature, true));

            // Check that outgoing signature is valid. Private certificate also contains public part.
            VerifyDocumentSignature(document, acceptantPrivateCertificate);

            return GetContentsFrom(document);
        }
コード例 #44
0
 /// <summary>
 /// Provides an extension method that converts an
 /// XmlNode to a Linq XElement.
 /// </summary>
 /// <param name="node">the XmlNode</param>
 /// <returns>Linq XElement</returns>
 public static XElement GetXElement(this XmlNode node)
 {
     var xDoc = new XDocument();
     using (var xmlWriter = xDoc.CreateWriter())
         node.WriteTo(xmlWriter);
     return xDoc.Root;
 }
コード例 #45
0
ファイル: UtilityController.cs プロジェクト: beardeddev/briar
        public ContentResult RSS()
        {
            List<Post> posts = Post.Collection.Find(Post.ActiveScope)
                .SetSortOrder(Post.DefaultSortByScope)
                .ToList();

            var rss = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("rss",
                  new XAttribute("version", "2.0"),
                        new XElement("channel",
                          new XElement("title", AppSettings.RSSTitle),
                          new XElement("link", AppSettings.RSSLink),
                          new XElement("description", AppSettings.RSSDescription),
                          new XElement("copyright", AppSettings.RSSCopyright),
                        from p in posts
                        select
                        new XElement("item",
                              new XElement("title", p.Title),
                              new XElement("description", p.Description),
                              new XElement("link", String.Format(AppSettings.PostUrlFormat, Request.Url.Host, p.TitleTransliterated)),
                              new XElement("pubDate", p.PublishedOn.ToString("R")),
                              new XElement("guid", String.Format(AppSettings.PostUrlFormat, Request.Url.Host, p.TitleTransliterated))
                              )
                          )
                     )
                );

            return Content(rss.ToString(), "text/xml");
        }
コード例 #46
0
 /// <summary>
 /// Updates the XML data.
 /// </summary>
 /// <param name="dtRow">The dt row.</param>
 /// <param name="uniqueIdentity">The unique identity.</param>
 /// <param name="type">The type.</param>
 /// <returns></returns>
 public int UpdateXmlData(DataRow dtRow, string uniqueIdentity, string type)
 {
     try
     {
         System.Xml.Linq.XDocument resultsDoc = System.Xml.Linq.XDocument.Parse((System.Xml.Linq.XDocument.Load(Datacontext.GetInstance().CorporateFavoriteFile)).ToString());
         var query = resultsDoc.Root.Descendants("Favorites");
         foreach (System.Xml.Linq.XElement e in query)
         {
             if (e.Element("UniqueIdentity").Value.ToString() == uniqueIdentity && e.Element("Type").Value.ToString() == type)
             {
                 e.Element("Category").Value     = dtRow["Category"].ToString();
                 e.Element("DisplayName").Value  = dtRow["DisplayName"].ToString();
                 e.Element("FirstName").Value    = dtRow["FirstName"].ToString();
                 e.Element("LastName").Value     = dtRow["LastName"].ToString();
                 e.Element("PhoneNumber").Value  = dtRow["PhoneNumber"].ToString();
                 e.Element("EmailAddress").Value = dtRow["EmailAddress"].ToString();
                 e.Element("Type").Value         = dtRow["Type"].ToString();
             }
         }
         resultsDoc.Save(Datacontext.GetInstance().CorporateFavoriteFile);
     }
     catch (Exception error)
     {
         _logger.Error("Error in updating favorite XMLdata : " + error.Message.ToString());
     }
     return(0);
 }
コード例 #47
0
ファイル: LastFMTrack.cs プロジェクト: arangas/MediaPortal-1
    public LastFMTrackInfo(XDocument xDoc)
    {
      if (xDoc.Root == null) return;
      var track = xDoc.Root.Element("track");
      if (track == null) return;

      Identifier = (int) track.Element("id");
      TrackTitle = (string) track.Element("name");
      MusicBrainzId = (string) track.Element("mbid");
      TrackURL = (string) track.Element("url");
      Duration = (int) track.Element("duration");
      Listeners = (int) track.Element("listeners");
      Playcount = (int) track.Element("playcount");

      var artistElement = track.Element("artist");
      if (artistElement != null) ArtistName = (string) artistElement.Element("name");

      TopTags = (from tagElement in track.Descendants("tag")
                 let tagName = (string) tagElement.Element("name")
                 let tagURL = (string) tagElement.Element("url")
                 select new LastFMTag(tagName, tagURL)
                ).ToList();

      var albumElement = track.Element("album");
      if (albumElement != null)
      {
        Images = (from i in albumElement.Elements("image")
                  select new LastFMImage(
                    LastFMImage.GetImageSizeEnum((string) i.Attribute("size")),
                    (string) i
                    )
                 ).ToList();
      }
    }
コード例 #48
0
        private static IEnumerable<ReferenceDescriptor> GetReferences(XDocument document) {
            var assemblyReferences = document
                .Elements(ns("Project"))
                .Elements(ns("ItemGroup"))
                .Elements(ns("Reference"))
                .Where(c => c.Attribute("Include") != null)
                .Select(c => {
                            string path = null;
                            XElement attribute = c.Elements(ns("HintPath")).FirstOrDefault();
                            if (attribute != null) {
                                path = attribute.Value;
                            }

                            return new ReferenceDescriptor {
                                SimpleName = ExtractAssemblyName(c.Attribute("Include").Value),
                                FullName = c.Attribute("Include").Value,
                                Path = path,
                                ReferenceType = ReferenceType.Library
                            };
                        });

            var projectReferences = document
                .Elements(ns("Project"))
                .Elements(ns("ItemGroup"))
                .Elements(ns("ProjectReference"))
                .Attributes("Include")
                .Select(c => new ReferenceDescriptor {
                    SimpleName = Path.GetFileNameWithoutExtension(c.Value),
                    FullName = Path.GetFileNameWithoutExtension(c.Value),
                    Path = c.Value,
                    ReferenceType = ReferenceType.Project
                });

            return assemblyReferences.Union(projectReferences);
        }
コード例 #49
0
        void ExtractArchetypesAndTemplates(ref List <string> listIdArchetypes, ref List <string> listEmbeddedTemplates, string sTemplateXML)
        {
            System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(sTemplateXML));

            if (String.IsNullOrEmpty(sTemplateXML))
            {
                return;
            }

            System.Xml.Linq.XDocument xtemplate = null;
            try
            {
                xtemplate = XDocument.Parse(sTemplateXML);
            }
            catch (Exception e)
            {
                throw e;
            }

            var defs = xtemplate.Descendants().Where(p => p.Name.LocalName == "integrity_checks");

            if (defs != null)
            {
                foreach (XElement def in defs)
                {
                    var archid = def.Attribute("archetype_id");
                    listIdArchetypes.Add(archid.Value);
                }
            }

            var names = xtemplate.Descendants().Where(p => p.Name.LocalName == "name").FirstOrDefault();

            if (names != null)
            {
                Console.WriteLine("Template Name = " + names.Value);
            }

            List <string> sValue = new List <string>();

            xtemplate.Descendants().Where(p => p.Name.LocalName == "Item")
            .ToList()
            .ForEach(e =>
            {
                XAttribute tid = e.Attribute("template_id");
                if (tid != null)
                {
                    Console.WriteLine(tid.Value);
                    string Value = tid.Value;

                    sValue.Add(Value);
                }
                //Console.WriteLine(e);
            });

            foreach (string template in sValue)
            {
                listEmbeddedTemplates.Add(template);
            }
        }
コード例 #50
0
        public void XDocumentTypeConverterTests()
        {
            PrimitiveTypeConverter converter = new XDocumentTypeConverter();

            System.Xml.Linq.XDocument xdoc = (System.Xml.Linq.XDocument)converter.Parse("<?xml version=\"1.0\" encoding=\"iso-8859-1\" standalone=\"yes\"?><feed></feed>");
            Assert.AreEqual("<feed></feed>", xdoc.ToString());
            Assert.AreEqual("<feed></feed>", converter.ToString(xdoc));
        }
コード例 #51
0
        public Epi.Core.EnterInterpreter.Rule_Context GetCheckCodeObj(System.Xml.Linq.XDocument xdoc, System.Xml.Linq.XDocument xdocResponse, string FormCheckCode)
        {
            Epi.Core.EnterInterpreter.EpiInterpreterParser EIP    = new Epi.Core.EnterInterpreter.EpiInterpreterParser(Epi.Core.EnterInterpreter.EpiInterpreterParser.GetEnterCompiledGrammarTable());
            Epi.Core.EnterInterpreter.Rule_Context         result = (Epi.Core.EnterInterpreter.Rule_Context)EIP.Context;
            result.LoadTemplate(xdoc, xdocResponse);
            EIP.Execute(FormCheckCode);

            return(result);
        }
コード例 #52
0
 public AFD(List <int> q, List <char> x, List <Transition> transitions, int q0, List <int> f, string ruta)
 {
     this.documento = XDocument.Load(ruta);
     Q           = list_Q();
     X           = list_X();
     transitions = list_Transicion();
     q0          = q0;
     F           = f;
 }
コード例 #53
0
        public void WriteTransformResult(string templateName, System.Xml.Linq.XDocument data)
        {
            this.httpresponse.ContentType     = this.design.ContentType;
            this.httpresponse.ContentEncoding = OutputEncoding;
            DateTime start = DateTime.Now;

            TemplateEngine.WriteCompiled(this.design.GetFSName(templateName), data, this.httpresponse.Output);
            Config.instance.Logger.Log(templateName + " transformation took " + (DateTime.Now - start).TotalSeconds + " seconds");
        }
コード例 #54
0
ファイル: RDLGenerator.cs プロジェクト: Avinash-acid/saveenr
        private static MemoryStream SaveXMLToMemoryStream(SXL.XDocument new_dom)
        {
            var mem_stream = new System.IO.MemoryStream();
            var ts         = new System.IO.StreamWriter(mem_stream);

            new_dom.Save(ts);
            mem_stream.Seek(0, System.IO.SeekOrigin.Begin);
            return(mem_stream);
        }
コード例 #55
0
ファイル: Report.cs プロジェクト: Avinash-acid/saveenr
        public XDocument ReportToXMLDOM()
        {
            var el_report = CreateReportXML();

            var doc = new System.Xml.Linq.XDocument();

            doc.Add(el_report);
            return(doc);
        }
コード例 #56
0
    private static void InjectImages(System.Xml.Linq.XDocument document)
    {
        var productElement = document.Root.Select("Product");

        productElement.Add(new XElement("WixVariable",
                                        new XAttribute("Id", "WixUIBannerBmp"),
                                        new XAttribute("Value", @"Images\bannrbmp.bmp")));
        // alternative syntax
        productElement.AddElement("WixVariable", @"Id=WixUIDialogBmp;Value=Images\dlgbmp.bmp");
    }
コード例 #57
0
        public void UpdateTuDien(string fileName, MathRule mathRule)
        {
            System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(fileName);
            var node = (from t in document.Descendants("Column")
                        where t.Element("DataBase").Value == mathRule.ColumnInDB
                        select t).FirstOrDefault();

            node.Element("Excel").Value = mathRule.ColumnInExcel;
            document.Save(fileName);
        }
コード例 #58
0
ファイル: Config.cs プロジェクト: thistuna/schLauncher
 private void buttonOK_Click(object sender, EventArgs e)
 {
     Xml.XDocument xDocument = new Xml.XDocument(new Xml.XDeclaration("1.0", "utf-8", "Yes"));
     Xml.XElement  xSettings = new Xml.XElement("schLauncherSettings");
     xSettings.Add(new Xml.XElement("KiCadPath", textBoxKiCad.Text));
     xSettings.Add(new Xml.XElement("EaglePath", textBoxEagle.Text));
     xDocument.Add(xSettings);
     xDocument.Save("settings.xml");
     this.Close();
 }
コード例 #59
0
ファイル: Form1.cs プロジェクト: IMAGE-ET/DicomViewer-4
        public Form1()
        {
            InitializeComponent();

            Slopelabel.Text     = "NaN";
            Interceptlabel.Text = "NaN";
            Maxscalarlabel.Text = "NaN";
            Minscalarlabel.Text = "NaN";


            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Ini.ini"))
            {
                IniObjMain    = new Ini(AppDomain.CurrentDomain.BaseDirectory + "Ini.ini");
                ApiURL        = IniObjMain.IniReadValue("Info", "api_url");
                CurrentHash   = IniObjMain.IniReadValue("Info", "curr_work_dir");
                TempDir       = IniObjMain.IniReadValue("Info", "temp_folder") + "\\" + CurrentHash;
                IniObjCurrent = new Ini(TempDir + "\\" + "Ini.ini");
                minScalar     = Convert.ToInt32(IniObjCurrent.IniReadValue("Info", "min_scalar"));
                maxScalar     = Convert.ToInt32(IniObjCurrent.IniReadValue("Info", "max_scalar"));
                DICOMDir      = IniObjCurrent.IniReadValue("Info", "dicom_folder");
                if (DICOMDir != "")
                {
                    string[] fileEntriesDICOM = Directory.GetFiles(DICOMDir);
                    foreach (string file in fileEntriesDICOM)
                    {
                        DicomTagParser.DICOMParser myDP = new DicomTagParser.DICOMParser(file);
                        System.Xml.Linq.XDocument  mdoc = myDP.GetXDocument();
                        var slope_this     = GetElement(mdoc, "(0028,1053)");
                        var intercept_this = GetElement(mdoc, "(0028,1052)");
                        if (slope_this == null || intercept_this == null)
                        {
                            continue;
                        }
                        else
                        {
                            slope               = Convert.ToInt32(slope_this);
                            intercept           = Convert.ToInt32(intercept_this);
                            Slopelabel.Text     = slope_this;
                            Interceptlabel.Text = intercept_this;
                            Maxscalarlabel.Text = Convert.ToString(maxScalar);
                            Minscalarlabel.Text = Convert.ToString(minScalar);
                            break;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Variable dicom_folder does not set!");
                }
            }
            else
            {
                MessageBox.Show("Ini file does not exist!");
            }
        }
コード例 #60
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (!System.IO.Directory.Exists(@"D:\"))
                {
                    Program.MessageError("Sticker", "Drive D:", "Not found.", false);
                }
                else
                {
                    if (!System.IO.Directory.Exists(@"D:\EmrCheckup"))
                    {
                        System.IO.DirectoryInfo di = System.IO.Directory.CreateDirectory(@"D:\EmrCheckup");
                        di.Attributes = System.IO.FileAttributes.Directory | System.IO.FileAttributes.Hidden;
                    }
                    if (!System.IO.File.Exists(@"D:\EmrCheckup\PrinterSticker.xml"))
                    {
                        new XDocument(
                            new XElement("PrinterCls",
                                         new XElement("Report",
                                                      new XAttribute("id", "Wristband"),
                                                      new XElement("Printer", comboAutoDropDownWidth1.Text),
                                                      new XElement("Paper", ((PrinterPaperSize)comboAutoDropDownWidth2.SelectedItem).Name)
                                                      )
                                         )
                            ).Save(@"D:\EmrCheckup\PrinterSticker.xml");
                    }
                    else
                    {
                        System.Xml.Linq.XDocument xml = System.Xml.Linq.XDocument.Load(@"D:\EmrCheckup\PrinterSticker.xml");
                        var wb = xml.Element("PrinterCls").Elements("Report").Where(x => x.Attribute("id").Value == "Wristband").FirstOrDefault();

                        if (wb == null)
                        {
                            xml.Element("PrinterCls").Add(
                                new XElement("Report",
                                             new XAttribute("id", "Wristband"),
                                             new XElement("Printer", comboAutoDropDownWidth1.Text),
                                             new XElement("Paper", ((PrinterPaperSize)comboAutoDropDownWidth2.SelectedItem).Name)
                                             )
                                );
                        }
                        else
                        {
                            wb.Element("Printer").Value = comboAutoDropDownWidth1.Text;
                            wb.Element("Paper").Value   = ((PrinterPaperSize)comboAutoDropDownWidth2.SelectedItem).Name;
                        }
                        xml.Save(@"D:\EmrCheckup\PrinterSticker.xml");
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }