Example #1
0
File: Locator.cs Project: ngeor/xdt
        public static string GetLocatorPredicate(XElement element)
        {
            var locatorAttribute = element.Attributes(Namespaces.Xdt + "Locator").FirstOrDefault();

            if (locatorAttribute == null)
            {
                return String.Empty;
            }
            else
            {
                var locator = Locator.Parse(locatorAttribute.Value);

                if (locator.Type == "Condition")
                {
                    // use the user-defined value as an xpath predicate
                    return "[" + locator.Arguments + "]";
                }
                else if (locator.Type == "Match")
                {
                    // convenience case of the Condition locator, build the xpath
                    // predicate for the user by matching on all specified attributes

                    var attributeNames = locator.Arguments.Split(',').Select(s => s.Trim());
                    var attributes = element.Attributes().Where(a => attributeNames.Contains(a.Name.LocalName));

                    return "[" + attributes.ToConcatenatedString(a =>
                        "@" + a.Name.LocalName + "='" + a.Value + "'", " and ") + "]";
                }
                else
                {
                    throw new NotImplementedException(String.Format("The Locator '{0}' is not supported", locator.Type));
                }
            }
        }
        public void ProcessElement(XElement element)
        {
            if (!IsEnabled) return;
            if (!element.HasAttributes) return;

            // Setter? Format "Value" attribute if "Property" atribute matches ThicknessAttributeNames
            if (element.Name == SetterName)
            {
                var propertyAttribute = element.Attributes("Property").FirstOrDefault();
                if (propertyAttribute != null && ThicknessAttributeNames.Any(match => match.IsMatch(propertyAttribute.Value)))
                {
                    var valueAttribute = element.Attributes("Value").FirstOrDefault();
                    if (valueAttribute != null)
                    {
                        FormatAttribute(valueAttribute);
                    }
                }
            }
            // Not setter. Format value of all attributes where attribute name matches ThicknessAttributeNames
            else
            {
                foreach (var attribute in element.Attributes())
                {
                    var isMatchingAttribute = ThicknessAttributeNames.Any(match => match.IsMatch(attribute.Name));
                    if (isMatchingAttribute)
                    {
                        FormatAttribute(attribute);
                    }
                }
            }
        }
Example #3
0
		MatchFactory GetRegexes(XElement element) {
			switch (element.Name.LocalName) {
				case "MatchHonorees":
					if (Presentation.MelaveMalka == null)
						return FixedRegexes();
					return FixedRegexes(Presentation.MelaveMalka.Honorees.SelectMany(AdVerifier.GetNameRegexes));
				case "MatchDonors":
					return ad => ad.Row.Pledges.SelectMany(p => AdVerifier.GetNameRegexes(p.Person));
				case "Match":
					return FixedRegexes(new Regex(element.Attribute("Regex").Value));
				case "MatchPerson":
					foreach (var field in element.Attributes())
						if (!Person.Schema.Columns.Contains(field.Name.LocalName))
							throw new ConfigurationException($"Unexpected attribute {field} in <MatchPerson>");
					var fields = element.Attributes().ToDictionary(
						a => a.Name.LocalName,
						a => a.Value
					);
					var people = Program.Table<Person>().Rows.Where(p => fields.All(f => f.Value.Equals(p[f.Key])));
					if (people.Has(2))
						throw new ConfigurationException($"Format rule {element} matches multiple people: {people.Join(", ", p => p.VeryFullName)}");
					var person = people.FirstOrDefault();
					if (person == null)
						throw new ConfigurationException($"Format rule {element} doesn't match anyone in the master directory.");
					return FixedRegexes(AdVerifier.GetNameRegexes(person));
				case "Format":  // Ignore this element.
					return FixedRegexes();
				default:
					throw new ConfigurationException($"Unexpected <{element.Name}> element in <FormatRule>.");
			}
		}
        private static bool BasicValueTypeAttributeCheckIsValid(XElement element, bool isCustomProperty, out string value)
        {
            Guard.AgainstNull(element, "element");

            if (isCustomProperty)
            {
                if (element.Attributes().Count() != 2)
                {
                    value = "Wrong number of attributes";
                    return false;
                }
                if (element.Attribute(SharedConstants.Name) == null)
                {
                    value = "Custom property has no 'name' attribute";
                    return false;
                }
            }
            else
            {
                if (element.Attributes().Count() != 1)
                {
                    value = "Wrong number of attributes";
                    return false;
                }
            }
            value = element.Attribute(SharedConstants.Val).Value;
            return true;
        }
Example #5
0
 public DslBuilder(XElement builderClassNode, XmlDocCommentReader commentReader, Type builderType)
 {
     input = builderClassNode.Value;
     syntaxStateClassname = builderClassNode.Attributes().Single(f => f.Name == "name").Value;
     outputNamespace = builderClassNode.Attributes().Single(f => f.Name == "namespace").Value;
     type = builderType;
     this.commentReader = commentReader;
 }
        private static string ElementToLevelText(XElement el)
        {
            var blueText = el.Attributes().Any( a => a.Name == "Text") ? el.Attribute("Text").Value : string.Empty;
            var blueAmount = el.Attributes().Any(a => a.Name == "AMOUNT") ? el.Attribute("AMOUNT").Value : string.Empty;
            var blueType = el.Attributes().Any(a => a.Name == "TYPE") ? el.Attribute("TYPE").Value : string.Empty;

            return blueText +" : "+ blueAmount + " " + blueType;
        }
Example #7
0
		void SetMathVariant(XElement mathVariant)
		{
			string name = mathVariant.Attribute("name").Value;
			string weight = mathVariant.Attributes("weight").FirstOrDefault() != null ? mathVariant.Attribute("weight").Value : "normal";
			string style = mathVariant.Attributes("style").FirstOrDefault() != null ? mathVariant.Attribute("style").Value : "normal";
			MathVariant mv = new MathVariant(name, weight, style);
			mathVariant.Attribute("family").Value.Split(',').Select(x => x.Trim()).ToList().ForEach(x=> mv.AddFamily(x));
			Variants.Add(name, mv);
		}
