示例#1
0
        public void NodeRemove()
        {
            XElement parent = new XElement("parent");

            XComment child1 = new XComment("child1");
            XText    child2 = new XText("child2");
            XElement child3 = new XElement("child3");

            parent.Add(child1, child2, child3);

            // Sanity check
            Assert.Equal(parent.Nodes(), new XNode[] { child1, child2, child3 }, XNode.EqualityComparer);

            // Remove the text.
            child1.NextNode.Remove();
            Assert.Equal(new XNode[] { child1, child3 }, parent.Nodes(), XNode.EqualityComparer);

            // Remove the XComment.
            child1.Remove();
            Assert.Equal(new XNode[] { child3 }, parent.Nodes(), XNode.EqualityComparer);

            // Remove the XElement.
            child3.Remove();
            Assert.Empty(parent.Nodes());
        }
示例#2
0
                /// <summary>
                /// Tests Remove on Node.
                /// </summary>
                /// <param name="context"></param>
                /// <returns></returns>
                //[Variation(Desc = "NodeRemove")]
                public void NodeRemove()
                {
                    XElement parent = new XElement("parent");

                    XComment child1 = new XComment("child1");
                    XText    child2 = new XText("child2");
                    XElement child3 = new XElement("child3");

                    parent.Add(child1, child2, child3);

                    // Sanity check
                    Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { child1, child2, child3 });

                    // Remove the text.
                    child1.NextNode.Remove();
                    Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { child1, child3 });

                    // Remove the XComment.
                    child1.Remove();
                    Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { child3 });

                    // Remove the XElement.
                    child3.Remove();
                    Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { });
                }
示例#3
0
        public static XDocument AddProjectGuidToWebConfig(XDocument document, string projectGuid, bool ignoreProjectGuid)
        {
            try
            {
                if (document != null && !string.IsNullOrEmpty(projectGuid))
                {
                    IEnumerable <XComment> comments = document.DescendantNodes().OfType <XComment>();
                    projectGuid = projectGuid.Trim('{', '}', '(', ')').Trim();
                    string   projectGuidValue   = string.Format("ProjectGuid: {0}", projectGuid);
                    XComment projectGuidComment = comments.FirstOrDefault(comment => string.Equals(comment.Value, projectGuidValue, StringComparison.OrdinalIgnoreCase));
                    if (projectGuidComment != null)
                    {
                        if (ignoreProjectGuid)
                        {
                            projectGuidComment.Remove();
                        }

                        return(document);
                    }

                    if (!ignoreProjectGuid)
                    {
                        document.LastNode.AddAfterSelf(new XComment(projectGuidValue));
                        return(document);
                    }
                }
            }
            catch
            {
                // This code path is only used for telemetry.
            }

            return(document);
        }
        public void Resolve(ConfigDocument includeDoc)
        {
            if (includeDoc == null)
            {
                throw new ArgumentNullException(nameof(includeDoc));
            }
            if (includeDoc.GetXDocument()?.Root == null)
            {
                return;
            }

            var payloadElements = includeDoc.GetXDocument().Root
                                  .Descendants()
                                  .Where(e => !e.HasElements);

            var addElements = new List <XElement>();

            foreach (var pe in payloadElements)
            {
                var pathItems = new List <XElement>();
                GetElementPath(pe, pathItems);

                var newElement = BuildPathElements(_includeComment.Parent, pathItems.ToArray(), pe.Name.LocalName, addElements);

                if (string.IsNullOrEmpty(newElement.Value))
                {
                    newElement.Value = pe.Value;
                }
            }

            _includeComment.Remove();
        }
示例#5
0
        public void Element6(int param)
        {
            XElement e1 = new XElement("A", "datata");
            XElement e2 = new XElement("A", "datata");

            switch (param)
            {
            case 1:
                XComment c = new XComment("hele");
                e2.Add(c);
                c.Remove();
                break;

            case 2:
                break;
            }

            VerifyComparison(true, e1, e2);
        }
