Esempio n. 1
0
 public XDocument ParseDocument(string text)
 {
     //System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
     XDocument doc = new XDocument();
     try
     {
         StringCounter sc = new StringCounter(text);
         sc.TrimStart();
         if (sc.StartsWith("<"))
         {
             while (!sc.IsAtEnd)
             {
                 XContainer childNode = this.ParseNode(sc, doc);
             }
             XElement[] enm = MyHelper.EnumToArray(doc.Elements());
             if (enm.Length > 1)
             {
                 XElement root = new XElement(XName.Get("root"));
                 foreach (XElement elem in enm)
                 {
                     root.Add(elem);
                 }
                 doc.Elements().Remove();
                 doc.Add(root);
             }
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.Message);
     }
     //sw.Stop();
     //System.Diagnostics.Debug.WriteLine(sw.Elapsed.TotalMilliseconds.ToString("N0"));
     return doc;
 }
        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);
        }
        public OstcOrderResult ExtractResult(Uri responseUri, XDocument responsePage)
        {

            var statusImageXml = responsePage
                .Elements("html")
                .Elements("body")
                .Elements("form")
                .Elements("table")
                .Elements("tr")
                .Elements("td").Where(x => x.Attributes("class").Any(y => y.Value== "sidebarFooter"))
                .Elements("img")
                .FirstOrDefault();
            if (statusImageXml == null)
                statusImageXml = responsePage
                    .Elements("html")
                    .Elements("body")
                    .Elements("blockquote")
                    .Elements("img")
                    .FirstOrDefault();
            if (statusImageXml == null)
                return null;

            var statusImageSrc = statusImageXml.Attributes("src").Select(x => x.Value).FirstOrDefault();
            switch (System.IO.Path.GetFileNameWithoutExtension(statusImageSrc))
            {
                case "ampel_gruen":
                    break;
                case "ampel_gelb":
                    return new OstcOrderResult() { Status = OstcOrderStatus.Processing };
                default:
                    return new OstcOrderResult() { Status = OstcOrderStatus.Failed, Message = statusImageXml.Value };
            }
            var certLinkXml = statusImageXml
                .Elements("p")
                .Elements("a")
                .FirstOrDefault();
            if (certLinkXml == null)
            {
                // Darf eigentlich nicht passieren...
                return new OstcOrderResult()
                {
                    Status = OstcOrderStatus.Unknown
                };
            }

            var hrefAttr = certLinkXml.Attribute("href");
            if (hrefAttr == null)
            {
                // Darf eigentlich nicht passieren...
                return new OstcOrderResult()
                {
                    Status = OstcOrderStatus.Unknown
                };
            }

            var certUri = new Uri(responseUri, hrefAttr.Value);

            return new OstcOrderResult { Status = OstcOrderStatus.Successful, DownloadUrl = certUri };
        }