Example #8
0
		/// <summary>
		/// Updates an element from the datasource.
		/// </summary>
		/// <param name="table"></param>
		/// <param name="element"></param>
		public void UpdateElement(IList<XElement> table, XElement element)
		{
			XElement orderToUpdate = (from order in table
									  where order.Attribute(element.Attributes().FirstOrDefault().Name).Value == element.Attributes().FirstOrDefault().Value
									  select order).FirstOrDefault();
			foreach (XElement el in orderToUpdate.Descendants())
			{
				el.Value = element.Element(el.Name).Value;
			}
		}
Example #9
0
                /// <summary>
                /// Tests the Add methods on Container.
                /// </summary>
                /// <param name="context"></param>
                /// <returns></returns>
                //[Variation(Desc = "ContainerAdd")]
                public void ContainerAdd()
                {
                    XElement element = new XElement("foo");

                    // Adding null does nothing.
                    element.Add(null);
                    Validate.Count(element.Nodes(), 0);

                    // Add node, attrbute, string, some other value, and an IEnumerable.
                    XComment comment = new XComment("this is a comment");
                    XComment comment2 = new XComment("this is a comment 2");
                    XComment comment3 = new XComment("this is a comment 3");
                    XAttribute attribute = new XAttribute("att", "att-value");
                    string str = "this is a string";
                    int other = 7;

                    element.Add(comment);
                    element.Add(attribute);
                    element.Add(str);
                    element.Add(other);
                    element.Add(new XComment[] { comment2, comment3 });

                    Validate.EnumeratorDeepEquals(
                        element.Nodes(),
                        new XNode[] { comment, new XText(str + other), comment2, comment3 });

                    Validate.EnumeratorAttributes(element.Attributes(), new XAttribute[] { attribute });

                    element.RemoveAll();
                    Validate.Count(element.Nodes(), 0);

                    // Now test params overload.
                    element.Add(comment, attribute, str, other);

                    Validate.EnumeratorDeepEquals(
                        element.Nodes(),
                        new XNode[] { comment, new XText(str + other) });

                    Validate.EnumeratorAttributes(element.Attributes(), new XAttribute[] { attribute });

                    // Not allowed to add a document as a child.
                    XDocument document = new XDocument();
                    try
                    {
                        element.Add(document);
                        Validate.ExpectedThrow(typeof(ArgumentException));
                    }
                    catch (Exception ex)
                    {
                        Validate.Catch(ex, typeof(ArgumentException));
                    }
                }
Example #10
0
        public KevinBaconItem(XElement element)
        {
            _actorName = element.Attributes("name").First().Value + " (" + element.Elements("link").Count() + ")";
            _description = element.Attributes("name").First().Value;
            var links = element.Elements("link").Select(linkElement => " to " + linkElement.Attributes("actor").First().Value
                                                           + " in " + linkElement.Attributes("movie").First().Value);
            _description += "\r\n";
            foreach (var link in links)
            {
                _description += "\r\n" + link;
            }

            _description += "\r\n";
        }
        private static dynamic CreateChildElement(XElement parent)
        {
            if (parent.Attributes().Count() == 0 && parent.Elements().Count() == 0)
                return null;

            IDictionary<string, object> child = new ExpandoObject();

            parent.Attributes().ToList().ForEach(attr =>
            {
                child.Add(attr.Name.LocalName, attr.Value);

                if (!child.ContainsKey("NodeName"))
                    child.Add("NodeName", attr.Parent.Name.LocalName);
            });

            parent.Elements().ToList().ForEach(childElement =>
            {
                var grandChild = CreateChildElement(childElement);

                if (grandChild != null)
                {
                    string nodeName = grandChild.NodeName;
                    if (child.ContainsKey(nodeName) && child[nodeName].GetType() != typeof(List<dynamic>))
                    {
                        var firstValue = child[nodeName];
                        child[nodeName] = new List<dynamic>();
                        ((dynamic)child[nodeName]).Add(firstValue);
                        ((dynamic)child[nodeName]).Add(grandChild);
                    }
                    else if (child.ContainsKey(nodeName) && child[nodeName].GetType() == typeof(List<dynamic>))
                    {
                        ((dynamic)child[nodeName]).Add(grandChild);
                    }
                    else
                    {
                        child.Add(childElement.Name.LocalName, CreateChildElement(childElement));
                        if (!child.ContainsKey("NodeName"))
                            child.Add("NodeName", parent.Name.LocalName);
                    }
                }
                else
                {
                    child.Add(childElement.Name.LocalName, childElement.Value);
                    if (!child.ContainsKey("NodeName"))
                        child.Add("NodeName", parent.Name.LocalName);
                }
            });

            return child;
        }