示例#6
0
 public static XElement Except(this XElement source, XElement target)
 {
     if (target != null)
     {
         using (List <XAttribute> .Enumerator enumerator = (from e in source.Attributes()
                                                            where AttributeEquals(e, target.Attribute(e.Name))
                                                            select e).ToList <XAttribute>().GetEnumerator())
         {
             while (enumerator.MoveNext())
             {
                 enumerator.Current.Remove();
             }
         }
         foreach (XNode node in source.Nodes().ToList <XNode>())
         {
             XComment comment = node as XComment;
             if (comment != null)
             {
                 if (!HasComment(target, comment))
                 {
                     continue;
                 }
                 comment.Remove();
                 continue;
             }
             XElement targetChild = node as XElement;
             if (targetChild != null)
             {
                 XElement element2 = FindElement(target, targetChild);
                 if ((element2 != null) && !HasConflict(targetChild, element2))
                 {
                     targetChild.Except(element2);
                     if (!(targetChild.HasAttributes || targetChild.HasElements))
                     {
                         targetChild.Remove();
                         element2.Remove();
                     }
                 }
             }
         }
     }
     return(source);
 }
示例#7
0
                //[Variation(Priority = 0, Desc = "XElement - text node incarnation - by touching", Param = 1)]
                //[Variation(Priority = 0, Desc = "XElement - text node incarnation - by adding new node", Param = 2)]
                public void Element6()
                {
                    XElement e1 = new XElement("A", "datata");
                    XElement e2 = new XElement("A", "datata");

                    switch ((int)Variation.Param)
                    {
                    case 1:
                        XComment c = new XComment("hele");
                        e2.Add(c);
                        c.Remove();
                        break;

                    case 2:
                        break;

                    default:
                        TestLog.Compare(false, "Unexpected value - test failed");
                        break;
                    }

                    VerifyComparison(true, e1, e2);
                }
示例#8
0
        public void MultiUnicodeHasCorrectRepsonses()
        {
            const string str     = @"<CmPossibilityList
						guid='cf379f73-9ee5-4e45-b2e2-4b169666d83e'>
		<Name>
			<AUni
				ws='en'>Genres &amp;</AUni>
			<AUni
				ws='es'>Géneros &amp;</AUni>
		</Name>
						</CmPossibilityList>"                        ;
            var          element = XElement.Parse(str);

            AddBasicPropertyElementsToPossList(element);
            var result = CmObjectValidator.ValidateObject(_mdc, element);

            Assert.IsNull(result);

            element.Element("Name").Add(new XAttribute("bogusAttr", "badvalue"));
            result = CmObjectValidator.ValidateObject(_mdc, element);
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Contains("Has unrecognized attribute(s)"));
            element.Element("Name").Attributes().Remove();

            element.Element("Name").Add(new XElement("extraChild"));
            result = CmObjectValidator.ValidateObject(_mdc, element);
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Contains("Has non-AUni child element"));
            element.Element("Name").Element("extraChild").Remove();

            element.Element("Name").Element("AUni").Add(new XAttribute("bogusAttr", "badValue"));
            result = CmObjectValidator.ValidateObject(_mdc, element);
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Contains("Has too many attributes"));
            var wsAttr = element.Element("Name").Element("AUni").Attribute("ws");

            wsAttr.Remove();
            result = CmObjectValidator.ValidateObject(_mdc, element);
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Contains("Does not have required 'ws' attribute"));
            element.Element("Name").Element("AUni").Attribute("bogusAttr").Remove();
            element.Element("Name").Element("AUni").Add(wsAttr);
            result = CmObjectValidator.ValidateObject(_mdc, element);
            Assert.IsNull(result);

            var extraChild = new XElement("extraChild");

            element.Element("Name").Element("AUni").Add(extraChild);
            result = CmObjectValidator.ValidateObject(_mdc, element);
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Contains("Has non-text child element"));
            extraChild.Remove();

            // Comment doesn't count, as trouble.
            var comment = new XComment("Some comment.");

            element.Element("Name").Element("AUni").Add(comment);
            result = CmObjectValidator.ValidateObject(_mdc, element);
            Assert.IsNull(result);
            comment.Remove();
        }