Esempio n. 4
0
        /// <summary>
        /// 初始化配置文件
        /// </summary>
        private Configuration()
        {

            if (File.Exists(FILE_NAME))
            {
                try
                {
                    document = System.Xml.Linq.XDocument.Load(FILE_NAME);
                    foreach (var elem in document.Elements("properties"))
                    {
                        if (elem.Name == "comment")
                            comment = elem.Value;
                        if (elem.Name == "entry" && elem.Attributes("key") != null)
                        {
                            if (elem.Attributes("key").First().Value == "ext_dict")
                                extDicStr = elem.Value;
                            if (elem.Attributes("key").First().Value == "ext_stopwords")
                                extStopStr = elem.Value;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
            }
        }
Esempio n. 5
0
 public static IEnumerable<ItemGroupItem> FromProjectDocument(XDocument projectDocument)
 {
     return projectDocument
         .Elements().Single(x => x.Name.LocalName == "Project")
         .Elements().Where(x => x.Name.LocalName == "ItemGroup")
         .SelectMany(x => x.Elements().Select(element => new ItemGroupItem(element)));
 }
        public Dictionary<string, Dictionary<string, string>> ParseEnglishGetCapabilities(XDocument getCapabilitiesEnglish)
        {
            Dictionary<string, Dictionary<string, string>> englishData = new Dictionary<string, Dictionary<string, string>>();

            IEnumerable<XElement> englishLayers =
                from el in getCapabilitiesEnglish.Elements(WMS + "WMS_Capabilities").Elements(WMS + "Capability").Elements(WMS + "Layer").Elements(WMS + "Layer")
                select el;

            if (englishLayers != null)
            {
                foreach (var layer in englishLayers)
                {
                    var nameElement = layer.Element(WMS + "Name");
                    string name = nameElement != null ? nameElement.Value : null;

                    var titleElement = layer.Element(WMS + "Title");
                    string title = titleElement != null ? titleElement.Value : null;

                    var abstractElement = layer.Element(WMS + "Abstract");
                    string @abstract = abstractElement != null ? abstractElement.Value : null;

                    var values = new Dictionary<string, string>();
                    values.Add("title", title);
                    values.Add("abstract", @abstract);

                    englishData.Add(name, values);
                }
            }

            return englishData;
        }
        private void populateLookup(XDocument xml)
        {
            IEnumerable<XElement> elements = null;

            if (xml.Element("UNITCONSTANTS").HasElements)
            {
                elements = xml.Elements();
                
                IEnumerator<XElement> itr = null;// = xml.DescendantNodes().GetEnumerator();
                //XElement unitConstants = XElement.Load(ofd1.FileName, LoadOptions.None);
                itr = elements.GetEnumerator();
                

                XElement child = null;
                itr.MoveNext();
                child = itr.Current;//UNITCONSTANTS
                if (child.HasElements)
                {
                    elements = child.Elements();
                    itr = elements.GetEnumerator();//SYMBOLS
                    while (itr.MoveNext())
                    {
                        child = itr.Current;
                        UnitDef temp = UnitDef.XNodeToUnitDef(child);
                        if ((temp != null) && _UnitDefinitions.ContainsKey(temp.getBasicSymbolId())==false)//temp will be null if node is an XCOMMENT
                            _UnitDefinitions.Add(temp.getBasicSymbolId(), temp);

                    }//end while
                }
            }//end if
        }//end populate lookup
Esempio n. 8
0
        private List<YaLimits> CollectLimitsTo(XDocument xDocument)
        {
            //Лист структур YaSearchResult, который метод в итоге возвращает.
            List<YaLimits> ret = new List<YaLimits>();

            //из полученного XML'я выдираем все элементы с именем "time-interval" - это результаты поиска
            var groupQuery = from gr in xDocument.Elements().
                Elements("response").
                Elements("limits").
                Elements("time-interval")
                select gr;
            //DateTime dtFrom, dtTo;
            //каждый элемент group преобразовывается в объект SearchResult
            for (int i = 0; i < groupQuery.Count(); i++)
            {
                string strFrom = GetAttribute(groupQuery.ElementAt(i), "from");
                string strTo = GetAttribute(groupQuery.ElementAt(i), "to");
                //string strTo = GetValue(groupQuery.ElementAt(i), "time-interval");
                string iQuantity = GetValue(groupQuery.ElementAt(i), "");
                //string indexedTimeQuery = GetValue(groupQuery.ElementAt(i), "modtime");
                //string cacheUrlQuery = GetValue(groupQuery.ElementAt(i), "saved-copy-url");
                ret.Add(new YaLimits(strFrom, strTo, iQuantity));
            }

            return ret;


        }
        protected override ConventionResult IsSatisfiedByInternal(string assemblyName, XDocument projectDocument)
        {
            var references =
                projectDocument.Elements()
                    .Single(x => x.Name.LocalName == "Project")
                    .Elements()
                    .Where(x => x.Name.LocalName == "ItemGroup")
                    .SelectMany(x => x.Elements().Where(e => e.Name.LocalName == "Reference"));


            var failures =
                references
                    .Where(x => x.Elements().Any(e => e.Name.LocalName == "HintPath" && Regex.IsMatch(e.Value, ObjOrBinPattern)))
                    .Select(x =>
                        new Failure(
                            x.Attributes().Single(a => a.Name.LocalName == "Include").Value,
                            x.Elements().Single(e => e.Name.LocalName == "HintPath").Value))
                    .ToArray();

            if (failures.Any())
            {
                var failureText =
                    FailureMessage.FormatWith(assemblyName) +
                    Environment.NewLine +
                    failures.Aggregate(string.Empty,
                        (s, t) => s + "\t" + t.Reference + " " + "(" + t.Location + ")" + Environment.NewLine);

                return ConventionResult.NotSatisfied(assemblyName, failureText);
            }

            return ConventionResult.Satisfied(assemblyName);
        }
Esempio n. 10
0
        private static TemplateInformation ParseXmlDocument(XDocument document)
        {
            var templateInformation = new TemplateInformation();
            var template = (from x in document.Elements("template") select x).FirstOrDefault();

            return ReadXmlDocument(templateInformation, template);
        }
Esempio n. 11
0
 private void ParseXML(XDocument doc)
 {
     foreach (XElement block in doc.Elements("Service"))
     {
         foreach (XElement element in block.Elements("Service_Information").Elements())
         {
             ServiceInformation[element.Name.ToString()] = element.Value;
         }
         foreach (XElement element in block.Elements("Service_Config").Elements())
         {
             ServiceConfig[element.Name.ToString()] = element.Value;
         }
         foreach (XElement element in block.Elements("SIP_Headers").Elements())
         {
             SIPHeaders[element.Name.ToString()] = element.Value;
         }
         foreach (XElement element in block.Elements("SIP_Responses").Elements())
         {
             SIPResponses[element.Name.ToString()] = element.Value;
         }
         foreach (XElement element in block.Elements("Capabalities").Elements())
         {
             Capabilities[element.Name.ToString()] = element.Value;
         }
         foreach (XElement element in block.Elements("Metrics").Elements())
         {
             Metrics[element.Name.ToString()] = element.Value;
         }
     }
 }
Esempio n. 12
0
        private static IEnumerable<DrumPreset> DrumLoad(XDocument document)
        {
            var preset = document.Elements("ux").Select(e => e.Elements("preset")).Select(e => e.Elements("drum")).FirstOrDefault();

            if (preset == null)
                throw new ArgumentException();

            var notes = preset.Elements("note");

            foreach (var note in notes)
            {
                var number = note.GetAttribute(PresetReader.xnumber);
                var note_number = note.GetAttribute(PresetReader.xnote);
                int num = 0, note_num = 0;

                if (!int.TryParse(number, out num))
                    throw new ArgumentException();

                if (!int.TryParse(note_number, out note_num))
                    throw new ArgumentException();

                yield return new DrumPreset(num, note_num,
                    note.Elements()
                    .Where(h => h.Name.LocalName.ToLower() != "final")
                    .Select(h => HandleCreator.Create(h.Name.LocalName.ToLower(), h.GetAttribute(PresetReader.xtype), h.GetAttribute(PresetReader.xvalue))));
            }
        }
Esempio n. 13
0
        public static Configuration FromXml(XDocument xdoc)
        {
            var result = new Dictionary<string, string>();
            foreach (var param in xdoc.Elements("configuration").SelectMany(i => i.Elements("parameter")))
            {
                var keyAttr = param.Attribute("key");
                var valueAttr = param.Attribute("value");
                if (keyAttr == null)
                {
                    throw new ArgumentException("Attribute 'key' is required for element 'parameter'.");
                }

                string parameterValue = null;

                if (valueAttr != null)
                {
                    parameterValue = valueAttr.Value;
                }
                else if (param.Elements().Any())
                {
                    parameterValue = param.Elements().Aggregate("", (xmlText, el) => xmlText + el.ToString());
                }

                result.Add(keyAttr.Value, parameterValue);
            }

            return new Configuration(result);
        }
Esempio n. 14
0
        public List<MyFitnessXML> GetValues(XDocument xDoc)
        {
            var Chart_DataL = from c in xDoc.Elements("chart").Elements("chart_data").Elements("row")
                              select c;

            var Chart_DataStrings = from c in Chart_DataL
                                    where c.Element("string") != null
                                    select c.Elements("string");

            var Chart_DataNumbers = from c in Chart_DataL
                                    where c.Element("number") != null
                                    select c.Elements("number");

             List<MyFitnessXML> XMLList = new List<MyFitnessXML>();

            //Start at 1 to avoid first record is 0 bug
            for (int i = 1; i < Chart_DataStrings.ElementAt(0).Count(); i++)
            {

                XMLList.Add(new MyFitnessXML
                {
                    StringValue = (string)Chart_DataStrings.ElementAt(0).ElementAt(i),
                    NumberValue = (double)Chart_DataNumbers.ElementAt(0).ElementAt(i)
                });
            }

            return XMLList;
        }
        /**
* @name populateLookup
*
* @desc
*
* @param xml - IN -
* @return None
*/
        private void populateLookup(XDocument xml)//XDocument xml
        {
            IEnumerable<XElement> elements = null;


            if (xml.Element("TACTICALGRAPHICS").HasElements) //"SINGLEPOINTMAPPINGS"
            {
                elements = xml.Elements();

                IEnumerator<XElement> itr = null;// = xml.DescendantNodes().GetEnumerator();
                //XElement unitConstants = XElement.Load(ofd1.FileName, LoadOptions.None);
                itr = elements.GetEnumerator();


                XElement child = null;
                itr.MoveNext();
                child = itr.Current;//TACTICALGRAPHICS
                if (child.HasElements)
                {
                    elements = child.Elements();
                    itr = elements.GetEnumerator();//SYMBOL
                    while (itr.MoveNext())
                    {
                        child = itr.Current;                                                                        /*SymbolDef .XNodeToSymbolDef*/
                        TacticalGraphicLookupInfo temp = TacticalGraphicLookupInfo.XNodeToTGLookupInfo(child);// SPSymbolDef temp = SPSymbolDef.XNodeToSPSymbolDef(child);
                        if ((temp != null) && _TGLookup.ContainsKey(temp.getBasicSymbolID()) == false)//temp will be null if node is an XCOMMENT
                            _TGLookup[temp.getBasicSymbolID()] = temp.getMapping();

                    }//end while
                }
            }//end if
        }
Esempio n. 16
0
 /// <summary>
 /// When an XML document is loaded, this methods scanns the XDocument for any namespace declarations. When it finds a namespace declation
 /// it is added to the Namespace attribute, in order to keep track of all namespaces.
 /// </summary>
 /// <param name="doc"></param>
 public void CheckXDocumentForNamespaces(XDocument doc)
 {
     ClearNamespaces();
     foreach (XElement node in doc.Elements())
     {
         CheckNodeForNamespace(node);
     }
 }
Esempio n. 17
0
 public List<XElement> QueryData(XDocument doc)
 {
     IEnumerable<XElement> queryResult =
     from el in doc.Elements()
     select el;
       List<XElement> queryResults = queryResult.ToList();
       return queryResults;
 }
 private static string GetAssemblyName(XDocument document) {
     return document
         .Elements(ns("Project"))
         .Elements(ns("PropertyGroup"))
         .Elements(ns("AssemblyName"))
         .Single()
         .Value;
 }
 private static IEnumerable<string> GetSourceFilenames(XDocument document) {
     return document
         .Elements(ns("Project"))
         .Elements(ns("ItemGroup"))
         .Elements(ns("Compile"))
         .Attributes("Include")
         .Select(c => c.Value);
 }
Esempio n. 20
0
 //--------------------------------------------------------------
 //By: Ryan Moe
 //Edited Last:
 //
 //Search an XDocuments's decendants.
 //PARAM 1 = the parent XDocument to search from.
 //PARAM 2 = the children element's name to search the parent for.
 //RETURNS = a list of XElements that you were looking for.
 public List<XElement> searchForElements(XDocument parent, string lookingFor)
 {
     List<XElement> _list = new List<XElement>();
     foreach (XElement subElement in parent.Elements(lookingFor))
     {
         _list.Add(subElement);
     }//foreach
     return _list;
 }
Esempio n. 21
0
        public static DbConnection GetDbConnection(string which, XDocument requestBody)
        {
            OdbcDrivers type;
            var conn = (from element in requestBody
                            .Elements("RegistrationRequest")
                            .Elements(which)
                        select element).ToList();

            if (conn.Count == 0)
            {
                if (which == "Metabase")
                {
                    return null;
                }

                throw new Exception(String.Format("Database was not correctly defined ({0}).", which));
            }

            var connType = (from element in conn
                            select (string)element.Attribute("type")).SingleOrDefault();

            if (connType != null && !connType.EndsWith("Connection"))
            {
                connType = connType + "Connection";
            }

            if (!OdbcDrivers.TryParse(connType, true, out type))
            {
                throw new Exception(String.Format("Database was not correctly defined (type of {0}).", which));
            }

            switch (type)
            {
                case OdbcDrivers.AccessConnection:
                    return (from element in conn
                            select
                                new DbConnection
                                {
                                    Type = type,
                                    Filename = (string)element.Element("File")
                                }).SingleOrDefault();
                case OdbcDrivers.MySqlConnection:
                    return (from element in conn
                            select
                                new DbConnection
                                {
                                    Type = type,
                                    Server = (string)element.Element("Server"),
                                    Database = (string)element.Element("Database"),
                                    Username = (string)element.Element("Username"),
                                    Password = (string)element.Element("Password")
                                }).SingleOrDefault();
            }

            throw new Exception(String.Format("Database was not correctly defined ({0}).", which));
        }
Esempio n. 22
0
		public void AddXTextElementCloning ()
		{
			XDocument document = new XDocument (new XElement ("root", "This is the root"));
			Assert.IsNotNull (document);
			Assert.IsNotNull (document.Elements ().First ());

			XDocument newDocument = new XDocument (document.Root);
			Assert.IsNotNull (newDocument);
			Assert.IsNotNull (newDocument.Elements ().First ());
		}
Esempio n. 23
0
        private static void RecreateComputer(XDocument save)
        {
            var isRedHuman = from game in save.Elements("game")
                            select new
                            {
                                isHuman = (bool)game.Attribute("isRedHuman")
                            };

            _recreation.IsRedHuman = isRedHuman.ElementAt(0).isHuman;
        }
Esempio n. 24
0
        /// <summary>
        ///     Loads the document from an XDocument
        /// </summary>
        /// <param name="extent">Extent to which the data is loaded</param>
        /// <param name="document">Document to be loaded</param>
        public void Load(IUriExtent extent, XDocument document)
        {
            _idToElement.Clear();

            // Skip the first element
            foreach (var element in document.Elements().Elements())
            {
                extent.elements().add(LoadElement(element));
            }
        }
Esempio n. 25
0
        public void SaveSettings(string fileName, XElement extras = null)
        {
            System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(GetSettings());

            if (extras != null)
            {
                doc.Elements("settings").ElementAtOrDefault(0).Add(extras);
            }

            doc.Save(fileName);
        }
        public override PictureDataItem GetPictureDataItemFromXDocument(System.Xml.Linq.XDocument doc)
        {
            var rssItem = (from el in doc.Elements("rss").Elements("channel").Elements("item")
                           where String.Equals(el.Element("category").Value, "Image of the Day,The Scientist")
                           select new
            {
                Title = el.Element("title").Value,
                Link = el.Element("link").Value,
                Category = el.Element("category").Value,
            }).First();


            var title   = rssItem.Title;
            var pattern = @"(?<=Image of the Day: ).+";
            var match   = Regex.Match(title, pattern);

            if (!match.Success)
            {
                throw new Exception(string.Format("Unable to parse title using regex:\r\n{0}.", title));
            }
            title = match.Value;

            var    link = new Uri(rssItem.Link);
            string contents;

            using (var wc = new System.Net.WebClient())
                contents = wc.DownloadString(link);

            //System.IO.File.WriteAllText(@"c:\temp\1.html", contents);

            var tokenStart = "src=\"/images/ImageoftheDay/";
            var tokenEnd   = "\"";
            int start      = contents.IndexOf(tokenStart, System.StringComparison.Ordinal);

            if (start == -1)
            {
                throw new Exception(string.Format("Could not find '{0}' start token in rssItem link html.", tokenStart));
            }
            start += 5;
            int end = contents.IndexOf(tokenEnd, start, System.StringComparison.Ordinal);

            if (end == -1)
            {
                throw new Exception(string.Format("Could not find '{0}' end token in rssItem link html.", tokenEnd));
            }
            Uri uri = new Uri(link.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped) + contents.Substring(start, end - start), UriKind.Absolute);

            var imageUrl = uri.AbsoluteUri;

            return(new PictureDataItem()
            {
                Title = title, Uri = new Uri(imageUrl, UriKind.Absolute)
            });
        }
        public string[] GetTranslationKeys(XDocument xDoc)
        {
            var langElements = xDoc.Elements("languages").Elements("language");
            var keys =
                (langElements.SelectMany(lang => lang.Elements(), (lang, category) => new { lang, category })
                    .SelectMany(@t => @t.category.Elements(),
                        (@t, translation) => $"/{@t.category.Name}/{translation.Name.ToString()}")
                    ).Distinct().ToArray();

            return keys;
        }
Esempio n. 28
0
		public void Run(XamlContext ctx, XDocument document) {
			key = ctx.GetXamlNsName("Key");

			bool doWork;
			do {
				doWork = false;
				foreach (var elem in document.Elements()) {
					doWork |= ProcessElement(ctx, elem);
				}
			} while (doWork);
		}
Esempio n. 29
0
 /// <param name="filePath">XML file path</param>
 /// <param name="loginUserRole">Role as string</param>
 /// <param name="menuType">Menu drop down orientation</param>
 /// <param name="title">Title in case of Verticale orientation</param>
 public UtilMenu(string menuUlID, System.Web.UI.Page page, string filePath, string loginUserRole, MenuTypes orientation = MenuTypes.Horizontal, string title = "", Dictionary<string, bool> permissions = null)
 {
     _menuUlID = menuUlID;
     _page = page;
     _loginUserRole = loginUserRole;
     _permissions = permissions;
     _doc = XDocument.Load(filePath);
     _eles = from e in _doc.Elements("menu").Elements("menuitem")
             select e;
     _menuType = orientation;
     _title = title;
 }
Esempio n. 30
0
        //------------------------------------------------------------------------------------------------
        //新規登録フォームのデータをXmlに書き込む
        //------------------------------------------------------------------------------------------------
        public void NewDataAdd()
        {
            var Root      = "";
            var Degree    = "";
            var Position1 = "";
            var Position2 = "";
            var Position3 = "";
            var Position4 = "";
            var BarreFlg  = "";
            var Barre     = "";
            var High      = "";

            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database());

            //Xmlファイルに書き込み
            Root      = textBox1_Root.Text;
            Degree    = textBox1_degree.Text;;
            Position1 = textBox_position1.Text;
            Position2 = textBox3_position2.Text;
            Position3 = textBox2_position3.Text;
            Position4 = textBox5_position4.Text;
            BarreFlg  = textBox6_barreflg.Text;
            Barre     = textBox7_barre.Text;
            High      = textBox8_high.Text;

            try
            {
                var query = (from y in XmlDoc.Descendants("Chord")
                             select y);

                int Count = query.Elements("Chord").Count();

                var writeXml = new XElement("Chord",
                                            new XAttribute("ID", Count + 1),
                                            new XElement("Root", Root),
                                            new XElement("Degree", Degree),
                                            new XElement("Position1", Position1),
                                            new XElement("Position2", Position2),
                                            new XElement("Position3", Position3),
                                            new XElement("Position4", Position4),
                                            new XElement("BarreFlg", BarreFlg),
                                            new XElement("Barre", Barre),
                                            new XElement("High", High));

                XmlDoc.Elements().First().Add(writeXml);
                XmlDoc.Save(createConfigXML.CurrentPath_database());
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 31
0
        public override PictureDataItem GetPictureDataItemFromXDocument(System.Xml.Linq.XDocument doc)
        {
            var rssItem = (from el in doc.Elements("rss").Elements("channel").Elements("item")
                           select new
            {
                Title = el.Element("title").Value,
                Link = el.Element("link").Value,
                Description = el.Element("description").Value
            }).Single();


            var desc       = rssItem.Description;
            var tokenStart = "<a href=\"";
            var tokenEnd   = "\"";
            int start      = desc.IndexOf(tokenStart, System.StringComparison.Ordinal);

            if (start == -1)
            {
                throw new Exception(string.Format("Could not find '{0}' start token in rssItem description.", tokenStart));
            }
            start += tokenStart.Length;
            int end = desc.IndexOf(tokenEnd, start, System.StringComparison.Ordinal);

            if (end == -1)
            {
                throw new Exception(string.Format("Could not find '{0}' end token in rssItem description.", tokenEnd));
            }
            Uri uriHost = new Uri(desc.Substring(start, end - start), UriKind.Absolute);

            string contents;

            using (var wc = new System.Net.WebClient())
                contents = wc.DownloadString(uriHost);

            //System.IO.File.WriteAllText(@"c:\temp\1.html", contents);

            //contents = File.ReadAllText(@"c:\temp\1.html");

            var pattern = "(?<=<img class=[\"|']wall_img)(?:.+) src=[\"|'](?<URL>\\S+)[\"|']";
            var match   = Regex.Match(contents, pattern);

            if (!match.Success)
            {
                throw new Exception("Unable to find <img> using regex");
            }
            Uri uriImage = new Uri(uriHost.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped) + match.Groups["URL"].Value, UriKind.Absolute);

            return(new PictureDataItem()
            {
                Title = rssItem.Title, Uri = uriImage
            });
        }
Esempio n. 32
0
 public static List<MenuModel> GetMenus(XDocument document)
 {
     List<MenuModel> menus = new List<MenuModel>();
     List<XElement> siteMapNodes = (from map in document.Elements("siteMap").Elements("siteMapNode")
                                    select map).ToList();
     MenuModel menu = null;
     foreach (var siteMap in siteMapNodes) {
         menu = GetMenu(siteMap);
         LoadMenus(siteMap, ref menu);
         menus.Add(menu);
     }
     return menus;
 }
Esempio n. 33
0
        static void AddMissingReferencesToReferenceCollection(XDocument projectFile, ReferenceCollection references)
        {
            var referencesInProject = from project in projectFile.Elements()
                                      from itemGroup in project.Elements(Msbuild.DefaultNamespace + "ItemGroup")
                                      from refElement in itemGroup.Elements()
                                      where refElement.Name == Msbuild.DefaultNamespace + "Reference"
                                            || refElement.Name == Msbuild.DefaultNamespace + "ProjectReference"
                                      select CreateReference(refElement);

            var newReferences = referencesInProject.Except(references).ToArray();

            newReferences.Each(references.Add);
        }
Esempio n. 34
0
        static EndpointAddress GetEndpointFromXML(XDocument XMLMapping)
        {
            EndpointAddress endpoint = null;
            //Examine the mappings and determine if we can map the volume
            IEnumerable<XElement> VolumeElements = XMLMapping.Elements().Where(elem => elem.Name.LocalName == "Volume");

            foreach (XElement elem in VolumeElements)
            {
                //Fetch the name if we know it
                switch (elem.Name.LocalName)
                {
                    case "Volume":
                        IEnumerable<XElement> SettingsElements = elem.Elements().Where(e => e.Name.LocalName == "DefaultWebAnnotationUserSettings");
                        if (SettingsElements.Count() > 0)
                        {
                            //UserSettingsElement = SettingsElements.First();
                        }

                        IEnumerable<XElement> MappingElements = elem.Elements().Where(e => e.Name.LocalName == "VolumeToEndpoint");

                        if (MappingElements.Count() == 0)
                            break;

                        XElement MappingElement = MappingElements.First();

                        XAttribute EndpointAttribute = MappingElement.Attribute("Endpoint");
                        if (EndpointAttribute == null)
                            break;

                        /*
                        XAttribute AuthenticationAttribute = MappingElement.Attribute("Authentication");
                        if (AuthenticationAttribute != null)
                        {
                            Global._AuthenticationAddress = new EndpointAddress(AuthenticationAttribute.Value);
                            ValidateUser();
                        }
                        */
            #if DEBUG
                        endpoint = new EndpointAddress(EndpointAttribute.Value);
                        //                        WebAnnotationModel.State.EndpointAddress = new EndpointAddress("https://connectomes.utah.edu/Services/TestBinary/Annotate.svc");
            #else
                        WebAnnotationModel.State.EndpointAddress = new EndpointAddress(EndpointAttribute.Value);
            #endif
                        return endpoint;
                    default:
                        break;
                }
            }

            return endpoint;
        }
Esempio n. 35
0
        protected override void LoadFromDoc(System.Xml.Linq.XDocument doc)
        {
            _weatherSet = new UndoAwareObservableCollection <WeatherTimeRange>(this);
            //WeatherSet.AllowNew = false;
            XElement root = (XElement)doc.FirstNode;

            XElement rootProps = doc.Elements().First().Element(FileDescriptions.FILE_GENERAL_EL_PROPS);

            if (rootProps != null)
            {
                _header = rootProps.Attribute(FileDescriptions.FILE_WEATHER_AT_PROPS_HEADER).Read <string>(string.Empty);
            }

            XElement illumination = root.Element(FileDescriptions.FILE_WEATHER_EL_ILLUMINATION);

            Illumination = AmbientIllumination.ReadFromXml(illumination, this, OwnPath);
            if (Illumination == null)
            {
                Illumination = new AmbientIllumination(this);
            }

            var set = root.Element(FileDescriptions.FILE_WEATHER_EL_WEATHER_SET);

            if (set != null)
            {
                List <WeatherTimeRange> tempL = new List <WeatherTimeRange>();
                foreach (XElement timeRange in set.Elements(FileDescriptions.FILE_WEATHER_EL_TIME_RANGE))
                {
                    WeatherTimeRange r = WeatherTimeRange.ReadFromXml(timeRange, this, OwnPath);
                    if (r != null)
                    {
                        tempL.Add(r);
                    }
                }
                foreach (var it in tempL.OrderBy(w => w.Begin))
                {
                    _weatherSet.Add(it);
                }
            }

            ClearUndoRedo();
        }
Esempio n. 36
0
        //------------------------------------------------------------------------------------------------
        //DataGridviewのデータをXmlに書き込む
        //------------------------------------------------------------------------------------------------
        public void WriteXml()
        {
            int RowCount  = dataGridView1.RowCount;
            var Root      = "";
            var Degree    = "";
            var Position1 = "";
            var Position2 = "";
            var Position3 = "";
            var Position4 = "";
            var BarreFlg  = "";
            var Barre     = "";
            var High      = "";

            XElement query;

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

            //Xmlファイルに書き込み
            for (int i = 0; i < RowCount; i++)
            {
                Root      = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
                Degree    = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value);
                Position1 = Convert.ToString(dataGridView1.Rows[i].Cells[3].Value);
                Position2 = Convert.ToString(dataGridView1.Rows[i].Cells[4].Value);
                Position3 = Convert.ToString(dataGridView1.Rows[i].Cells[5].Value);
                Position4 = Convert.ToString(dataGridView1.Rows[i].Cells[6].Value);
                BarreFlg  = Convert.ToString(dataGridView1.Rows[i].Cells[7].Value);
                Barre     = Convert.ToString(dataGridView1.Rows[i].Cells[8].Value);
                High      = Convert.ToString(dataGridView1.Rows[i].Cells[9].Value);

                try
                {
                    var writeXml = new XElement("Data",
                                                new XAttribute("ID", i + 1),
                                                new XElement("Root", ""),
                                                new XElement("Degree", ""),
                                                new XElement("Position1", ""),
                                                new XElement("Position2", ""),
                                                new XElement("Position3", ""),
                                                new XElement("Position4", ""),
                                                new XElement("BarreFlg", ""),
                                                new XElement("Barre", ""),
                                                new XElement("High", ""));

                    XmlDoc.Elements().First().Add(writeXml);
                    XmlDoc.Save(createConfigXML.CurrentPath_database());

                    //データグリッドビューの値をXmlに書き込み
                    query = (from y in XmlDoc.Descendants("Chord")
                             where y.Attribute("ID").Value == Convert.ToString(i + 1)
                             select y).Single();

                    query.Element("Root").Value      = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
                    query.Element("Degree").Value    = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value);
                    query.Element("Position1").Value = Convert.ToString(dataGridView1.Rows[i].Cells[3].Value);
                    query.Element("Position2").Value = Convert.ToString(dataGridView1.Rows[i].Cells[4].Value);
                    query.Element("Position3").Value = Convert.ToString(dataGridView1.Rows[i].Cells[5].Value);
                    query.Element("Position4").Value = Convert.ToString(dataGridView1.Rows[i].Cells[6].Value);
                    query.Element("BarreFlg").Value  = Convert.ToString(dataGridView1.Rows[i].Cells[7].Value);
                    query.Element("Barre").Value     = Convert.ToString(dataGridView1.Rows[i].Cells[8].Value);
                    query.Element("High").Value      = Convert.ToString(dataGridView1.Rows[i].Cells[9].Value);



                    XmlDoc.Save(createConfigXML.CurrentPath_database());
                }
                catch (Exception ex)
                {
                }
            }
        }