Example #12
0
        public PendingUpdate(XElement updateXml)
        {
            var rawVersion = updateXml
                   .Attributes("NewVersion")
                   .Select(a => a.Value)
                   .FirstOrDefault();

            NewVersion = new Version(rawVersion);

            var rawUpdateFileUri = updateXml
                   .Attributes("UpdateFileUri")
                   .Select(a => a.Value)
                   .FirstOrDefault();

            UpdateFileUri = new Uri(rawUpdateFileUri);

            var rawInfoFileUri = updateXml
                   .Attributes("UpdateInfoUri")
                   .Select(a => a.Value)
                   .FirstOrDefault();

            if (rawInfoFileUri != null)
            {
                UpdateInfoUri = new Uri(rawInfoFileUri);
            }

            var rawCategories = updateXml
                   .Attributes("Categories")
                   .Select(a => a.Value)
                   .FirstOrDefault();

            Categories = rawCategories == null
                ? new List<string>()
                : new List<string>(rawCategories.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));

            InstallFileName = updateXml
                   .Attributes("InstallFileName")
                   .Select(a => a.Value)
                   .FirstOrDefault();

            var descriptionNode = updateXml
                .Elements("Description")
                .FirstOrDefault();

            if (descriptionNode != null)
            {
                Description = descriptionNode.Value;
            }
        }
        public IOperand CreateFieldRefOperand(XElement el)
        {
            if (el == null)
            {
                throw new ArgumentNullException("el");
            }
            Guid? id = null;
            var idAttr = el.Attributes().FirstOrDefault(a => a.Name == Attributes.ID);
            if (idAttr != null)
            {
                try
                {
                    id = new Guid(idAttr.Value);
                }
                catch
                {
                    throw new CamlAnalysisException(string.Format("Value '{0}' is not correct for attribute '{1}'", idAttr.Value, Attributes.ID));
                }
            }

            string name = null;
            var nameAttr = el.Attributes().FirstOrDefault(a => a.Name == Attributes.Name);
            if (nameAttr != null)
            {
                name = nameAttr.Value;
            }

            if (id != null && !string.IsNullOrEmpty(name))
            {
                throw new CamlAnalysisException(string.Format("Only one from two attributes should be specified: {0} or {1}", Attributes.ID, Attributes.Name));
            }

            if (id == null && string.IsNullOrEmpty(name))
            {
                throw new CamlAnalysisException(string.Format("At least one from two attributes should be specified: {0} or {1}", Attributes.ID, Attributes.Name));
            }

            var attributes = el.Attributes().Where(
                attr =>
                {
                    return (attr.Name != Attributes.ID && attr.Name != Attributes.Name &&
                            !string.IsNullOrEmpty(attr.Value));
                })
                    .Select(attr => new KeyValuePair<string, string>(attr.Name.ToString(), attr.Value))
                    .ToList();

            return (id != null ? new FieldRefOperand(id.Value, attributes) : new FieldRefOperand(name, attributes));
        }
Example #14
0
 public BookModel ConvertXmlToBookModel(XElement book)
 {
     XElement publisher = book.Elements().Where(x => x.Name == "publisher").FirstOrDefault();
     return new BookModel()
     {
         ISBN = book.Attributes().Where(x => x.Name == "isbn").FirstOrDefault().Value,
         ISBN13 = book.Attributes().Where(x => x.Name == "isbn13").FirstOrDefault().Value,
         Title = book.Elements().Where(x => x.Name == "title").FirstOrDefault().Value,
         Author = book.Elements().Where(x => x.Name == "author").FirstOrDefault().Value,
         Publisher = new Publisher()
         {
             Id = publisher.Attributes().Where(x => x.Name == "publisher_id").FirstOrDefault().Value,
             Name = publisher.Value
         }
     };
 }
Example #15
0
        public static XElement MergeWith(this XElement source, XElement target, IDictionary<XName, Action<XElement, XElement>> nodeActions)
        {
            if (target == null) {
                return source;
            }

            // Merge the attributes
            foreach (var targetAttribute in target.Attributes()) {
                var sourceAttribute = source.Attribute(targetAttribute.Name);
                if (sourceAttribute == null) {
                    source.Add(targetAttribute);
                }
            }

            // Go through the elements to be merged
            foreach (var targetChild in target.Elements()) {
                var sourceChild = FindElement(source, targetChild);
                if (sourceChild != null && !HasConflict(sourceChild, targetChild)) {
                    // Other wise merge recursively
                    sourceChild.MergeWith(targetChild, nodeActions);
                }
                else {
                    Action<XElement, XElement> nodeAction;
                    if (nodeActions != null && nodeActions.TryGetValue(targetChild.Name, out nodeAction)) {
                        nodeAction(source, targetChild);
                    }
                    else {
                        // If that element is null then add that node
                        source.Add(targetChild);
                    }
                }
            }
            return source;
        }
		bool RewriteElement(XamlContext ctx, XElement parent, XElement elem) {
			var type = parent.Annotation<XamlType>();
			var property = elem.Annotation<XamlProperty>();
			if ((property == null || type == null) && elem.Name != key)
				return false;

			if (elem.Elements().Count() != 1 || elem.Attributes().Any(t => t.Name.Namespace != XNamespace.Xmlns))
				return false;

			var value = elem.Elements().Single();

			if (!CanInlineExt(ctx, value))
				return false;

			var ext = InlineExtension(ctx, value);
			if (ext == null)
				return false;

			ctx.CancellationToken.ThrowIfCancellationRequested();

			var extValue = ext.ToString(ctx, parent);

			var attrName = elem.Name;
			if (attrName != key)
				attrName = property.ToXName(ctx, parent, property.IsAttachedTo(type));
			var attr = new XAttribute(attrName, extValue);
			parent.Add(attr);
			elem.Remove();

			return true;
		}