示例#9
0
        public bool Load(object inputObj, string sectionName)
        {
            if (inputObj == null)
            {
                _logger.Error("Received object is null.");
                return(false);
            }

            if (string.IsNullOrEmpty(sectionName) || string.IsNullOrWhiteSpace(sectionName))
            {
                _logger.Error($"Received {nameof(sectionName)} is null, empty, or white space");
                return(false);
            }

            try
            {
                Type     type                  = inputObj.GetType();
                string   namespaceOfType       = type.Namespace ?? "Unknown";
                string[] namespaceFragments    = namespaceOfType.Split('.');
                string   currentConfigFileName = Path.Combine(_configFolder, namespaceFragments[0] + _CONFIG_FILE_EXTENSION);

                _logger.Info($"Reading object (type: {type}) parameters in section name: {sectionName}");
                _logger.Info($"Object (type: {type}) namespace {namespaceOfType}");

                bool differenceFound = false;

                CreateConfigFileIfNotExisting(currentConfigFileName);

                // load the required section in XElement format:

                XElement currentSectionElement = LoadSectionXElementFromFile(currentConfigFileName, sectionName, type);

                if (currentSectionElement == null)
                {
                    currentSectionElement = CreateSectionXElement(sectionName, type);
                }

                if (!CheckAssemblyAttributeOfSection(currentSectionElement, type))
                {
                    currentSectionElement = FixAssembylAttributeOfSection(currentSectionElement, type);
                    differenceFound       = true;
                }

                // edit according to the received parameter object:



                FieldInfo   currentObjectField            = null;
                FieldInfo[] fieldInfosWithConfigAttribute = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(p => p.GetCustomAttributes(typeof(ConfigurationAttribute)).ToList().Count == 1).ToArray();
                foreach (var fieldInfo in fieldInfosWithConfigAttribute)
                {
                    ConfigurationAttribute fieldConfigurationAttribute = (ConfigurationAttribute)fieldInfo.GetCustomAttribute(typeof(ConfigurationAttribute));

                    XAttribute             nameAttribute      = null;
                    XAttribute             valueAttribute     = null;
                    IEnumerable <XElement> xmlListElementNode = null;

                    foreach (XNode parameterNode in currentSectionElement.Nodes())
                    {
                        if (parameterNode is XComment)       // todo
                        {
                            continue;
                        }

                        if (!(parameterNode is XElement parameterElement))
                        {
                            continue;       // todo
                        }

                        xmlListElementNode = parameterElement.Elements();
                        nameAttribute      = GetAttributeValueByAttributeName(parameterElement, NAME_ATTRIBUTE_NAME);
                        valueAttribute     = GetAttributeValueByAttributeName(parameterElement, VALUE_ATTRIBUTE_NAME);

                        if (nameAttribute == null || valueAttribute == null)
                        {
                            parameterNode.Remove();
                            _logger.Info($"Section ({parameterElement.Name}) without {NAME_ATTRIBUTE_NAME} or {VALUE_ATTRIBUTE_NAME} attribute was found. It is removed.");

                            continue;
                        }

                        if (fieldConfigurationAttribute.Name == nameAttribute.Value)
                        {
                            break;
                        }
                    }

                    // xnode was found for the given field in the section:
                    if (nameAttribute != null && valueAttribute != null && fieldConfigurationAttribute.Name == nameAttribute.Value)
                    {
                        try
                        {
                            currentObjectField = fieldInfo;
                            Type fieldType = currentObjectField.FieldType;

                            // process list if list was found:
                            if (valueAttribute.Value == string.Empty && xmlListElementNode != null && typeof(ICollection).IsAssignableFrom(fieldType))
                            {
                                IList listobj = (IList)Activator.CreateInstance(fieldType);

                                foreach (XElement item in xmlListElementNode)
                                {
                                    valueAttribute = GetAttributeValueByAttributeName(item, VALUE_ATTRIBUTE_NAME);
                                    string listElement = (string)Convert.ChangeType(valueAttribute.Value, typeof(string));
                                    listobj.Add(listElement);
                                }
                                currentObjectField.SetValue(inputObj, listobj);
                            }
                            else // not list, but a single lement was found
                            {
                                object temporary;
                                // if a string was found -> no conversion is needed:
                                if (fieldType.IsEnum && !string.IsNullOrEmpty(valueAttribute.Value))
                                {
                                    temporary = Enum.Parse(fieldType, valueAttribute.Value);
                                }
                                else
                                {
                                    if (fieldType.GenericTypeArguments != null && fieldType.GenericTypeArguments.Length > 0 && fieldType.GenericTypeArguments[0] == typeof(System.String))
                                    {
                                        temporary = valueAttribute.Value;
                                    }
                                    else // not string -> conversion is needed
                                    {
                                        temporary = Convert.ChangeType(valueAttribute.Value, fieldType);
                                    }
                                }

                                currentObjectField.SetValue(inputObj, temporary);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Error($"Exception occured during {nameAttribute.Value}, {valueAttribute.Value} conversion: {ex.Message}");
                            break;
                        }
                    }
                    else // no section was found in the file for the searched field:
                    {
                        XElement newElement = CreateFieldSectionXElement(fieldConfigurationAttribute.Name, "");
                        XComment comment    = CreateXComment(fieldConfigurationAttribute.Description, fieldInfo);

                        currentSectionElement.Add(comment);
                        currentSectionElement.Add(newElement);

                        differenceFound = true;
                    }
                }


                // Investigate whether all field sections has pair in the loaded object -> if not make comment from it.
                XComment previousComment = null;
                foreach (XNode childXNode in currentSectionElement.Nodes())
                {
                    XAttribute nameXAttribute = null;

                    if (childXNode is XComment || childXNode == null)
                    {
                        previousComment = (XComment)childXNode;
                        continue;
                    }

                    XElement childXElement = (XElement)childXNode;
                    nameXAttribute = GetAttributeValueByAttributeName(childXElement, NAME_ATTRIBUTE_NAME);
                    ConfigurationAttribute matchingConfigurationAttribute = null;

                    foreach (var fieldInfo in fieldInfosWithConfigAttribute)
                    {
                        ConfigurationAttribute fieldConfigurationAttribute = (ConfigurationAttribute)fieldInfo.GetCustomAttribute(typeof(ConfigurationAttribute));

                        if (fieldConfigurationAttribute.Name == nameXAttribute.Value)
                        {
                            matchingConfigurationAttribute = fieldConfigurationAttribute;
                            break;
                        }
                    }

                    if (matchingConfigurationAttribute == null)
                    {
                        XComment comment = CreateXComment(childXNode.ToString());
                        try
                        {
                            childXNode.Remove();
                            previousComment.Remove();
                            currentSectionElement.Add(previousComment);
                            currentSectionElement.Add(comment);
                        }
                        catch (Exception ex)
                        {
                            _logger.Error($"Exception occured during node commenting: {ex.Message}");
                        }

                        differenceFound = true;
                    }
                }

                if (differenceFound)
                {
                    Save(currentConfigFileName, sectionName, currentSectionElement, type);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"Exception occured: {ex}");
                return(false);
            }

            return(true);
        }
示例#10
0
        public void Element6(int param)
        {
            XElement e1 = new XElement("A", "datata");
            XElement e2 = new XElement("A", "datata");
            switch (param)
            {
                case 1:
                    XComment c = new XComment("hele");
                    e2.Add(c);
                    c.Remove();
                    break;
                case 2:
                    break;
            }

            VerifyComparison(true, e1, e2);
        }