Example #17
0
 private static XElement createOutputNode(XElement inputNode, XDocument input)
 {
     var outputNode = new XElement(inputNode.Name);
     setAttributesWithParentsNames(inputNode, input.Root, outputNode);
     outputNode.Add(inputNode.Attributes());
     return outputNode;
 }
            private void CompareAttributes(XElement actualElement, XElement expectedElement)
            {
                var actualAttributes = new List<XAttribute>(actualElement.Attributes());
                var expectedAttributes = new List<XAttribute>(expectedElement.Attributes());
                for (int i1 = actualAttributes.Count - 1; i1 >= 0; i1--)
                {
                    for (int i2 = expectedAttributes.Count - 1; i2 >= 0; i2--)
                    {
                        if (actualAttributes[i1].Name == expectedAttributes[i2].Name)
                        {
                            if (actualAttributes[i1].Value != expectedAttributes[i2].Value)
                            {
                                var message = string.Format("Attribute '{0}' actual value '{1}' expected value '{2}'",
                                        actualAttributes[i1].LocalAttributeXPath(), actualAttributes[i1].Value, expectedAttributes[i2].Value);
                                Notify(l => l.DifferentAttributes(message));
                            }
                            actualAttributes.RemoveAt(i1);
                            expectedAttributes.RemoveAt(i2);
                            break;
                        }
                    }
                }

                foreach (var attribute in actualAttributes)
                {
                    var message = string.Format("Attribute '{0}' is only in the actual tree", attribute.LocalAttributeXPath());
                    Notify(l => l.DifferentAttributes(message));
                }

                foreach (var attribute in expectedAttributes)
                {
                    var message = string.Format("Attribute '{0}' is only in the expected tree", attribute.LocalAttributeXPath());
                    Notify(l => l.DifferentAttributes(message));
                }
            }
        public static MPD LoadMPD(XElement element)
        {
            var ns = element.GetDefaultNamespace().NamespaceName;
            var result = new MPD();

            result.Id = (string)element.Attribute("id");
            result.Profiles = (string)element.Attribute("profiles");
            result.Type = element.Attribute("type").GetEnum<Presentation>();
            result.AvailabilityStartTime = element.Attribute("availabilityStartTime").GetNullableDateTime();
            result.AvailabilityEndTime = element.Attribute("availabilityEndTime").GetNullableDateTime();
            result.MediaPresentationDuration = element.Attribute("mediaPresentationDuration").GetNullableDuration();
            result.MinimumUpdatePeriod = element.Attribute("minimumUpdatePeriod").GetNullableDuration();
            result.MinBufferTime = element.Attribute("minBufferTime").GetNullableDuration();
            result.TimeShiftBufferDepth = element.Attribute("timeShiftBufferDepth").GetNullableDuration();
            result.SuggestedPresentationDelay = element.Attribute("suggestedPresentationDelay").GetNullableDuration();
            result.MaxSegmentDuration = element.Attribute("maxSegmentDuration").GetNullableDuration();
            result.MaxSubsegmentDuration = element.Attribute("maxSubsegmentDuration").GetNullableDuration();
            result.AnyAttr.AddRange(element.Attributes());

            result.ProgramInformation.AddRange(element.Elements(XName.Get("ProgramInformation", ns)).Select(LoadProgramInformation));
            result.BaseURL.AddRange(element.Elements(XName.Get("BaseURL", ns)).Select(LoadBaseURL));
            result.Location.AddRange(element.Elements(XName.Get("Location", ns)).Select(e => e.Value));
            result.Period.AddRange(element.Elements(XName.Get("Period", ns)).Select(LoadPeriod));
            result.Metrics.AddRange(element.Elements(XName.Get("Metrics", ns)).Select(LoadMetrics));
            result.Any.AddRange(element.Elements());

            return result;
        }
Example #20
0
        private void AddNode(TreeNodeCollection parentTreeNodes, XElement element)
        {
            StringBuilder sb = new StringBuilder();

            string attrstring = string.Join(" ", element.Attributes().Select(a => a.Name + "=\"" + a.Value + "\""));
            if (attrstring != string.Empty)
            {
                sb.Append(" " + attrstring);
            }

            string innertext = element.Value;
            if (innertext != string.Empty)
            {
                sb.Append(" Value=\"" + innertext + "\"");
            }

            TreeNode treenode = new TreeNode();
            treenode.Text = element.Name.LocalName + sb.ToString();
            parentTreeNodes.Add(treenode);

            foreach (XElement child in element.Descendants())
            {
                AddNode(treenode.Nodes, child);
            }

            treenode.Expand();
        }
        private static bool HasIncludePath(XElement includeElement, string includePath)
        {
            XAttribute attr;
            attr = includeElement.Attributes(PathAttrName).Single();

            return attr != null && string.Equals(attr.Value, includePath, StringComparison.OrdinalIgnoreCase);
        }
 private IEnumerable<PlacementShapeLocation> AcceptPlace(XElement element) {
     // return attributes as part locations
     return element.Attributes().Select(attr => new PlacementShapeLocation {
         ShapeType = attr.Name.LocalName,
         Location = attr.Value
     });
 }
        private static InternalResult AreAttributesEqual(XElement xmlA, XElement xmlB)
        {
            var attributesB = xmlB.Attributes().Where(a => !a.IsNamespaceDeclaration).ToDictionary(a => a.Name);

            var attributesA = xmlA.Attributes().Where(a => !a.IsNamespaceDeclaration).ToList();

            if (attributesA.Count != attributesB.Count)
            {
                return new InternalResult
                {
                    FailObject = xmlA,
                    ErrorMessage = "Element has different number of attributes"
                };
            }

            foreach (var attributeA in attributesA)
            {
                XAttribute attributeB;
                if (attributesB.TryGetValue(attributeA.Name, out attributeB) && attributeA.Value == attributeB.Value)
                    continue;

                return new InternalResult
                {
                    FailObject = attributeA,
                    ErrorMessage = "No matching attribute found."
                };
            }

            return new InternalResult();
        }
        /// <summary>
        /// Uses XML to initialize the object.
        /// </summary>
        /// <param name="element">The element used for loading.</param>
        public override void LoadFromXml(XElement element)
        {
            //Attributes
            foreach (var attribute in element.Attributes())
            {
                if (attribute.Name.LocalName.Equals("walkspeed", StringComparison.OrdinalIgnoreCase))
                {
                    float value;

                    if (float.TryParse(attribute.Value, out value))
                    {
                        WalkSpeed = value;
                    }

                    continue;
                }

                if (attribute.Name.LocalName.Equals("runspeed", StringComparison.OrdinalIgnoreCase))
                {
                    float value;

                    if (float.TryParse(attribute.Value, out value))
                    {
                        RunSpeed = value;
                    }

                    continue;
                }
            }
        }
Example #25
0
        /// <summary>
        /// v3 serialization
        /// </summary>
        /// <param name="e"></param>
        public TranscriptionPhrase(XElement e)
        {
            Elements = e.Attributes().ToDictionary(a => a.Name.ToString(), a => a.Value);
            Elements.Remove("b");
            Elements.Remove("e");
            Elements.Remove("f");

            this._phonetics = (e.Attribute("f") ?? EmptyAttribute).Value;
            this._text = e.Value.Trim('\r', '\n');
            if (e.Attribute("b") != null)
            {
                string val = e.Attribute("b").Value;
                int ms;
                if (int.TryParse(val, out ms))
                {
                    Begin = TimeSpan.FromMilliseconds(ms);
                }
                else
                    Begin = XmlConvert.ToTimeSpan(val);

            }

            if (e.Attribute("e") != null)
            {
                string val = e.Attribute("e").Value;
                int ms;
                if (int.TryParse(val, out ms))
                {
                    End = TimeSpan.FromMilliseconds(ms);
                }
                else
                    End = XmlConvert.ToTimeSpan(val);
            }
        }
 /// <summary>
 /// Removes all namespaces from a XDocument
 /// </summary>
 /// <param name="e"></param>
 /// <returns></returns>
 /// <remarks>Borrowed from http://stackoverflow.com/a/7238007/41596</remarks>
 public static XElement RemoveAllNamespaces(XElement e)
 {
     return new XElement(e.Name.LocalName,
                         (from n in e.Nodes()
                          select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)),
                         (e.HasAttributes) ? (from a in e.Attributes() select a) : null);
 }
 protected virtual SiteMapNode CreateNodeFromElement(XElement element, int currentLevel)
 {
     string str;
     NameValueCollection attributes = new NameValueCollection();
     foreach (XAttribute attribute in element.Attributes())
     {
         attributes.Add(attribute.Name.ToString(), attribute.Value);
     }
     try
     {
         if (element.Attribute("uri") != null)
         {
             str = element.Attribute("uri").Value;
         }
         else if (element.Attribute("pageId") != null)
         {
             str = element.Attribute("pageId").Value;
         }
         else if (element.Attribute("id") != null)
         {
             str = element.Attribute("id").Value;
         }
         else
         {
             str = "";
         }
     }
     catch
     {
         LoggerService.Debug("exception while retrieving uri", LoggingCategory.General, new object[0]);
         str = "";
     }
     return new TridionSiteMapNode(this, element.Attribute("id").Value, str, element.Attribute("url").Value, element.Attribute("title").Value, "", null, attributes, null, null) { Level = currentLevel };
 }
        private void GenerateCommandCallTree(XElement element, CommandCall parentCommandCall, Resource resource)
        {
            bool isCommandAssigned = false;

            foreach (XAttribute attribute in element.Attributes())
            {
                string namespaceURI = attribute.Name.Namespace.NamespaceName;

                if (!attribute.IsNamespaceDeclaration && !String.IsNullOrEmpty(namespaceURI))
                {
                    string commandName = attribute.Name.LocalName;
                    ICommand command = CreateCommand(namespaceURI, commandName);
                    if (command != null)
                    {
                        Check.IsFalse(isCommandAssigned, "Multiple commands per element is currently not supported.");
                        isCommandAssigned = true;
                        String expression = attribute.Value;
                        CommandCall commandCall = new CommandCall(command, new Element(element), expression, resource);
                        parentCommandCall.AddChild(commandCall);
                        parentCommandCall = commandCall;
                    }
                }
            }

            foreach (XElement child in element.Elements())
            {
                GenerateCommandCallTree(child, parentCommandCall, resource);
            }
        }
Example #29
0
		public static void Parse(dynamic parent, XElement node)
		{
			foreach (var a in node.Attributes())
				AddProperty(parent, a.Name.ToString(), a.Value);
			if (node.HasElements)
			{
				IEnumerable<XElement> sorted = from XElement elt in node.Elements() orderby node.Elements(elt.Name.LocalName).Count() descending select elt;
				string elementName = string.Empty;
				List<dynamic> list = null;
				foreach (var element in sorted)
				{
					var item = new ExpandoObject();
					Parse(item, element);
					if (element.Name.LocalName != elementName)
					{
						list = null;
						AddProperty(parent, elementName = element.Name.LocalName, item);
					}
					else
						if (list == null)
							AddProperty(parent, element.Name.LocalName, list = new List<dynamic>() { (parent as IDictionary<string, object>)[element.Name.LocalName], item });
						else
							list.Add(item);
				}
			}
			else if (!string.IsNullOrWhiteSpace(node.Value))
				AddProperty(parent, "TextValue", node.Value.Trim());
		}
 private static IEnumerable<XAttribute> NormalizeAttributes(XElement element,
     bool havePSVI)
 {
     return element.Attributes()
                     .Where(a => !a.IsNamespaceDeclaration &&
                             a.Name != Xsi.schemaLocation &&
                             a.Name != Xsi.noNamespaceSchemaLocation)
                     .OrderBy(a => a.Name.NamespaceName)
                     .ThenBy(a => a.Name.LocalName)
                     .Select(
                             a => {
                                 if (havePSVI) {
                                     var dt = a.GetSchemaInfo().SchemaType.TypeCode;
                                     switch (dt) {
                                         case XmlTypeCode.Boolean:
                                             return new XAttribute(a.Name, (bool)a);
                                         case XmlTypeCode.DateTime:
                                             return new XAttribute(a.Name, (DateTime)a);
                                         case XmlTypeCode.Decimal:
                                             return new XAttribute(a.Name, (decimal)a);
                                         case XmlTypeCode.Double:
                                             return new XAttribute(a.Name, (double)a);
                                         case XmlTypeCode.Float:
                                             return new XAttribute(a.Name, (float)a);
                                         case XmlTypeCode.HexBinary:
                                         case XmlTypeCode.Language:
                                             return new XAttribute(a.Name,
                                                     ((string)a).ToLower());
                                     }
                                 }
                                 return a;
                             }
                     );
 }
Example #31
0
        private static void RemoveSCCElementsAttributes(System.Xml.Linq.XElement el)
        {
            el.Elements().Where(x => x.Name.LocalName.StartsWith("Scc")).Remove();
            el.Attributes().Where(x => x.Name.LocalName.StartsWith("Scc")).Remove();

            foreach (var child in el.Elements())
            {
                RemoveSCCElementsAttributes(child);
            }
        }
Example #32
0
        /// <summary>
        /// Maps an XML element to a settings dictionary.
        /// </summary>
        /// <param name="element">The XML element to be mapped.</param>
        /// <returns>The settings dictionary.</returns>
        public Models.SettingsDictionary Map(System.Xml.Linq.XElement element)
        {
            if (element == null)
            {
                return(new SettingsDictionary());
            }

            return(new SettingsDictionary(
                       element.Attributes()
                       .ToDictionary(attr => XmlConvert.DecodeName(attr.Name.LocalName), attr => attr.Value)));
        }
Example #33
0
        //TODO: add a link for Trinity Configuration File Format Specification v1.
        /// <summary>
        /// Constructs a new configuration entry from an XML element.
        /// </summary>
        /// <param name="entry">The XML element.</param>
        public ConfigurationEntry(System.Xml.Linq.XElement entry) :
            this(entry.Name.LocalName)
        {
            foreach (var attribute in entry.Attributes())
            {
                m_settings.Add(attribute.Name.LocalName, new ConfigurationSetting(attribute));
            }

            foreach (var child in entry.Descendants())
            {
                m_children.Add(new ConfigurationEntry(child));
            }
        }
Example #34
0
    //Core recursion function
    private static System.Xml.Linq.XElement RemoveAllNamespaces(System.Xml.Linq.XElement xmlDocument)
    {
        if (xmlDocument.HasAttributes)
        {
            xmlDocument.RemoveAttributes();
        }
        if (!xmlDocument.HasElements)
        {
            System.Xml.Linq.XElement xElement = new System.Xml.Linq.XElement(xmlDocument.Name.LocalName);
            xElement.Value = xmlDocument.Value;

            foreach (System.Xml.Linq.XAttribute attribute in xmlDocument.Attributes())
            {
                xElement.Add(attribute);
            }

            return(xElement);
        }
        return(new System.Xml.Linq.XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el))));
    }
Example #35
0
        protected override void InnerInitializeProperties(System.Xml.Linq.XElement element)
        {
            this.FillProperty(m => m.TotalDeposit);
            this.FillProperty(m => m.Equity);
            this.FillProperty(m => m.AlertLevel);
            this.FillProperty(m => m.AlertTime);
            this.FillProperty(m => m.IsMultiCurrency);
            this.FillProperty(m => m.Code);
            this.FillProperty(m => m.CustomerName);
            this.FillProperty(m => m.CurrencyCode);
            this.FillProperty(m => m.Type);
            this.FillProperty(m => m.CreditAmount);
            this.FillProperty(m => m.Leverage);
            this.FillProperty(m => m.RateMarginD);
            this.FillProperty(m => m.RateMarginO);
            this.FillProperty(m => m.RateMarginLockD);
            this.FillProperty(m => m.RateMarginLockO);
            this.FillProperty(m => m.EstimateCloseCommission);
            this.FillProperty(m => m.EstimateCloseLevy);

            foreach (XAttribute attribute in element.Attributes())
            {
                if (attribute.Name == "Necessary")
                {
                    this._necessaries[0] = decimal.Parse(attribute.Value);
                }
                else if (attribute.Name == "MinEquityAvoidRiskLevel1")
                {
                    this._necessaries[1] = decimal.Parse(attribute.Value);
                }
                else if (attribute.Name == "MinEquityAvoidRiskLevel2")
                {
                    this._necessaries[2] = decimal.Parse(attribute.Value);
                }
                else if (attribute.Name == "MinEquityAvoidRiskLevel3")
                {
                    this._necessaries[3] = decimal.Parse(attribute.Value);
                }
            }
        }
Example #36
0
    private void ShowData( System.Xml.Linq.XElement i_element )
    {
        string nameText     = i_element.Name.LocalName;
        string valueText    = i_element.Value;
        string atrText      = string.Empty;

        // アトリビュートがある場合。
        if( i_element.HasAttributes )
        {
            foreach( var attribute in i_element.Attributes() )
            {
                atrText += string.Format( "\t\t{0}={1}\n", attribute.Name, attribute.Value );
            }
        }

        Debug.LogFormat( "name:{0}\n\tvalue:{1}\n\tattribute:\n{2}", nameText, valueText, atrText );

        // 子ノードも探そう。
        foreach( var child in i_element.Elements() )
        {
            ShowData( child );
        }
    }
Example #37
0
        private void Transit(System.Xml.Linq.XElement expression)
        {
            if (expression == null)
            {
                return;
            }

            if (expression.Elements().Any())
            {
                foreach (var element in expression.Elements())
                {
                    Transit(element);
                }
            }
            var attirbs = from attirb in expression.Attributes()
                          where attirb.Value == typeof(DTO).FullName
                          select attirb;

            foreach (var attrib in attirbs)
            {
                attrib.Value = typeof(Entity).FullName;
                //expression.ReplaceAttributes(new XAttribute("Name", typeof(Entity).FullName));
            }
        }
Example #38
0
 public XElement(XElement source)
 {
     name = source.name;
     Add(source.Attributes());
     Add(source.Nodes());
 }
Example #39
0
        static bool ProcessXamlForDisplay(string sourceXaml, string sourceXamlFileNameAndPath, EnvDTE.Project currentProject, EnvDTE.Solution currentSolution, Dictionary <string, EnvDTE.Project> assemblyNameToProjectDictionary, ResourcesCache resourcesCache, out string outputXaml, out string errorsIfAny, out HashSet <string> warningsAndTips)
        {
            warningsAndTips = new HashSet <string>();

            // Default output values:
            outputXaml  = sourceXaml;
            errorsIfAny = "";

            //---------------------------------------
            // Remove the content of all the "HtmlPresenter" nodes, because the content may be not well formatted and may lead to a syntax error when parsing the XDocument:
            //---------------------------------------
            sourceXaml = HtmlPresenterRemover.RemoveHtmlPresenterNodes(sourceXaml);

            //---------------------------------------
            // Read the XDocument:
            //---------------------------------------
            System.Xml.Linq.XDocument xdoc;
            try
            {
                xdoc = System.Xml.Linq.XDocument.Parse(sourceXaml);
            }
            catch (Exception ex)
            {
                errorsIfAny = ex.Message;
                return(false);
            }

            //---------------------------------------
            // Remove the "x:Class" attribute if any:
            //---------------------------------------

            if (xdoc.Root != null)
            {
                // Remove the "x:Class" attribute if any:
                XNamespace xNamespace          = "http://schemas.microsoft.com/winfx/2006/xaml";
                XAttribute classAttributeIfAny = xdoc.Root.Attribute(xNamespace + "Class");
                if (classAttributeIfAny != null)
                {
                    classAttributeIfAny.Remove();
                }
            }

            //---------------------------------------
            // Replace the root control with a UserControl (if it is not already one) and keep only the properties and attributes supported by the UserControl class:
            //---------------------------------------

            ProcessNodeToMakeItCompatibleWithWpf.ReplaceRootWithUserControl(xdoc);


            //---------------------------------------
            // Get the styles and other resources defined in App.xaml
            //---------------------------------------

            IEnumerable <XElement> appDotXamlResources;
            string appDotXamlFullPath;

            if (resourcesCache.AppDotXamlResources != null) // This avoids reloading App.xaml at every refresh, to improve performance.
            {
                // Read from cache:
                appDotXamlResources = resourcesCache.AppDotXamlResources;
                appDotXamlFullPath  = resourcesCache.AppDotXamlFullPath;
            }
            else
            {
                // Attempt to find App.xaml and read it:
                appDotXamlResources = ResolvingReferencedXamlResources.GetAppDotXamlResources(currentProject, currentSolution, out appDotXamlFullPath);
                resourcesCache.AppDotXamlResources = appDotXamlResources;
                resourcesCache.AppDotXamlFullPath  = appDotXamlFullPath;
            }

            //---------------------------------------
            // Resolve all the "Merged Dictionaries", and merge them so that there are no more references to other XAML files:
            //---------------------------------------

            // Process the resources defined in App.xaml:
            if (appDotXamlResources != null)
            {
                try
                {
                    foreach (XElement element in appDotXamlResources)
                    {
                        ResolvingReferencedXamlResources.ResolveAndMergeTheMergedDictionaries(element, appDotXamlFullPath, assemblyNameToProjectDictionary, new HashSet <string>(), resourcesCache);
                    }
                }
                catch (Exception ex)
                {
                    errorsIfAny = ex.Message;
                    return(false);
                }
            }

            // Process the resources defined in the current file:
            try
            {
                ResolvingReferencedXamlResources.ResolveAndMergeTheMergedDictionaries(xdoc.Root, sourceXamlFileNameAndPath, assemblyNameToProjectDictionary, new HashSet <string>(), resourcesCache);
            }
            catch (Exception ex)
            {
                errorsIfAny = ex.Message;
                return(false);
            }

            //---------------------------------------
            // Surround the document with a control in which we inject all the resources that we found in the end-user's "App.xaml" file:
            //---------------------------------------

            if (appDotXamlResources != null && appDotXamlResources.Any())
            {
                // Put those resouces in a control that will surround the xaml of the current page:
                var surroundingControlForResources = new XElement(DefaultXamlNamespace + "Border", xdoc.Root);
                surroundingControlForResources.Add(new XAttribute(XNamespace.Xmlns + "x", @"http://schemas.microsoft.com/winfx/2006/xaml")); // Note: This is required in case the XAML code contains the "x" prefix inside Markup Extensions (such as "{x:Null}"). It is not needed for the "x" prefix in elements and attributes (such as "x:Name"), because those are automatically imported when copying nodes, where as markup extensions are considered as simple strings by "Linq to XML".
                surroundingControlForResources.Add(new XAttribute("Tag", "AddedByDesignerToInjectAppDotXamlResources"));
                var resourcesContainer = new XElement(DefaultXamlNamespace + "Border.Resources");
                surroundingControlForResources.AddFirst(resourcesContainer);
                resourcesContainer.Add(appDotXamlResources);

                // Replace the document with the one surrounded by the new control:
                xdoc = new XDocument(surroundingControlForResources);
            }

#if Display_The_Processed_XAML
            // Uncomment to display the processed XAML:
            errorsIfAny = xdoc.Root.ToString();
            outputXaml  = xdoc.Root.ToString();
            return(false);
#endif

            //---------------------------------------
            // Iterate through the document using a Stack<XElement> (pre-order traversal, no recursion) and process the nodes:
            //---------------------------------------

            XElement root = xdoc.Root;
            Stack <System.Xml.Linq.XElement> stack = new Stack <System.Xml.Linq.XElement>();
            stack.Push(root);
            while (stack.Count > 0)
            {
                System.Xml.Linq.XElement current       = stack.Pop();
                bool elementWasReplacedWithPlaceholder = false; // default value

                //---------------------------------------
                // Process node to make it compatible with WPF (remove events such as PointerPressed, change "Page" to "UserControl", etc.):
                //---------------------------------------
                ProcessNodeToMakeItCompatibleWithWpf.Process(current, ref warningsAndTips);

                //---------------------------------------
                // Remove unknown nodes and attributes, and display "Cannot preview this element" instead:
                //---------------------------------------

                // Verify that the node is not a property:
                if (!current.Name.LocalName.Contains("."))
                {
                    bool isKnownType = false;

                    // Check to see if the element corresponds to a known type (only for elements that are supposed to be in the default namespace):
                    Type type;
                    if (current.Name.NamespaceName == DefaultXamlNamespace &&
                        TryGetType(current.Name, out type))
                    {
                        isKnownType = true;

                        // List all the event handlers of the type:
                        List <string> eventHandlers = new List <string>();
                        foreach (EventInfo eventInfo in type.GetEvents())
                        {
                            eventHandlers.Add(eventInfo.Name);
                        }

                        // Duplicate the list of attributes so that when we remove one, it doesn't affect the iteration:
                        List <System.Xml.Linq.XAttribute> attributesListCopy = new List <System.Xml.Linq.XAttribute>();
                        foreach (System.Xml.Linq.XAttribute attr in current.Attributes())
                        {
                            attributesListCopy.Add(attr);
                        }

                        // Remove event handlers:
                        foreach (System.Xml.Linq.XAttribute attr in attributesListCopy)
                        {
                            // Check if the attribute is an event handler:
                            //test+= "  ||||  " + attr.Name.LocalName + "  " + attr.Name.NamespaceName + "  " + (!attr.Name.LocalName.Contains(".")).ToString() + "  " + eventHandlers.Contains(attr.Name.LocalName).ToString();
                            if (!attr.Name.LocalName.Contains(".") && eventHandlers.Contains(attr.Name.LocalName))
                            {
                                // Remove the attrbute:
                                attr.Remove();
                            }
                        }
                    }
                    else if (current.Name.NamespaceName.EndsWith("assembly=mscorlib"))
                    {
                        isKnownType = true;
                    }

                    // If not known type, replace the element with a placeholder that says "Unable to display":
                    if (!isKnownType)
                    {
                        // Create a border with inside a TextBlock that says "Unable to display":
                        System.Xml.Linq.XElement msg    = new System.Xml.Linq.XElement(DefaultXamlNamespace + "Border");
                        System.Xml.Linq.XElement msgTxt = new System.Xml.Linq.XElement(DefaultXamlNamespace + "TextBlock");

                        // Add the newly created stuff to the XAML:
                        current.ReplaceWith(msg);
                        msg.Add(msgTxt);

                        // Set some attributes:
                        msg.Add(new XAttribute("Background", "DarkRed"));
                        msg.Add(new XAttribute("Opacity", "0.5"));
                        msg.Add(new XAttribute("Tag", "AddedByDesignerAsPlaceholder"));
                        msgTxt.Add(new XAttribute("Text", "Unable to preview this element"));
                        msgTxt.Add(new XAttribute("TextWrapping", "Wrap"));
                        msgTxt.Add(new XAttribute("TextAlignment", "Center"));
                        msgTxt.Add(new XAttribute("HorizontalAlignment", "Stretch"));
                        msgTxt.Add(new XAttribute("VerticalAlignment", "Center"));
                        msgTxt.Add(new XAttribute("FontSize", "12"));
                        msgTxt.Add(new XAttribute("Foreground", "#AAFFFFFF"));
                        msgTxt.Add(new XAttribute("Tag", "AddedByDesignerForRendering"));

                        // Give to that Border the same positioning information as the element that it replaces:
                        MoveAttributeIfAny("Width", current, msg);
                        MoveAttributeIfAny("Height", current, msg);
                        MoveAttributeIfAny("HorizontalAlignment", current, msg);
                        MoveAttributeIfAny("VerticalAlignment", current, msg);
                        MoveAttributeIfAny("Margin", current, msg);
                        MoveAttributeIfAny("Opacity", current, msg);
                        MoveAttributeIfAny("MaxWidth", current, msg);
                        MoveAttributeIfAny("MaxHeight", current, msg);
                        MoveAttributeIfAny("MinWidth", current, msg);
                        MoveAttributeIfAny("MinHeight", current, msg);
                        MoveAttributeIfAny("Visibility", current, msg);
                        MoveAttributeIfAny("Canvas.Left", current, msg);
                        MoveAttributeIfAny("Canvas.Top", current, msg);
                        MoveAttributeIfAny((XNamespace)"clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit" + "DockPanel.Dock", current, msg);
                        MoveAttributeIfAny((XNamespace)"http://schemas.microsoft.com/winfx/2006/xaml" + "Name", current, msg);
                        MoveAttributeIfAny((XNamespace)"http://schemas.microsoft.com/winfx/2006/xaml" + "Key", current, msg);

                        // Remember that the element was replaced:
                        elementWasReplacedWithPlaceholder = true;
                    }
                }

                // Continue with the children of this element:
                if (!elementWasReplacedWithPlaceholder)
                {
                    foreach (XElement element in current.Elements())
                    {
                        stack.Push(element);
                    }
                }
            }



            errorsIfAny = ""; //xdoc.ToString();
            outputXaml  = root.ToString();
            return(true);
        }
Example #40
0
 public static IEnumerable <XAttribute> NormalizedAttributes(this XElement element)
 {
     return(element.Attributes().Where(a => !a.IsNamespaceDeclaration)
            .OrderBy(a => a.Name.NamespaceName)
            .ThenBy(a => a.Name.LocalName));
 }
Example #41
0
 public static XAttribute GetAttribute(this XElement element, string name)
 {
     return(element.Attributes().FirstOrDefault(x => x.Name.LocalName.Equals(name, StringComparison.InvariantCultureIgnoreCase)));
 }