ReplaceChild() public method

public ReplaceChild ( XmlNode node, XmlNode child ) : XmlNode
node XmlNode
child XmlNode
return XmlNode
        private static void ReplaceDefs(XmlNode xmlNode)
        {
            for (var i = 0; i < xmlNode.ChildNodes.Count; i++)
            {
                var childNode = xmlNode.ChildNodes[i];
                ReplaceDefs(childNode);
                if (childNode.Name != "defs")
                {
                    continue;
                }

                var gNode = childNode.OwnerDocument.CreateElement("g", childNode.NamespaceURI);
                foreach (XmlAttribute attribute in childNode.Attributes)
                {
                    gNode.SetAttributeNode((XmlAttribute)attribute.Clone());
                }
                gNode.SetAttribute("display", "none");
                while (childNode.HasChildNodes)
                {
                    gNode.AppendChild(childNode.FirstChild);
                }

                xmlNode.ReplaceChild(gNode, childNode);
            }
        }
Esempio n. 2
0
        private void CloseWithReplaceToFollowingSibling()
        {
            XmlNode parent = _start.ParentNode;

            if (parent == null)
            {
                throw new InvalidOperationException(SR.Xpn_MissingParent);
            }
            if (_start != _end)
            {
                if (!DocumentXPathNavigator.IsFollowingSibling(_start, _end))
                {
                    throw new InvalidOperationException(SR.Xpn_BadPosition);
                }
                if (_start.IsReadOnly)
                {
                    throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly);
                }
                DocumentXPathNavigator.DeleteToFollowingSibling(_start.NextSibling, _end);
            }
            XmlNode fragment0 = _fragment[0];

            parent.ReplaceChild(fragment0, _start);
            for (int i = _fragment.Count - 1; i >= 1; i--)
            {
                parent.InsertAfter(_fragment[i], fragment0);
            }
            _navigator.ResetPosition(fragment0);
        }
Esempio n. 3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        String adName   = Request.QueryString["ad"];
        String redirect = Request.QueryString["target"];

        if (adName == null | redirect == null)
        {
            redirect = "AdRedirection.aspx";
        }

        XmlDocument doc = new XmlDocument();

        doc.Load(Server.MapPath("AdResponses.xml"));
        System.Xml.XmlNode root   = doc.DocumentElement;
        System.Xml.XmlNode adNode =
            root.SelectSingleNode(
                @"descendant::ad[@adname='" + adName + "']");
        if (adNode != null)
        {
            int ctr =
                int.Parse(adNode.Attributes["hitCount"].Value);
            ctr += 1;
            System.Xml.XmlNode newAdNode = adNode.CloneNode(false);
            newAdNode.Attributes["hitCount"].Value = ctr.ToString();
            root.ReplaceChild(newAdNode, adNode);
            doc.Save(Server.MapPath("AdResponses.xml"));
        }
        Response.Redirect(redirect);
    }
Esempio n. 4
0
    //
    //createDataElement
    //
    private static void createDataElement(
        ref System.Xml.XmlDocument pdoc,
        string pname, string pvalue,
        string pcomment)
    {
        System.Xml.XmlElement data = pdoc.CreateElement("data");
        data.SetAttribute("name", pname);
        data.SetAttribute("xml:space", "preserve");

        System.Xml.XmlElement value = pdoc.CreateElement("value");
        value.InnerText = pvalue;
        data.AppendChild(value);

        if (!(pcomment == null))
        {
            System.Xml.XmlElement comment = pdoc.CreateElement("comment");
            comment.InnerText = pcomment;
            data.AppendChild(comment);
        }

        System.Xml.XmlNode root     = pdoc.SelectSingleNode("//root");
        System.Xml.XmlNode old_data = root.SelectSingleNode("//data[@name='" + pname + "']");
        if (old_data == null)
        {
            root.AppendChild(data);
        }
        else
        {
            root.ReplaceChild(data, old_data);
        }
    }
        private void CloseWithReplaceToFollowingSibling()
        {
            XmlNode parentNode = this.start.ParentNode;

            if (parentNode == null)
            {
                throw new InvalidOperationException(Res.GetString("Xpn_MissingParent"));
            }
            if (this.start != this.end)
            {
                if (!DocumentXPathNavigator.IsFollowingSibling(this.start, this.end))
                {
                    throw new InvalidOperationException(Res.GetString("Xpn_BadPosition"));
                }
                if (this.start.IsReadOnly)
                {
                    throw new InvalidOperationException(Res.GetString("Xdom_Node_Modify_ReadOnly"));
                }
                DocumentXPathNavigator.DeleteToFollowingSibling(this.start.NextSibling, this.end);
            }
            XmlNode newChild = this.fragment[0];

            parentNode.ReplaceChild(newChild, this.start);
            for (int i = this.fragment.Count - 1; i >= 1; i--)
            {
                parentNode.InsertAfter(this.fragment[i], newChild);
            }
            this.navigator.ResetPosition(newChild);
        }
Esempio n. 6
0
        private void createTypeElement(ref System.Xml.XmlDocument pdoc, string pid, string pname, string pcore, System.Collections.Generic.Dictionary <int, ContenttypeColumn> pfieldstable)
        {
            System.Xml.XmlElement contenttype = pdoc.CreateElement("", "ContentType", ns);
            contenttype.SetAttribute("ID", pid);
            contenttype.SetAttribute("Name", pname);
            contenttype.SetAttribute("Group", "$Resources:" + pcore + ",TypesGroupName;");
            contenttype.SetAttribute("Description", "$Resources:" + pcore + "," + pname + ";");
            contenttype.SetAttribute("Version", "0");

            System.Xml.XmlElement fieldrefs = pdoc.CreateElement("", "FieldRefs", ns);
            contenttype.AppendChild(fieldrefs);

            System.Collections.Generic.SortedDictionary <string, ContenttypeColumn> scol = new System.Collections.Generic.SortedDictionary <string, ContenttypeColumn>();
            foreach (ContenttypeColumn col in pfieldstable.Values)
            {
                scol.Add(col.Seqnr, col);
            }

            foreach (ContenttypeColumn col in scol.Values)
            {
                if (!col.SysCol)
                {
                    System.Xml.XmlElement fieldref = pdoc.CreateElement("", "FieldRef", ns);
                    fieldref.SetAttribute("ID", col.colGUID);
                    fieldref.SetAttribute("Name", col.SysName);
                    fieldrefs.AppendChild(fieldref);
                }
            }

            System.Xml.XmlNode elements = pdoc.SelectSingleNode("//mha:Elements", nsMgr);
            string             filter   = "//mha:ContentType[@ID=\"" + pid + "\"]";

            System.Xml.XmlNode old_contenttype = elements.SelectSingleNode(filter, nsMgr);

            if (old_contenttype == null)
            {
                elements.AppendChild(contenttype);
            }
            else
            {
                elements.ReplaceChild(contenttype, old_contenttype);
            }
        }
Esempio n. 7
0
        public static void CommentOutXML(string fileName, string outFileName)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(fileName);

            // Get the target node using XPath
            System.Xml.XmlNode elementToComment = doc.SelectSingleNode("/configuration/system.web/customErrors");

            // Get the XML content of the target node
            String commentContents = elementToComment.OuterXml;

            // Create a new comment node
            // Its contents are the XML content of target node
            System.Xml.XmlComment commentNode = doc.CreateComment(commentContents);

            // Get a reference to the parent of the target node
            System.Xml.XmlNode parentNode = elementToComment.ParentNode;

            // Replace the target node with the comment
            parentNode.ReplaceChild(commentNode, elementToComment);

            doc.Save(outFileName);
        }
        private static XmlNode Run(XmlMerger merger, XmlNode ours, XmlNode theirs, XmlNode ancestor)
        {
            if (ours == null && theirs == null && ancestor == null)
                return null;

            if (ancestor == null)
            {
                return HandleCaseOfNoAncestor(merger, ours, theirs);
            }
            // ancestor is not null at this point.
            var mergeSituation = merger.MergeSituation;
            var pathToFileInRepository = mergeSituation.PathToFileInRepository;
            if (ours == null && theirs == null)
            {
                // We both deleted main node.
            // Route tested, but the MergeChildrenMethod adds the change report for us.
                merger.EventListener.ChangeOccurred(new XmlBothDeletionChangeReport(pathToFileInRepository, ancestor));
                return null;
            }
            if (ours == null)
            {
                return HandleOursNotPresent(merger, ancestor, theirs);
            }
            if (theirs == null)
            {
                return HandleTheirsNotPresent(merger, ancestor, ours);
            }
            // End of checking main parent node.

            // ancestor, ours, and theirs all exist here.
            var ourChild = GetElementChildren(ours).FirstOrDefault();
            var theirChild = GetElementChildren(theirs).FirstOrDefault();
            var ancestorChild = GetElementChildren(ancestor).FirstOrDefault();
            if (ourChild == null && theirChild == null && ancestorChild == null)
            {
                return ours; // All three are childless.
            }

            if (ancestorChild == null)
            {
                return HandleCaseOfNoAncestorChild(merger, ours, ourChild, theirChild);
            }
            var mergeStrategyForChild = merger.MergeStrategies.GetElementStrategy(ancestorChild);
            if (ourChild == null)
            {
                return HandleOurChildNotPresent(merger, ours, ancestor, theirChild, pathToFileInRepository, ancestorChild, mergeSituation, mergeStrategyForChild);
            }
            if (theirChild == null)
            {
                return HandleTheirChildNotPresent(merger, ours, ancestor, ancestorChild, ourChild, mergeSituation, mergeStrategyForChild, pathToFileInRepository);
            }

            // ancestorChild, ourChild, and theirChild all exist.
            // But, it could be that we or they deleted and added something.
            // Check for edit vs delete+add, or there can be two items in ours, which is not legal.
            var match = mergeStrategyForChild.MergePartnerFinder.GetNodeToMerge(ourChild, ancestor, SetFromChildren.Get(ancestor));
            if (match == null)
            {
                // we deleted it and added a new one.
                if (XmlUtilities.AreXmlElementsEqual(theirChild, ancestorChild))
                {
                    // Our delete+add wins, since they did nothing.
                    merger.EventListener.ChangeOccurred(new XmlDeletionChangeReport(pathToFileInRepository, ancestor, ancestorChild));
                    merger.EventListener.ChangeOccurred(new XmlAdditionChangeReport(pathToFileInRepository, ourChild));
                    return ours;
                }

                // They edited old one, so they win over our delete+add.
                merger.ConflictOccurred(new RemovedVsEditedElementConflict(theirChild.Name, theirChild, null, ancestorChild,
                                                                           mergeSituation, mergeStrategyForChild,
                                                                           mergeSituation.BetaUserId));
                ours.ReplaceChild(ours.OwnerDocument.ImportNode(theirChild, true), ourChild);
                return ours;
            }
            match = mergeStrategyForChild.MergePartnerFinder.GetNodeToMerge(theirChild, ancestor, SetFromChildren.Get(ancestor));
            if (match == null)
            {
                // they deleted it and added a new one.
                if (XmlUtilities.AreXmlElementsEqual(ourChild, ancestorChild))
                {
                    // Their delete+add wins, since we did nothing.
                    merger.EventListener.ChangeOccurred(new XmlDeletionChangeReport(pathToFileInRepository, ancestor, ancestorChild));
                    merger.EventListener.ChangeOccurred(new XmlAdditionChangeReport(pathToFileInRepository, theirChild));
                    ours.ReplaceChild(ours.OwnerDocument.ImportNode(theirChild, true), ourChild);
                    return ours;
                }

                // We edited old one, so we win over their delete+add.
                merger.ConflictOccurred(new RemovedVsEditedElementConflict(ourChild.Name, ourChild, null, ancestorChild,
                                                                           mergeSituation, mergeStrategyForChild,
                                                                           mergeSituation.AlphaUserId));
                return ours;
            }

            merger.MergeInner(ref ourChild, theirChild, ancestorChild);

            // Route tested. (UsingWith_NumberOfChildrenAllowed_ZeroOrOne_DoesNotThrowWhenParentHasOneChildNode)
            return ours;
        }
        /// <summary>
        /// This handles merging of the custom component configurations into
        /// the configuration file including dependencies.
        /// </summary>
        /// <param name="id">The ID of the component to merge</param>
        /// <param name="info">The build component definition</param>
        /// <param name="rootNode">The root container node</param>
        /// <param name="configNode">The configuration node to merge</param>
        /// <param name="isConceptualConfig">True if this is a conceptual
        /// content configuration file or false if it is a reference build
        /// configuration file.</param>
        private void MergeComponent(string id, BuildComponentInfo info, XmlNode rootNode, XmlNode configNode,
          bool isConceptualConfig)
        {
            BuildComponentInfo depInfo;
            ComponentPosition position;
            XmlNodeList matchingNodes;
            XmlNode node;
            string replaceId;

            // Merge dependent component configurations first
            if(info.Dependencies.Count != 0)
                foreach(string dependency in info.Dependencies)
                {
                    node = rootNode.SelectSingleNode("component[@id='" + dependency + "']");

                    // If it's already there or would create a circular
                    // dependency, ignore it.
                    if(node != null || mergeStack.Contains(dependency))
                        continue;

                    // Add the dependency with a default configuration
                    if(!BuildComponentManager.BuildComponents.TryGetValue(dependency, out depInfo))
                        throw new BuilderException("BE0023", String.Format(
                            CultureInfo.InvariantCulture, "The project contains " +
                            "a reference to a custom build component '{0}' that " +
                            "has a dependency '{1}' that could not be found.",
                            id, dependency));

                    node = rootNode.OwnerDocument.CreateDocumentFragment();
                    node.InnerXml = reField.Replace(depInfo.DefaultConfiguration, fieldMatchEval);

                    this.ReportProgress("    Merging '{0}' dependency for '{1}'", dependency, id);

                    mergeStack.Push(dependency);
                    this.MergeComponent(dependency, depInfo, rootNode, node, isConceptualConfig);
                    mergeStack.Pop();
                }

            position = (!isConceptualConfig) ? info.ReferenceBuildPosition : info.ConceptualBuildPosition;

            // Find all matching components by ID or type name
            if(!String.IsNullOrEmpty(position.Id))
            {
                replaceId = position.Id;
                matchingNodes = rootNode.SelectNodes("component[@id='" + replaceId + "']");
            }
            else
            {
                replaceId = position.TypeName;
                matchingNodes = rootNode.SelectNodes("component[@type='" + replaceId + "']");
            }

            // If replacing another component, search for that by ID or
            // type and replace it if found.
            if(position.Place == ComponentPosition.Placement.Replace)
            {
                if(matchingNodes.Count < position.AdjustedInstance)
                {
                    this.ReportProgress("    Could not find configuration '{0}' (instance {1}) to replace with " +
                        "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id);

                    // If it's a dependency, that's a problem
                    if(mergeStack.Count != 0)
                        throw new BuilderException("BE0024", "Unable to add dependent configuration: " + id);

                    return;
                }

                rootNode.ReplaceChild(configNode, matchingNodes[position.AdjustedInstance - 1]);

                this.ReportProgress("    Replaced configuration for '{0}' (instance {1}) with configuration " +
                    "for '{2}'", replaceId, position.AdjustedInstance, id);

                // Adjust instance values on matching components
                foreach(BuildComponentInfo component in BuildComponentManager.BuildComponents.Values)
                  if(!isConceptualConfig)
                  {
                    if(((!String.IsNullOrEmpty(component.ReferenceBuildPosition.Id) &&
                      component.ReferenceBuildPosition.Id == replaceId) ||
                      (String.IsNullOrEmpty(component.ReferenceBuildPosition.Id) &&
                      component.ReferenceBuildPosition.TypeName == replaceId)) &&
                      component.ReferenceBuildPosition.AdjustedInstance >
                      position.AdjustedInstance)
                        component.ReferenceBuildPosition.AdjustedInstance--;
                  }
                  else
                      if(((!String.IsNullOrEmpty(component.ConceptualBuildPosition.Id) &&
                        component.ConceptualBuildPosition.Id == replaceId) ||
                        (String.IsNullOrEmpty(component.ConceptualBuildPosition.Id) &&
                        component.ConceptualBuildPosition.TypeName == replaceId)) &&
                        component.ConceptualBuildPosition.AdjustedInstance >
                        position.AdjustedInstance)
                          component.ConceptualBuildPosition.AdjustedInstance--;

                return;
            }

            // See if the configuration already exists.  If so, replace it.
            // We'll assume it's already in the correct location.
            node = rootNode.SelectSingleNode("component[@id='" + id + "']");

            if(node != null)
            {
                this.ReportProgress("    Replacing default configuration for '{0}' with the custom configuration", id);
                rootNode.ReplaceChild(configNode, node);
                return;
            }

            // Create the node and add it in the correct location
            switch(position.Place)
            {
                case ComponentPosition.Placement.Start:
                    rootNode.InsertBefore(configNode, rootNode.ChildNodes[0]);
                    this.ReportProgress("    Added configuration for '{0}' to the start of the configuration file", id);
                    break;

                case ComponentPosition.Placement.End:
                    rootNode.InsertAfter(configNode,
                        rootNode.ChildNodes[rootNode.ChildNodes.Count - 1]);
                    this.ReportProgress("    Added configuration for '{0}' to the end of the configuration file", id);
                    break;

                case ComponentPosition.Placement.Before:
                    if(matchingNodes.Count < position.AdjustedInstance)
                        this.ReportProgress("    Could not find configuration '{0}' (instance {1}) to add " +
                            "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id);
                    else
                    {
                        rootNode.InsertBefore(configNode, matchingNodes[position.AdjustedInstance - 1]);
                        this.ReportProgress("    Added configuration for '{0}' before '{1}' (instance {2})",
                            id, replaceId, position.AdjustedInstance);
                    }
                    break;

                default:    // After
                    if(matchingNodes.Count < position.AdjustedInstance)
                        this.ReportProgress("    Could not find configuration '{0}' (instance {1}) to add " +
                            "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id);
                    else
                    {
                        rootNode.InsertAfter(configNode, matchingNodes[position.AdjustedInstance - 1]);
                        this.ReportProgress("    Added configuration for '{0}' after '{1}' (instance {2})",
                            id, replaceId, position.AdjustedInstance);
                    }
                    break;
            }
        }
Esempio n. 10
0
        private void AddNode(XmlNode node, XmlNode root)
        {
            string[] keyAttrs;
            GetElementKey keyMain = GetKeyMain(node, out keyAttrs);
            string[] keyVals = keyMain.KeyVals;
            string elementName = keyMain.ElementName;

            XmlNode extantNode = null;
            // Value may be null in the Dictionary, even if key is present.
            m_getElementTable.TryGetValue(keyMain, out extantNode);

            // Is the current node a derived node?
            string baseName = XmlUtils.GetOptionalAttributeValue(node, "base");
            if (baseName != null)
            {
                string id = XmlUtils.GetManditoryAttributeValue(node, keyAttrs[keyAttrs.Length - 1]);
                if (id == baseName)
                {
                    // it is an override.
                    if (extantNode == null)
                    {
                        // Possibly trying to override a derived element?
                        extantNode = GetElement(elementName, keyVals);
                        if (extantNode == null)
                            throw new Exception("no base found to override " + baseName);
                    }
                    GetElementKey keyBase = new GetElementKey(elementName, keyVals, m_baseDoc);
                    if (m_getElementTable.ContainsKey(keyBase))
                        throw new Exception("only one level of override is allowed " + baseName);
                    // Save the base node for future use.
                    m_baseDoc["Main"].AppendChild(m_baseDoc.ImportNode(extantNode, true));
                    m_getElementTable[keyBase] = extantNode;
                    // Immediately compute the effect of the override and save it, replacing the base.
                    XmlNode unified = Unify(node, extantNode);
                    root.ReplaceChild(unified, extantNode);
                    // and update the cache, which is loaded with the old element
                    m_getElementTable[keyMain] = unified;
                }
                else
                {
                    // it is a normal alteration node
                    if (extantNode != null)
                    {
                        // derived node displaces non-derived one.
                        root.RemoveChild(extantNode);
                    }
                }
                // alteration node goes into alterations doc (displacing any previous alteration
                // with the same key).
                GetElementKey keyAlterations = new GetElementKey(elementName, keyVals, m_alterationsDoc);
                extantNode = null;
                if (m_getElementTable.ContainsKey(keyAlterations))
                    extantNode = m_getElementTable[keyAlterations]; // May still be null.
                CopyNodeToDoc(node, extantNode, m_alterationsDoc, keyAlterations);
            }
            else // not an override, just save it, replacing existing node if needed
            {
                CopyNodeToDoc(node, extantNode, m_mainDoc, keyMain);
            }
        }
Esempio n. 11
0
        private static void SetOrReplaceXmlElement(
            XmlNode parent,
            XmlElement newElement)
        {
            string attrNameValue = newElement.GetAttribute("name");
            string elementType = newElement.Name;

            XmlElement existingElment;
            if (TryFindElementWithAndroidName(parent, attrNameValue, out existingElment, elementType))
            {
                parent.ReplaceChild(newElement, existingElment);
            }
            else
            {
                parent.AppendChild(newElement);
            }
        }
Esempio n. 12
0
 private void _replaceNode(XmlNode vPrent, XmlNode vDest, XmlNode vSrc){
   if(vPrent != null){
     XmlNode newNode = this._cloneNode(vPrent.OwnerDocument, vSrc);
     vPrent.ReplaceChild(newNode, vDest);
   }
 }
Esempio n. 13
0
 /// <summary>
 /// This should be used when we want to replace a child element in our document with the contents
 /// found in their equivalent child.
 /// </summary>
 internal static void ReplaceOursWithTheirs(XmlNode ourParent, ref XmlNode ours, XmlNode theirs)
 {
     if (ourParent == null)
         throw new ArgumentNullException("ourParent");
     var ourOwnerDocument = ourParent.OwnerDocument;
     if (ourOwnerDocument == null)
         throw new ArgumentException("This method can not be used to replace root nodes.");
     if (theirs == null)
     {
         if (ours != null) // If both are null there is nothing to do, but if theirs is null delete ours
         {
             ourParent.RemoveChild(ours);
             ours = null;
         }
     }
     else
     {
         var theirData = theirs.Clone();
         theirData = ourOwnerDocument.ImportNode(theirData, true);
         if (ours == null)
             ourParent.AppendChild(theirData);
         else
             ourParent.ReplaceChild(theirData, ours);
         ours = theirData;
     }
 }
Esempio n. 14
0
        private void DecorateInvestment(int jobKeyCode, ref XmlNode investment, Hashtable htInstrumentTypes, XmlDocument xdocOutput)
        {
            string tktr = String.Empty;
            string name = String.Empty;
            string desc = String.Empty;
            string assetTypeLookup = String.Empty;
            string assetType = String.Empty;
            string investmentType = String.Empty;
            string exchCode = String.Empty;
            string country = String.Empty;
            string cusip = String.Empty;
            string coupon = String.Empty;
            string maturity= String.Empty;
            string accrualDaysPerMonth = String.Empty;
            string accrualDaysPerYear = String.Empty;

            foreach (XmlNode node in investment.ChildNodes)
            {
                try
                {
                    switch (node.Name.ToUpper())
                    {
                        case "ASSETTYPE":
                            assetType = node.InnerText.Trim();
                            break;
                        case "NAME":
                            name = node.InnerText.Trim();
                            break;
                        case "TICKER":
                            if (htIntlOptions.ContainsKey(investment.SelectSingleNode("Investment").InnerText.Trim()))
                                tktr = htIntlOptions[investment.SelectSingleNode("Investment").InnerText.Trim()].ToString();
                            else
                                tktr = node.InnerText.Trim();
                            break;
                        case "SECURITY_DES":
                            desc = node.InnerText.Trim();
                            break;
                        case "EQY_SH_OUT_REAL":
                        case "EQY_SH_OUT":
                        case "EQY_SH_OUT_ACTUAL":
                            if (node.InnerText.Equals("N.A."))
                                node.InnerText = String.Empty;
                            break;
                        case "EXCH_CODE":
                            exchCode = node.InnerText.Trim();
                            break;
                        case "ID_CUSIP":
                        case "ID_SEDOL1":
                        case "ID_ISIN":
                            if (node.Name.ToUpper().Equals("ID_CUSIP"))
                                cusip = node.InnerText.Trim();
                            if (node.InnerText.Trim().Equals("N.A."))
                                node.InnerText = String.Empty;
                            break;
                        case "OPT_UNDL_TICKER":
                            node.InnerText = node.InnerText.Trim().Replace(" US", "");
                            break;
                        case "OPT_EXPIRE_DT":
                            DateTime dt = DateTime.MinValue;
                            DateTime.TryParse(node.InnerText.Trim(), out dt);
                            if (!dt.Equals(DateTime.MinValue))
                                node.InnerText = dt.ToString("yyyy-MM-ddTHH:mm:ss");
                            break;
                        case "MATURITY":
                            maturity = node.InnerText.Trim();
                            break;
                        case "CPN":
                            coupon = node.InnerText.Trim();
                            break;
                        case "COUNTRY":
                            country = node.InnerText.Trim();
                            break;
                        case "CPN_FREQ":
                            switch (node.InnerText.Trim())
                            {
                                case "1":
                                    node.InnerText = "Annual";
                                    break;
                                case "2":
                                    node.InnerText = "Semi Annual";
                                    break;
                                case "4":
                                    node.InnerText = "Quarterly";
                                    break;
                                case "12":
                                    node.InnerText = "Monthly";
                                    break;
                            }
                            break;
                        case "DAY_CNT_DES":
                            accrualDaysPerMonth = node.InnerXml.Substring(node.InnerXml.LastIndexOf('-') + 1);
                            accrualDaysPerMonth = accrualDaysPerMonth.Substring(0, accrualDaysPerMonth.LastIndexOf('/'));
                            accrualDaysPerYear = node.InnerXml.Substring(node.InnerXml.LastIndexOf('/')+1);
                            break;
                    }
                }
                catch (Exception exc)
                {
                    log.Warn(jobKeyCode, exc);
                }
            }

            //check for non_US exchange code and fix BB ticker by appending exchange
            if (!exchCode.Equals("US") && investment.SelectSingleNode("AssetType").InnerXml.Equals("Equity"))
            {
                string[] keys = investment.SelectSingleNode("TICKER").InnerXml.Split(' ');

                if (keys != null && !keys[keys.Length - 1].Equals(exchCode))
                {
                    investment.SelectSingleNode("TICKER").InnerXml = investment.SelectSingleNode("TICKER").InnerXml + " " + exchCode;
                }
            }

            string id = assetType.ToUpper().Equals("FIXED INCOME") ? cusip : tktr;
            if (!id.Equals(String.Empty) && !name.Equals(String.Empty))
            {
                if (!htInstrumentTypes.ContainsKey(id))
                {
                    if (!htInstrumentTypes.ContainsKey(name))
                    {
                        if (!htInstrumentTypes.ContainsKey(id + " " + exchCode))
                        {
                            log.ErrorFormat(jobKeyCode, "Error in instrument type lookup for {0}", id);
                        }
                        else
                            assetTypeLookup = htInstrumentTypes[id + " " + exchCode].ToString();
                    }
                    else
                        assetTypeLookup = htInstrumentTypes[name].ToString();
                }
                else
                    assetTypeLookup = htInstrumentTypes[id].ToString();
            }

            switch (assetTypeLookup.ToUpper())
            {
                case "EQ":
                case "EQB":
                case "EQI":
                case "EQUITY":
                case "STOCK":
                case "IDX":
                case "INDEX":
                case "PREFERRED":
                case "PFD":
                case "WRNT":
                case "WRNTI":
                case "WARRANT":

                    assetType = "Equity";
                    if (investment.Name.IndexOf(" ADR") > -1)
                        investmentType = "Depository receipt";
                    else
                        investmentType = "Ordinary Share";

                    break;

                case "OPT":
                case "OPTI":
                case "OPTION":

                    assetType = "Option";
                    investmentType = "Equity";

                    break;

                case "FI":
                case "FIGOV":
                case "BOND":

                    assetType = "Fixed Income";
                    investmentType = "Bond";
                    desc = String.Format("{0} {1} {2}", name, coupon.Trim().TrimEnd('0'), maturity);
                    exchCode = country;

                    break;
            }

            XmlNode investmentTypeNode = xdocOutput.CreateNode(XmlNodeType.Element, "InvestmentType", "");
            investmentTypeNode.InnerText = investmentType;
            investment.AppendChild(investmentTypeNode);

            if (investmentType.ToUpper().Equals("BOND"))
            {
                XmlNode accrualDaysPerMonthNode = xdocOutput.CreateNode(XmlNodeType.Element, "AccrualDaysPerMonth", "");
                accrualDaysPerMonthNode.InnerText = accrualDaysPerMonth;
                investment.AppendChild(accrualDaysPerMonthNode);

                XmlNode accrualDaysPerYearNode = xdocOutput.CreateNode(XmlNodeType.Element, "AccrualDaysPerYear", "");
                accrualDaysPerYearNode.InnerText = accrualDaysPerYear;
                investment.AppendChild(accrualDaysPerYearNode);

                XmlNode longDecriptionNode = xdocOutput.CreateNode(XmlNodeType.Element, "LongDescription", "");
                longDecriptionNode.InnerText = desc;
                investment.AppendChild(longDecriptionNode);

                XmlNode exchNode = investment.SelectSingleNode("EXCH_CODE");
                exchNode.InnerText = country;
                investment.ReplaceChild(exchNode, investment.SelectSingleNode("EXCH_CODE"));
                //investment.AppendChild(exchNode);
            }

            if(assetType.Equals("Option"))
            {
                XmlNode n = investment.SelectSingleNode("TICKER");
                XmlNode nExch = investment.SelectSingleNode("EXCH_CODE");

                string[] keys = n.InnerXml.Split(' ');
                if (keys.Length == 3 && n!= null && nExch != null)
                {
                    string exchange =
                    n.InnerXml = String.Format("{0} {1} {2} {3}", keys[0], nExch.InnerXml, keys[1], keys[2]);
                }
            }

        }
 private static void InlineUses(IReadOnlyDictionary<string, XmlNode> map, XmlNode xmlNode)
 {
     var childNodes = xmlNode.ChildNodes;
     for (var i = 0; i < childNodes.Count; i++)
     {
         var childNode = childNodes[i];
         if (childNode.Name == "use")
         {
             var href = childNode.Attributes.GetNamedItem("href", "http://www.w3.org/1999/xlink");
             var hrefValue = href.Value;
             if (!hrefValue.StartsWith("#"))
             {
                 throw new UnsupportedFormatException("Only references within an SVG document are allowed.");
             }
             childNode.Attributes.Remove((XmlAttribute)href);
             hrefValue = hrefValue.Substring(1);
             childNode = CreateInline(childNode, map[hrefValue].CloneNode(true));
             xmlNode.ReplaceChild(childNode, childNodes[i]);
         }
         InlineUses(map, childNode);
     }
 }
Esempio n. 16
0
        private static string[] ExpandIncludes(XmlNode section, string baseDirectory, List <string> parentFileList)
        {
            List <string> includeFileList = new List <string>();

            if (section.SelectNodes(String.Format("//{1}[@{0}]", PathToken, IncludeToken)).Count > 0)
            {
                if (!String.IsNullOrEmpty(baseDirectory) && !parentFileList.Contains(baseDirectory) && Path.HasExtension(baseDirectory))
                {
                    parentFileList.Add(baseDirectory);
                }

                if (!String.IsNullOrEmpty(baseDirectory) && Path.HasExtension(baseDirectory))
                {
                    baseDirectory = Path.GetDirectoryName(baseDirectory);
                }

                XmlDocument ownerDocument = section is XmlDocument ? section as XmlDocument : section.OwnerDocument;

                foreach (XmlElement includeElement in section.SelectNodes(String.Format("//{1}[@{0}]", PathToken, IncludeToken)))
                {
                    if (includeElement == null)
                    {
                        continue;
                    }

                    string includeFileName = includeElement.GetAttribute(PathToken);

                    bool    isFirstChild = true;
                    XmlNode lastChild    = null;
                    XmlNode parentNode   = includeElement.ParentNode;
                    foreach (XmlNode newNode in ExpandIncludeNode(ownerDocument, baseDirectory, parentFileList, includeFileList, includeElement))
                    {
                        if (isFirstChild)
                        {
                            isFirstChild = false;
                            lastChild    = newNode;

                            parentNode.ReplaceChild(newNode, includeElement);
                            parentNode.InsertBefore(ownerDocument.CreateComment(String.Format(String.Format("DO NOT REMOVE - BEGIN INCLUDE {0}", includeFileName))), newNode);
                        }
                        else
                        {
                            parentNode.InsertAfter(newNode, lastChild);
                            lastChild = newNode;
                        }

                        if (newNode.NodeType == XmlNodeType.Element)
                        {
                            ExpandIncludes(newNode, baseDirectory, parentFileList);
                        }
                    }

                    if (lastChild.Name != IncludeToken)
                    {
                        parentNode.InsertAfter(ownerDocument.CreateComment(String.Format(String.Format("DO NOT REMOVE - END INCLUDE {0}", includeFileName))), lastChild);
                    }
                    else
                    {
                        parentNode.AppendChild(ownerDocument.CreateComment(String.Format(String.Format("DO NOT REMOVE - END INCLUDE {0}", includeFileName))));
                    }
                }
            }
            return(includeFileList.ToArray());
        }
Esempio n. 17
0
        private static void AddBondAttributes(XmlDocument xdocNewInvestmentData, XmlNode xnodeInvestment, string name, ref string desc, ref string exchCode, string country, string coupon, string maturity, string accrualDaysPerMonth, string accrualDaysPerYear)
        {
            desc = String.Format("{0} {1} {2}", name, coupon.Trim().TrimEnd('0'), maturity);
            exchCode = country;

            XmlNode accrualDaysPerMonthNode = xdocNewInvestmentData.CreateNode(XmlNodeType.Element, "AccrualDaysPerMonth", "");
            accrualDaysPerMonthNode.InnerText = accrualDaysPerMonth.Replace("ACT", "Actual");
            xnodeInvestment.AppendChild(accrualDaysPerMonthNode);

            XmlNode accrualDaysPerYearNode = xdocNewInvestmentData.CreateNode(XmlNodeType.Element, "AccrualDaysPerYear", "");
            accrualDaysPerYearNode.InnerText = accrualDaysPerYear.Replace("ACT", "Actual"); ;
            xnodeInvestment.AppendChild(accrualDaysPerYearNode);

            XmlNode longDecriptionNode = xdocNewInvestmentData.CreateNode(XmlNodeType.Element, "LongDescription", "");
            longDecriptionNode.InnerText = desc;
            xnodeInvestment.AppendChild(longDecriptionNode);

            XmlNode exchNode = xnodeInvestment.SelectSingleNode("EXCH_CODE");
            exchNode.InnerText = country;
            xnodeInvestment.ReplaceChild(exchNode, xnodeInvestment.SelectSingleNode("EXCH_CODE"));
        }
        private static void AddTypes(XmlDocument swaggerDocument, XmlNode node, string ns, string element, string typeName)
        {
            if (ns == null && element == null)
            {
                return;
            }

            var type = node.SelectSingleNode("type");

            XmlElement xmltype = swaggerDocument.CreateElement(type.Name);
            xmltype.SetAttribute("namespace", ns);
            xmltype.SetAttribute("element", element);
            xmltype.InnerXml = typeName;

            node.ReplaceChild(xmltype, type);
        }
        private void ConvertRoutingTableRoutingItemChildNode(XmlNode routingTable, bool isInternalExternal, string oldChildNodeName, string newChildNodeName)
        {
            if ((null == routingTable) || (string.IsNullOrEmpty(oldChildNodeName)) || (string.IsNullOrEmpty(newChildNodeName)))
                return;

            XmlNode oldNode = routingTable.SelectSingleNode(oldChildNodeName);
            if (null == oldNode)
                return;

            XmlNode newNode = routingTable.OwnerDocument.CreateElement(newChildNodeName);
            XmlAttribute channelTypeAttribute = routingTable.Attributes["type"];
            Workshare.Policy.ChannelType channelType = Workshare.Policy.TypeConverters.GetChannelType(channelTypeAttribute.Value);
           
            foreach (XmlNode addressCollectionNode in oldNode.ChildNodes)
            {
                XmlNode routingItemCollectionNode = routingTable.OwnerDocument.CreateElement("RoutingItemCollection");
                CopyAttributes(addressCollectionNode, routingItemCollectionNode);
                newNode.AppendChild(routingItemCollectionNode);

                if (Workshare.Policy.ChannelType.SMTP == channelType)
                {
                    InsertSmtpRoutingAssemblyInformation(routingItemCollectionNode, isInternalExternal);
                }
            }

            routingTable.ReplaceChild(newNode, oldNode);
        }
 private static void MergePropertyAndGroup(XmlNode newParent, XmlNode mergingParent, string name)
 {
     Dictionary<string, XmlNode> propertyDict = new Dictionary<string, XmlNode>();
     Dictionary<string, XmlNode> groupDict = new Dictionary<string, XmlNode>();
     string value = "";
     //record the first property node where the Group node to insert before
     XmlNode firstProperty = null;
     foreach (XmlNode child in mergingParent.ChildNodes)
     {
         if (child.NodeType == XmlNodeType.Element)
         {
             value = child.Attributes[name].Value;
             try
             {
                 if (child.Name == "Property")
                 {
                     propertyDict.Add(value, child);
                 }
                 else
                     groupDict.Add(value, child);
             }
             catch
             {
                 throw new InvalidOperationException("Duplicate node with type\"" + child.Name + "name \"" + name + "\"=\"" + value + "\" found.");
             }
         }
     }
     foreach (XmlNode child in groupDict.Values)
     {
         bool duplicate = false;
         XmlNode old = null;
         foreach (XmlNode xn in newParent.ChildNodes)
         {
             if (xn.NodeType != XmlNodeType.Element)
                 continue;
             if (xn.Name == "Property" && firstProperty == null)
             {
                 firstProperty = xn;
                 continue;
             }
             if (xn.Name == "Group" && xn.Attributes[name].Value == child.Attributes[name].Value)
             {
                 duplicate = true;
                 old = xn;
                 break;
             }
         }
         if (duplicate)
         {
             MergePropertyAndGroup(old, child.CloneNode(true), name);
         }
         else
         {
             if(firstProperty == null)
                 newParent.AppendChild(child.CloneNode(true));
             else
                 newParent.InsertBefore(child.CloneNode(true), firstProperty);
         }
     }
     foreach (XmlNode child in propertyDict.Values)
     {
         bool duplicate = false;
         XmlNode old = null;
         foreach (XmlNode xn in newParent.ChildNodes)
         {
             if (xn.NodeType != XmlNodeType.Element || xn.Name != "Property")
                 continue;
             if (xn.Attributes[name].Value == child.Attributes[name].Value)
             {
                 duplicate = true;
                 old = xn;
                 break;
             }
         }
         if (duplicate)
         {
             newParent.ReplaceChild(child.CloneNode(true), old);
         }
         else
         {
             newParent.AppendChild(child.CloneNode(true));
         }
     }
     groupDict.Clear();
     propertyDict.Clear();
 }
 private void replaceCodeBase(XmlNode node, string path)
 {
     XmlNode identity = node.FirstChild;
        XmlNode codebase = identity.NextSibling;
        Uri fileURI = new Uri(Path.Combine(path, Path.Combine(@"web\bin", ((XmlElement)identity).GetAttribute("name") + ".dll")));
        string ns = codebase.GetNamespaceOfPrefix(String.Empty);
        XmlElement element = configDoc.CreateElement(String.Empty, "codeBase", ns);
        element.SetAttribute("href", fileURI.AbsoluteUri);
        node.ReplaceChild(element, codebase);
 }
Esempio n. 22
0
        private void BuildGenevaInvestment(int jobKeyCode, ref XmlNode investment, Hashtable htInstrumentTypes, XmlDocument xdocOutput)
        {
            string tktr = String.Empty;
            string name = String.Empty;
            string desc = String.Empty;
            string assetTypeLookup = String.Empty;
            string assetType = String.Empty;
            string investmentType = String.Empty;
            string exchCode = String.Empty;
            string country = String.Empty;
            string cusip = String.Empty;
            string coupon = String.Empty;
            string maturity = String.Empty;
            string accrualDaysPerMonth = String.Empty;
            string accrualDaysPerYear = String.Empty;

            //add additional Geneva-specific investment attributes
            XmlNode investmentTypeNode = xdocOutput.CreateNode(XmlNodeType.Element, "InvestmentType", "");
            investment.AppendChild(investmentTypeNode);

            //transform or decorate Geneva-specific attributes
            foreach (XmlNode node in investment.ChildNodes)
            {
                try
                {
                    switch (node.Name.ToUpper())
                    {
                        case "ASSETTYPE":
                            assetType = node.InnerText.Trim();
                            switch (assetType)
                            {
                                case "Fixed Income":
                                case "FI":
                                case "FIGOV":
                                case "FIGOVI":
                                case "FISOV":
                                case "FII":
                                case "FICONV":
                                case "FI144A":
                                    node.InnerText = "Bond";
                                    break;
                            }
                            break;

                        case "NAME":
                            name = node.InnerText.Trim();
                            break;
                        case "TICKER":
                            if (htIntlOptions.ContainsKey(investment.SelectSingleNode("Investment").InnerText.Trim()))
                                tktr = htIntlOptions[investment.SelectSingleNode("Investment").InnerText.Trim()].ToString();
                            else
                                tktr = node.InnerText.Trim();
                            break;
                        case "SECURITY_DES":
                            desc = node.InnerText.Trim();
                            break;
                        case "EQY_SH_OUT_REAL":
                        case "EQY_SH_OUT":
                        case "EQY_SH_OUT_ACTUAL":
                            if (node.InnerText.Equals("N.A."))
                                node.InnerText = String.Empty;
                            break;
                        case "EXCH_CODE":
                            exchCode = node.InnerText.Trim();
                            break;
                        case "ID_CUSIP":
                        case "ID_SEDOL1":
                        case "ID_ISIN":
                            if (node.Name.ToUpper().Equals("ID_CUSIP"))
                                cusip = node.InnerText.Trim();
                            if (node.InnerText.Trim().Equals("N.A."))
                                node.InnerText = String.Empty;
                            break;
                        case "OPT_UNDL_TICKER":
                            node.InnerText = node.InnerText.Trim().Replace(" US", "");
                            break;
                        case "OPT_EXPIRE_DT":
                            DateTime dt = DateTime.MinValue;
                            DateTime.TryParse(node.InnerText.Trim(), out dt);
                            if (!dt.Equals(DateTime.MinValue))
                                node.InnerText = dt.ToString("yyyy-MM-ddTHH:mm:ss");
                            break;
                        case "MATURITY":
                            maturity = node.InnerText.Trim();
                            break;
                        case "CPN":
                            coupon = node.InnerText.Trim();
                            break;
                        case "COUNTRY":
                            country = node.InnerText.Trim();
                            break;
                        case "CPN_FREQ":
                            switch (node.InnerText.Trim())
                            {
                                case "1":
                                    node.InnerText = "Annual";
                                    break;
                                case "2":
                                    node.InnerText = "Semi Annual";
                                    break;
                                case "4":
                                    node.InnerText = "Quarterly";
                                    break;
                                case "12":
                                    node.InnerText = "Monthly";
                                    break;
                            }
                            break;
                        case "DAY_CNT_DES":
                            accrualDaysPerMonth = node.InnerXml.Substring(node.InnerXml.LastIndexOf('-') + 1);
                            accrualDaysPerMonth = accrualDaysPerMonth.Substring(0, accrualDaysPerMonth.LastIndexOf('/'));
                            accrualDaysPerYear = node.InnerXml.Substring(node.InnerXml.LastIndexOf('/') + 1);
                            break;
                        case "INVESTMENTTYPE":
                            assetType = investment.SelectSingleNode("AssetType").InnerXml;

                            switch (assetType.ToUpper())
                            {
                                case "EQUITY":

                                    if (investment.Name.IndexOf(" ADR") > -1)
                                        investmentType = "Depository receipt";
                                    else
                                        investmentType = "Ordinary Share";

                                    node.InnerText = investmentType;

                                    break;

                                case "OPTION":

                                    investmentType = "Equity";
                                    node.InnerText = investmentType;

                                    XmlNode nTicker = investment.SelectSingleNode("TICKER");
                                    XmlNode nExch = investment.SelectSingleNode("EXCH_CODE");

                                    string[] keys = nTicker.InnerXml.Split(' ');
                                    if (keys.Length == 3 && nTicker != null && nExch != null && nExch.InnerXml.Trim() != "US")
                                    {
                                        string exchange =
                                        nTicker.InnerXml = String.Format("{0} {1} {2} {3}", keys[0], nExch.InnerXml, keys[1], keys[2]);
                                    }
                                    else
                                    {
                                        XmlNode bloombergTicker = xdocOutput.CreateNode(XmlNodeType.Element, "BloombergTicker", "");
                                        bloombergTicker.InnerText = nTicker.InnerXml;
                                        investment.AppendChild(bloombergTicker);

                                        if (ifUseOccSymbol)
                                            nTicker.InnerXml = investment.SelectSingleNode("OCC_SYMBOL").InnerXml;
                                    }

                                    break;

                                case "BOND":
                                case "FIXED INCOME":

                                    investmentType = "Bond";
                                    node.InnerText = investmentType;

                                    desc = String.Format("{0} {1} {2}", name, coupon.Trim().TrimEnd('0'), maturity);
                                    exchCode = country;

                                    XmlNode accrualDaysPerMonthNode = xdocOutput.CreateNode(XmlNodeType.Element, "AccrualDaysPerMonth", "");
                                    accrualDaysPerMonthNode.InnerText = accrualDaysPerMonth.Replace("ACT", "Actual");
                                    investment.AppendChild(accrualDaysPerMonthNode);

                                    XmlNode accrualDaysPerYearNode = xdocOutput.CreateNode(XmlNodeType.Element, "AccrualDaysPerYear", "");
                                    accrualDaysPerYearNode.InnerText = accrualDaysPerYear.Replace("ACT", "Actual");
                                    investment.AppendChild(accrualDaysPerYearNode);

                                    XmlNode longDecriptionNode = xdocOutput.CreateNode(XmlNodeType.Element, "LongDescription", "");
                                    longDecriptionNode.InnerText = desc;
                                    investment.AppendChild(longDecriptionNode);

                                    XmlNode exchNode = investment.SelectSingleNode("EXCH_CODE");
                                    exchNode.InnerText = country;
                                    investment.ReplaceChild(exchNode, investment.SelectSingleNode("EXCH_CODE"));

                                    break;

                                case "FUTURE":

                                    if (investment.SelectSingleNode("MARKET_SECTOR_DES") != null)
                                    {
                                        switch (investment.SelectSingleNode("MARKET_SECTOR_DES").InnerXml)
                                        {
                                            case "Comdty":
                                                node.InnerText = "Commodity";
                                                break;
                                            case "Index":
                                                node.InnerText = "Index";
                                                break;
                                            case "Curncy":
                                                node.InnerText = "Currency";
                                                break;
                                        }
                                    }
                                    else
                                        node.InnerText = "Commodity";

                                    break;
                            }

                            break;

                        //case "PX_POS_MULT_FACTOR":
                        //    XmlNode tradingFactorNode = xdocOutput.CreateNode(XmlNodeType.Element, "TradingFactor", "");
                        //    tradingFactorNode.InnerText = node.InnerText;
                        //    investment.AppendChild(tradingFactorNode);
                        //    break;

                        //case "FUT_LAST_TRADE_DT":
                        //    XmlNode expireDateNode = xdocOutput.CreateNode(XmlNodeType.Element, "ExpireDate", "");
                        //    expireDateNode.InnerText = node.InnerText;
                        //    investment.AppendChild(expireDateNode);
                        //    break;
                    }
                }
                catch (Exception exc)
                {
                    log.Warn(jobKeyCode, exc);
                }
            }

            //check for non_US exchange code and fix BB ticker by appending exchange
            if (!exchCode.Equals("US") && investment.SelectSingleNode("AssetType").InnerXml.Equals("Equity"))
            {
                string[] keys = investment.SelectSingleNode("TICKER").InnerXml.Split(' ');

                if (keys != null && !keys[keys.Length - 1].Equals(exchCode))
                {
                    investment.SelectSingleNode("TICKER").InnerXml = investment.SelectSingleNode("TICKER").InnerXml + " " + exchCode;
                }
            }
        }
Esempio n. 23
0
        private static string HandleNode(XmlNode node)
        {
            var cNodes = node.SelectNodes("c");
            var codeNodes = node.SelectNodes("code");
            var list = cNodes.Cast<XmlNode>().Concat<XmlNode>(codeNodes.Cast<XmlNode>());

            foreach (XmlNode cNode in list)
            {
                XmlElement pre = node.OwnerDocument.CreateElement("pre");
                XmlElement code = node.OwnerDocument.CreateElement("code");
                code.InnerXml = HandleNode(cNode);
                pre.AppendChild(code);
                node.ReplaceChild(pre, cNode);
            }

            cNodes = node.SelectNodes("para");
            foreach (XmlNode cNode in cNodes)
            {
                XmlElement p = node.OwnerDocument.CreateElement("p");
                p.InnerXml = HandleNode(cNode);
                node.ReplaceChild(p, cNode);
            }

            list = node.SelectNodes("paramref").Cast<XmlNode>().Concat<XmlNode>(node.SelectNodes("typeparamref").Cast<XmlNode>());
            foreach (XmlNode cNode in list)
            {
                XmlElement p = node.OwnerDocument.CreateElement("b");
                var attr = node.Attributes["name"];
                p.InnerXml = attr != null ? attr.InnerText : "";
                node.ReplaceChild(p, cNode);
            }

            cNodes = node.SelectNodes("see");
            foreach (XmlNode cNode in cNodes)
            {
                var attr = node.Attributes["cref"];
                XmlText p = node.OwnerDocument.CreateTextNode(string.Format("{{@link {0}}}", attr != null ? attr.InnerText : ""));
                node.ReplaceChild(p, cNode);
            }

            RemoveNodes(node, "include");
            RemoveNodes(node, "list");
            RemoveNodes(node, "permission");

            return node.InnerXml.Trim();
        }
Esempio n. 24
0
 /// <summary>
 /// 解析sqlNode
 /// </summary>
 /// <param name="sqlNode">sql节点</param>
 /// <returns>解析后的sql</returns>
 public static XmlNode AnalyzeChildSqlNode(XmlNode sqlNode, List<IDbDataParameter> parmeters)
 {
     /*
      * <isEmpty property="ZTECntNo">d.zte_cnt_no like #ZTECntNo#</isNotEmpty>
      * <isNotEmpty property="ZTECntNo">d.zte_cnt_no like #ZTECntNo#</isNotEmpty>
      * <isEqual  property="IsShowSended" compareValue="0"></isEqual>
      * <isNotEqual property="IsShowSended" compareValue="0"></isNotEqual>
      */
     sqlNode = sqlNode.Clone();
     if (parmeters != null && parmeters.Count > 0)
     {
         //去除isEmpty
         var isEmptyList = sqlNode.SelectNodes("isEmpty");
         foreach (XmlNode node in isEmptyList)
         {
             string nodeproperty = node.Attributes["property"].Value;
             var p = (from o in parmeters
                      where o.ParameterName.ToLower() == nodeproperty.ToLower() || o.ParameterName.ToLower() == "@" + nodeproperty.ToLower()
                      select o).FirstOrDefault();
             //如果没有此属性,那么去除此节点
             //如果此属性中有值,那么也去除此节点
             if (p == null)
             {
                 sqlNode.ReplaceChild(AnalyzeChildSqlNode(node, parmeters), node);
             }
             else if (p.Value is DBNull == false)
             {
                 sqlNode.RemoveChild(node);
             }
             else
             {
                 sqlNode.ReplaceChild(AnalyzeChildSqlNode(node, parmeters), node);
             }
         }
         //去除isNotEmpty
         var isNotEmptyList = sqlNode.SelectNodes("isNotEmpty");
         foreach (XmlNode node in isNotEmptyList)
         {
             string nodeproperty = node.Attributes["property"].Value;
             var p = (from o in parmeters
                      where o.ParameterName.ToLower() == nodeproperty.ToLower() || o.ParameterName.ToLower() == "@" + nodeproperty.ToLower()
                      select o).FirstOrDefault();
             //如果没有此属性,那么去除此节点
             //如果此属性中无值,那么也去除此节点
             if (p == null || p.Value is DBNull)
             {
                 sqlNode.RemoveChild(node);
             }
             else
             {
                 sqlNode.ReplaceChild(AnalyzeChildSqlNode(node, parmeters), node);
             }
         }
         //去除isEqual
         var isEqualList = sqlNode.SelectNodes("isEqual");
         foreach (XmlNode node in isEqualList)
         {
             string nodeProperty = node.Attributes["property"].Value;
             string nodeValue = node.Attributes["compareValue"].Value;
             var p = (from o in parmeters
                      where o.ParameterName.ToLower() == nodeProperty.ToLower() || o.ParameterName.ToLower() == "@" + nodeProperty.ToLower()
                      select o).FirstOrDefault();
             //如果没有此属性,那么去除此节点
             //如果此属性中无值,那么也去除此节点
             if (p == null || p.Value.ToStringEx().ToLower().Equals(nodeValue.ToLower()) == false)
             {
                 sqlNode.RemoveChild(node);
             }
             else
             {
                 sqlNode.ReplaceChild(AnalyzeChildSqlNode(node, parmeters), node);
             }
         }
         //去除isNotEqual
         var isNotEqualList = sqlNode.SelectNodes("isNotEqual");
         foreach (XmlNode node in isNotEqualList)
         {
             string nodeProperty = node.Attributes["property"].Value;
             string nodeValue = node.Attributes["compareValue"].Value;
             var p = (from o in parmeters
                      where o.ParameterName.ToLower() == nodeProperty.ToLower() || o.ParameterName.ToLower() == "@" + nodeProperty.ToLower()
                      select o).FirstOrDefault();
             //如果没有此属性,那么去除此节点
             //如果此属性中无值,那么也去除此节点
             if (p == null || p.Value.ToStringEx().ToLower().Equals(nodeValue.ToLower()))
             {
                 sqlNode.RemoveChild(node);
             }
             else
             {
                 sqlNode.ReplaceChild(AnalyzeChildSqlNode(node, parmeters), node);
             }
         }
     }
     return sqlNode;
 }
Esempio n. 25
0
		private void FleshOutProxy(XmlNode currentNode, XmlDocument dom)
		{
			string sTarget = XmlUtils.GetAttributeValue(currentNode, "target");
			XmlNode xn = dom.SelectSingleNode("//item[@id='" + sTarget + "']");
			if (xn != null)
			{
				XmlAttribute idAttr = dom.CreateAttribute("id");
				idAttr.Value = sTarget;
				currentNode.Attributes.Append(idAttr);
				XmlAttribute typeAttr = (XmlAttribute)xn.SelectSingleNode("@type");
				if (typeAttr != null)
					currentNode.Attributes.Append((XmlAttribute)typeAttr.Clone());
				// replace any abbrev, term or def items from target and add any citations in target
				string[] asNodes =  new string[3] {"abbrev", "term", "def"};
				for (int i = 0; i<3; i++)
				{
					XmlNode newTempNode = xn.SelectSingleNode(asNodes[i]);
					XmlNode oldNode = currentNode.SelectSingleNode(asNodes[i]);
					if (newTempNode != null)
					{
						if (oldNode != null)
							currentNode.ReplaceChild(newTempNode.Clone(), oldNode);
						else
							currentNode.AppendChild(newTempNode.Clone());
					}
				}
				XmlNodeList citationNodes = xn.SelectNodes("citation");
				foreach (XmlNode citation in citationNodes)
				{
					currentNode.AppendChild(citation.Clone());
				}
			}
		}
        private static XmlNode HandleCaseOfNoAncestor(XmlMerger merger, XmlNode ours, XmlNode theirs)
        {
            var mainNodeStrategy = merger.MergeStrategies.GetElementStrategy(ours ?? theirs);
            var mergeSituation = merger.MergeSituation;
            var pathToFileInRepository = mergeSituation.PathToFileInRepository;
            if (ours == null)
            {
                // They added, we did nothing.
            // Route tested, but the MergeChildrenMethod adds the change report for us.
                // So, theory has it one can't get here from any normal place.
                // But, keep it, in case MergeChildrenMethod gets 'fixed'.
                merger.EventListener.ChangeOccurred(new XmlAdditionChangeReport(pathToFileInRepository, theirs));
                return theirs;
            }
            if (theirs == null)
            {
                // We added, they did nothing.
            // Route tested.
                merger.EventListener.ChangeOccurred(new XmlAdditionChangeReport(pathToFileInRepository, ours));
                return ours;
            }

            // Both added the special containing node.
            // Remove children nodes to see if main containing nodes are the same.
            if (XmlUtilities.AreXmlElementsEqual(ours, theirs))
            {
            // Route tested.
                // Same content.
                merger.EventListener.ChangeOccurred(new XmlBothAddedSameChangeReport(pathToFileInRepository, ours));
            }
            else
            {
                // Different content.
                var ourChild = GetElementChildren(ours).FirstOrDefault();
                var theirChild = GetElementChildren(theirs).FirstOrDefault();
                var ourClone = MakeClone(ours);
                var theirClone = MakeClone(theirs);
                if (XmlUtilities.AreXmlElementsEqual(ourClone, theirClone))
                {
                    // new main elements are the same, but not the contained child
                    merger.EventListener.ChangeOccurred(new XmlBothAddedSameChangeReport(pathToFileInRepository, ourClone));
                    if (ourChild == null && theirChild == null)
                        return ours; // Nobody added the child node.
                    if (ourChild == null)
                    {
                        merger.EventListener.ChangeOccurred(new XmlAdditionChangeReport(pathToFileInRepository, theirChild));
                        ours.AppendChild(theirChild);
                        return ours;
                    }
                    if (theirChild == null)
                    {
                        merger.EventListener.ChangeOccurred(new XmlAdditionChangeReport(pathToFileInRepository, ourChild));
                        return ours;
                    }
                    // both children exist, but are different.
                    var mergeStrategyForChild = merger.MergeStrategies.GetElementStrategy(ourChild);
                    if (merger.MergeSituation.ConflictHandlingMode == MergeOrder.ConflictHandlingModeChoices.WeWin)
                    {
                        // Do the clone thing on the two child nodes to see if the diffs are in the child or lower down.
                        var ourChildClone = MakeClone(ourChild);
                        var theirChildClone = MakeClone(theirChild);
                        if (XmlUtilities.AreXmlElementsEqual(ourChildClone, theirChildClone))
                        {
                            var ourChildReplacement = ourChild;
                            merger.MergeInner(ref ourChildReplacement, theirChild, null);
                            if (!ReferenceEquals(ourChild, ourChildReplacement))
                            {
                                ours.ReplaceChild(ours.OwnerDocument.ImportNode(ourChildReplacement, true), ourChild);
                            }
                        }
                        else
                        {
                            merger.ConflictOccurred(new BothAddedMainElementButWithDifferentContentConflict(ourChild.Name, ourChild, theirChild,
                                                                                                            mergeSituation, mergeStrategyForChild,
                                                                                                            mergeSituation.AlphaUserId));
                        }
                    }
                    else
                    {
                        // Do the clone thing on the two child nodes to see if the diffs are in the child or lower down.
                        var ourChildClone = MakeClone(ourChild);
                        var theirChildClone = MakeClone(theirChild);
                        if (XmlUtilities.AreXmlElementsEqual(ourChildClone, theirChildClone))
                        {
                            var ourChildReplacement = ourChild;
                            merger.MergeInner(ref ourChildReplacement, theirChild, null);
                            if (!ReferenceEquals(ourChild, ourChildReplacement))
                            {
                                ours.ReplaceChild(ours.OwnerDocument.ImportNode(ourChildReplacement, true), ourChild);
                            }
                        }
                        else
                        {
                            merger.ConflictOccurred(new BothAddedMainElementButWithDifferentContentConflict(ourChild.Name, ourChild, theirChild,
                                                                                                            mergeSituation, mergeStrategyForChild,
                                                                                                            mergeSituation.AlphaUserId));
                            ours.ReplaceChild(ours.OwnerDocument.ImportNode(theirChild, true), ourChild);
                        }
                    }
                    return ours;
                }

                // Main containing element is not the same. Not to worry about child
                if (merger.MergeSituation.ConflictHandlingMode == MergeOrder.ConflictHandlingModeChoices.WeWin)
                {
                    merger.ConflictOccurred(new BothAddedMainElementButWithDifferentContentConflict(ours.Name, ours, theirs,
                                                                                                    mergeSituation, mainNodeStrategy,
                                                                                                    mergeSituation.AlphaUserId));
                }
                else
                {
                    merger.ConflictOccurred(new XmlTextBothAddedTextConflict(theirs.Name, theirs, ours, mergeSituation,
                                                                             mainNodeStrategy, mergeSituation.BetaUserId));
                    ours = theirs;
                }
            }
            return ours;
        }
        /// <summary>
        /// This handles merging of the custom component configurations into the configuration file including
        /// dependencies.
        /// </summary>
        /// <param name="id">The ID of the component to merge</param>
        /// <param name="factory">The build component factory</param>
        /// <param name="rootNode">The root container node</param>
        /// <param name="configNode">The configuration node to merge</param>
        /// <param name="isConceptualConfig">True if this is a conceptual content configuration file or false if
        /// it is a reference build configuration file.</param>
        /// <param name="mergeStack">A stack used to check for circular build component dependencies.  Pass null
        /// on the first non-recursive call.</param>
        private void MergeComponent(string id, BuildComponentFactory factory, XmlNode rootNode, XmlNode configNode,
          bool isConceptualConfig, Stack<string> mergeStack)
        {
            BuildComponentFactory dependencyFactory;
            ComponentPlacement position;
            XmlNodeList matchingNodes;
            XmlNode node;
            string replaceId;

            // Merge dependent component configurations first
            if(factory.Dependencies.Any())
            {
                if(mergeStack == null)
                    mergeStack = new Stack<string>();

                foreach(string dependency in factory.Dependencies)
                {
                    node = rootNode.SelectSingleNode("component[@id='" + dependency + "']");

                    // If it's already there or would create a circular dependency, ignore it
                    if(node != null || mergeStack.Contains(dependency))
                        continue;

                    // Add the dependency with a default configuration
                    if(!buildComponents.TryGetValue(dependency, out dependencyFactory))
                        throw new BuilderException("BE0023", String.Format(CultureInfo.CurrentCulture,
                            "The project contains a reference to a custom build component '{0}' that has a " +
                            "dependency '{1}' that could not be found.", id, dependency));

                    node = rootNode.OwnerDocument.CreateDocumentFragment();
                    node.InnerXml = substitutionTags.TransformText(dependencyFactory.DefaultConfiguration);

                    this.ReportProgress("    Merging '{0}' dependency for '{1}'", dependency, id);

                    mergeStack.Push(dependency);
                    this.MergeComponent(dependency, dependencyFactory, rootNode, node, isConceptualConfig, mergeStack);
                    mergeStack.Pop();
                }
            }

            position = (!isConceptualConfig) ? factory.ReferenceBuildPlacement : factory.ConceptualBuildPlacement;

            // Find all matching components by ID
            replaceId = position.Id;
            matchingNodes = rootNode.SelectNodes("component[@id='" + replaceId + "']");

            // If replacing another component, search for that by ID and replace it if found
            if(position.Placement == PlacementAction.Replace)
            {
                if(matchingNodes.Count < position.AdjustedInstance)
                {
                    this.ReportProgress("    Could not find configuration '{0}' (instance {1}) to replace with " +
                        "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id);

                    // If it's a dependency, that's a problem
                    if(mergeStack.Count != 0)
                        throw new BuilderException("BE0024", "Unable to add dependent configuration: " + id);

                    return;
                }

                rootNode.ReplaceChild(configNode, matchingNodes[position.AdjustedInstance - 1]);

                this.ReportProgress("    Replaced configuration for '{0}' (instance {1}) with configuration " +
                    "for '{2}'", replaceId, position.AdjustedInstance, id);

                // Adjust instance values on matching components
                foreach(var component in buildComponents.Values)
                    if(!isConceptualConfig)
                    {
                        if(component.ReferenceBuildPlacement.Id == replaceId &&
                          component.ReferenceBuildPlacement.AdjustedInstance > position.AdjustedInstance)
                        {
                            component.ReferenceBuildPlacement.AdjustedInstance--;
                        }
                    }
                    else
                        if(component.ConceptualBuildPlacement.Id == replaceId &&
                          component.ConceptualBuildPlacement.AdjustedInstance > position.AdjustedInstance)
                        {
                            component.ConceptualBuildPlacement.AdjustedInstance--;
                        }

                return;
            }

            // See if the configuration already exists.  If so, replace it.
            // We'll assume it's already in the correct location.
            node = rootNode.SelectSingleNode("component[@id='" + id + "']");

            if(node != null)
            {
                this.ReportProgress("    Replacing default configuration for '{0}' with the custom configuration", id);
                rootNode.ReplaceChild(configNode, node);
                return;
            }

            // Create the node and add it in the correct location
            switch(position.Placement)
            {
                case PlacementAction.Start:
                    rootNode.InsertBefore(configNode, rootNode.ChildNodes[0]);
                    this.ReportProgress("    Added configuration for '{0}' to the start of the configuration file", id);
                    break;

                case PlacementAction.End:
                    rootNode.InsertAfter(configNode,
                        rootNode.ChildNodes[rootNode.ChildNodes.Count - 1]);
                    this.ReportProgress("    Added configuration for '{0}' to the end of the configuration file", id);
                    break;

                case PlacementAction.Before:
                    if(matchingNodes.Count < position.AdjustedInstance)
                        this.ReportProgress("    Could not find configuration '{0}' (instance {1}) to add " +
                            "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id);
                    else
                    {
                        rootNode.InsertBefore(configNode, matchingNodes[position.AdjustedInstance - 1]);
                        this.ReportProgress("    Added configuration for '{0}' before '{1}' (instance {2})",
                            id, replaceId, position.AdjustedInstance);
                    }
                    break;

                default:    // After
                    if(matchingNodes.Count < position.AdjustedInstance)
                        this.ReportProgress("    Could not find configuration '{0}' (instance {1}) to add " +
                            "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id);
                    else
                    {
                        rootNode.InsertAfter(configNode, matchingNodes[position.AdjustedInstance - 1]);
                        this.ReportProgress("    Added configuration for '{0}' after '{1}' (instance {2})",
                            id, replaceId, position.AdjustedInstance);
                    }
                    break;
            }
        }
Esempio n. 28
0
    private static void createFieldElement(ref System.Xml.XmlDocument pdoc, string pid, string pname, string pcore, string KolonneType)
    {
        System.Xml.XmlElement field = pdoc.CreateElement("", "Field", ns);
        field.SetAttribute("ID", pid);
        field.SetAttribute("Name", pname);
        field.SetAttribute("DisplayName", "$Resources:" + pcore + "," + pname + ";");

        switch (KolonneType)
        {
        case "Text":
            field.SetAttribute("Type", "Text");
            field.SetAttribute("MaxLength", "255");
            break;

        case "Note":
            field.SetAttribute("Type", "Note");
            field.SetAttribute("NumLines", "3");
            field.SetAttribute("RichText", "TRUE");
            break;

        case "Choice":
            field.SetAttribute("Type", "Choice");
            break;

        case "Number":
            field.SetAttribute("Type", "Number");
            field.SetAttribute("Decimals", "0");
            break;

        case "Percentage":
            field.SetAttribute("Type", "Number");
            field.SetAttribute("Percentage", "TRUE");
            field.SetAttribute("Min", "0");
            field.SetAttribute("Max", "1");
            break;

        case "Currency":
            field.SetAttribute("Type", "Currency");
            field.SetAttribute("Decimals", "2");
            break;

        case "DateOnly":
            field.SetAttribute("Type", "DateTime");
            field.SetAttribute("Format", "DateOnly");
            break;

        case "DateTime":
            field.SetAttribute("Type", "DateTime");
            break;

        case "Boolean":
            field.SetAttribute("Type", "Boolean");
            break;

        default:
            break;
        }

        field.SetAttribute("Group", "$Resources:" + pcore + ",FieldsGroupName;");

        System.Xml.XmlNode elements = pdoc.SelectSingleNode("//mha:Elements", nsMgr);
        string             filter   = "//mha:Field[@ID=\"" + pid + "\"]";

        System.Xml.XmlNode old_field = elements.SelectSingleNode(filter, nsMgr);

        if (old_field == null)
        {
            elements.AppendChild(field);
        }
        else
        {
            elements.ReplaceChild(field, old_field);
        }
    }
Esempio n. 29
0
    //
    //createListElement
    //
    private static void createListElement(
        ref System.Xml.XmlDocument pdoc,
        string pname,
        string pcore,
        System.Collections.Generic.List <pvMetadata.ListtemplateContenttype> ptypestable,
        System.Collections.Generic.List <pvMetadata.ListtemplateColumn> pfieldstable)
    {
        //
        // Insert ContentTypeRef
        //
        System.Xml.XmlNode contenttypes = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes", s_nsMgr);
        foreach (ListtemplateContenttype typ in ptypestable)
        {
            string ContentTypeID;
            switch (typ.BasedOn)
            {
            case "Element":
                ContentTypeID = "0x01" + "00" + typ.typeGUID;
                break;

            case "Annoncering":
                ContentTypeID = "0x0104" + "00" + typ.typeGUID;
                break;

            case "Hyperlink":
                ContentTypeID = "0x0105" + "00" + typ.typeGUID;
                break;

            case "'Kontaktperson":
                ContentTypeID = "0x0106" + "00" + typ.typeGUID;
                break;

            case "'Meddelelse":
                ContentTypeID = "0x0107" + "00" + typ.typeGUID;
                break;

            case "'Opgave":
                ContentTypeID = "0x0108" + "00" + typ.typeGUID;
                break;

            case "'Problem":
                ContentTypeID = "0x0103" + "00" + typ.typeGUID;
                break;

            default:
                ContentTypeID = "Error" + "00" + typ.typeGUID;
                break;
            }

            System.Xml.XmlElement contenttyperef      = pdoc.CreateElement("", "ContentTypeRef", s_ns);
            System.Xml.XmlComment contenttypescomment = pdoc.CreateComment(typ.SysName);
            contenttyperef.SetAttribute("ID", ContentTypeID);

            System.Xml.XmlNode ContentTypeRef0x01 = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes/mha:ContentTypeRef[@ID=\"0x01\"]", s_nsMgr);
            if (ContentTypeRef0x01 == null)
            {
                System.Xml.XmlNode lastContentTypeRef = contenttypes.AppendChild(contenttyperef);
                contenttypes.InsertBefore(contenttypescomment, lastContentTypeRef);
            }
            else
            {
                System.Xml.XmlNode Folder = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes/mha:ContentTypeRef[@ID=\"0x01\"]/mha:Folder", s_nsMgr);
                if (Folder != null)
                {
                    System.Xml.XmlNode copyFolder = Folder.CloneNode(true);
                    contenttyperef.AppendChild(copyFolder);
                }
                contenttypes.InsertBefore(contenttypescomment, ContentTypeRef0x01);
                contenttypes.ReplaceChild(contenttyperef, ContentTypeRef0x01);
            }
        }


        System.Collections.Generic.SortedDictionary <string, ListtemplateColumn> scol = new System.Collections.Generic.SortedDictionary <string, ListtemplateColumn>();
        foreach (ListtemplateColumn col in pfieldstable)
        {
            scol.Add(col.Seqnr, col);
        }

        //
        // Insert Field in Fields
        //
        System.Xml.XmlNode fields = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:Fields", s_nsMgr);
        foreach (ListtemplateColumn col in scol.Values)
        {
            if (!col.SysCol)
            {
                System.Xml.XmlElement fieldref = pdoc.CreateElement("", "Field", s_ns);
                fieldref.SetAttribute("Name", col.SysName);
                fieldref.SetAttribute("ID", col.colGUID);

                fieldref.SetAttribute("DisplayName", "$Resources:" + pcore + "," + col.SysName + ";");
                switch (col.KolonneType)
                {
                case "Text":
                    fieldref.SetAttribute("Type", "Text");
                    break;

                case "Note":
                    fieldref.SetAttribute("Type", "Note");
                    fieldref.SetAttribute("NumLines", "3");
                    fieldref.SetAttribute("RichText", "TRUE");
                    break;

                case "Choice":
                    fieldref.SetAttribute("Type", "Choice");
                    break;

                case "Number":
                    fieldref.SetAttribute("Type", "Number");
                    fieldref.SetAttribute("Decimals", "0");
                    break;

                case "Percentage":
                    fieldref.SetAttribute("Type", "Number");
                    fieldref.SetAttribute("Percentage", "TRUE");
                    fieldref.SetAttribute("Min", "0");
                    fieldref.SetAttribute("Max", "1");
                    break;

                case "Currency":
                    fieldref.SetAttribute("Type", "Currency");
                    fieldref.SetAttribute("Decimals", "2");
                    break;

                case "DateOnly":
                    fieldref.SetAttribute("Type", "DateTime");
                    fieldref.SetAttribute("Format", "DateOnly");
                    break;

                case "DateTime":
                    fieldref.SetAttribute("Type", "DateTime");
                    break;

                case "Boolean":
                    fieldref.SetAttribute("Type", "Boolean");
                    break;

                case "Counter":
                    fieldref.SetAttribute("Type", "Counter");
                    break;

                case "Picture":
                    fieldref.SetAttribute("Type", "Picture");
                    break;

                case "Hyperlink":
                    fieldref.SetAttribute("Type", "Hyperlink");
                    break;

                default:
                    break;
                }

                fields.AppendChild(fieldref);
            }
        }


        //
        // Insert FieldsRef in ViewFields
        //
        System.Xml.XmlNode viewfields = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:Views/mha:View[@BaseViewID=\"1\"]/mha:ViewFields", s_nsMgr);
        foreach (ListtemplateColumn col in scol.Values)
        {
            if (!col.SysCol)
            {
                System.Xml.XmlElement fieldref = pdoc.CreateElement("", "FieldRef", s_ns);
                fieldref.SetAttribute("ID", col.colGUID);
                fieldref.SetAttribute("Name", col.SysName);
                viewfields.AppendChild(fieldref);
            }
        }
    }
// Methods
    internal override void Apply( XmlNode parent, ref XmlNode currentPosition )
    {
        Debug.Assert( _matchNode.ParentNode == parent ||
                     ( _matchNode.ParentNode == null && _matchNode.NodeType == XmlNodeType.Attribute ) || 
                       _matchNode.NodeType == XmlNodeType.XmlDeclaration ||
                       _matchNode.NodeType == XmlNodeType.DocumentType );

        switch ( _matchNode.NodeType )
        {
            case XmlNodeType.Element:
            {
                Debug.Assert( _value == null );

                if ( _name == null )   _name = ((XmlElement)_matchNode).LocalName;
                if ( _ns == null )     _ns = ((XmlElement)_matchNode).NamespaceURI;
                if ( _prefix == null ) _prefix = ((XmlElement)_matchNode).Prefix;

                XmlElement newEl = parent.OwnerDocument.CreateElement( _prefix, _name, _ns );

				// move attributes
				XmlAttributeCollection attrs = _matchNode.Attributes;
				while ( attrs.Count > 0 )
				{
					XmlAttribute attr = (XmlAttribute)attrs.Item( 0 );
					attrs.RemoveAt( 0 );
					newEl.Attributes.Append( attr );
				}

				// move children
                XmlNode curChild = _matchNode.FirstChild;
                while ( curChild != null )
                {
                    XmlNode nextSibling = curChild.NextSibling;
                    _matchNode.RemoveChild( curChild );
                    newEl.AppendChild( curChild );
                    curChild = nextSibling;
                }

                parent.ReplaceChild( newEl, _matchNode );
                currentPosition = newEl;

                ApplyChildren( newEl );

                break;
            }
            case XmlNodeType.Attribute:
            {
                if ( _name == null )   _name = ((XmlAttribute)_matchNode).LocalName;
                if ( _ns == null )     _ns = ((XmlAttribute)_matchNode).NamespaceURI;
                if ( _prefix == null ) _prefix = ((XmlAttribute)_matchNode).Prefix;
                if ( _value == null )  _value = ((XmlAttribute)_matchNode).Value;

                XmlAttribute newAttr = parent.OwnerDocument.CreateAttribute( _prefix, _name, _ns );
                newAttr.Value = _value;

                parent.Attributes.Remove( (XmlAttribute)_matchNode );
                parent.Attributes.Append( newAttr );
                break;
            }
            case XmlNodeType.Text:
            case XmlNodeType.CDATA:
            case XmlNodeType.Comment:
                Debug.Assert( _value != null );
                ((XmlCharacterData)_matchNode).Data = _value;
                currentPosition = _matchNode;
                break;
            case XmlNodeType.ProcessingInstruction:
            {
                if ( _name != null ) 
                {
                    if ( _value == null )  
                        _value = ((XmlProcessingInstruction)_matchNode).Data;
                    XmlProcessingInstruction newPi = parent.OwnerDocument.CreateProcessingInstruction( _name, _value );

                    parent.ReplaceChild( newPi, _matchNode );
                    currentPosition = newPi;
                }
                else
                {
                    ((XmlProcessingInstruction)_matchNode).Data = _value;
                    currentPosition = _matchNode;
                }
                break;
            }
            case XmlNodeType.EntityReference:
            {
                Debug.Assert( _name != null );
                
                XmlEntityReference newEr = parent.OwnerDocument.CreateEntityReference( _name );
                
                parent.ReplaceChild( newEr, _matchNode );
                currentPosition = newEr;
                break;
            }
            case XmlNodeType.XmlDeclaration:
            {
                Debug.Assert( _value != null && _value != string.Empty );
                XmlDeclaration xmlDecl = (XmlDeclaration)_matchNode;
                xmlDecl.Encoding = null;
                xmlDecl.Standalone = null;
                xmlDecl.InnerText = _value;
                break;
            }
            case XmlNodeType.DocumentType:
            {
                if ( _name == null )
                    _name = ((XmlDocumentType)_matchNode).LocalName;

                if ( _ns == null )
                    _ns = ((XmlDocumentType)_matchNode).SystemId;
                else if ( _ns == string.Empty )
                    _ns = null;

                if ( _prefix == null ) 
                    _prefix = ((XmlDocumentType)_matchNode).PublicId;
                else if ( _prefix == string.Empty ) 
                    _prefix = null;

                if ( _value == null )  
                    _value = ((XmlDocumentType)_matchNode).InternalSubset;

                XmlDocumentType docType = _matchNode.OwnerDocument.CreateDocumentType( _name, _prefix, _ns, _value );
                _matchNode.ParentNode.ReplaceChild( docType, _matchNode );
                break;
            }
            default:
                Debug.Assert( false ); 
                break;
        }
    }
Esempio n. 31
0
        internal static XmlNode ProcessSageLinkElement(SageContext context, XmlNode node)
        {
            Contract.Requires<ArgumentNullException>(node != null);
            if (node.SelectSingleElement("ancestor::sage:literal", XmlNamespaces.Manager) != null)
                return node;

            XmlElement linkElem = (XmlElement) node;
            string linkName = context.ProcessText(linkElem.GetAttribute("ref"));
            bool rawString = linkElem.GetAttribute("raw").EqualsAnyOf("1", "yes", "true");

            if (!string.IsNullOrEmpty(linkName) && rawString)
            {
                if (context.Url.Links.ContainsKey(linkName))
                {
                    linkElem.InnerText = context.Url.Links[linkName].Value;
                }

                return linkElem;
            }

            string linkHref = context.Url.GetUrl(linkElem);
            if (!string.IsNullOrEmpty(linkHref))
            {
                linkElem.SetAttribute("href", linkHref);
            }

            foreach (XmlNode child in node.ChildNodes)
            {
                XmlNode processed = NodeEvaluator.GetNodeHandler(child)(context, child);
                if (processed != null)
                    node.ReplaceChild(processed, child);
                else
                    node.RemoveChild(child);
            }

            return linkElem;
        }
Esempio n. 32
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Appends or replaces a node.
		/// </summary>
		/// <param name="parentNode">The parent node.</param>
		/// <param name="childElement">The child element.</param>
		/// <param name="attribute">The attribute.</param>
		/// <param name="attrValue">The attribute value.</param>
		/// ------------------------------------------------------------------------------------
		private static void AppendOrReplaceNode(XmlNode parentNode, XmlNode childElement,
			string attribute, string attrValue)
		{
			var oldChild = GetChildNode(parentNode, childElement.Name, attribute, attrValue);
			if (oldChild != null)
				parentNode.ReplaceChild(childElement, oldChild);
			else
				parentNode.AppendChild(childElement);
		}
Esempio n. 33
0
		protected void ReplaceNode(XmlNode element, XmlNode newNode, XmlNode oldNode)
		{
			if (newNode == oldNode)
			{
				return;
			}

			var importedNode = ImportNode(element, newNode);

			element.ReplaceChild(importedNode, oldNode);
		}
Esempio n. 34
0
		private static void UpdateNode(XmlNode parentElement, XmlNode updateChild, string path)
		{
			XmlElement existingElement = parentElement.SelectSingleNode(path) as XmlElement;
			if (existingElement != null)
				parentElement.ReplaceChild(parentElement.OwnerDocument.ImportNode(updateChild, true), existingElement);
			else
				parentElement.AppendChild(parentElement.OwnerDocument.ImportNode(updateChild, true));
		}
Esempio n. 35
0
        private void walkBodyNodes(XmlNode node, HTMLParserContext parseContext)
        {
            XmlNodeList list = node.ChildNodes;
            for (int index = 0; index < list.Count; ++index )
            {
                XmlNode newNode = parseContext.replaceNode(list[index]);

                if (node.HasChildNodes && node != parseContext.IntermediateRootElement)
                {
                    //if (newNode.HasChildNodes)
                    //{
                    //    walkBodyNodes(newNode, parseContext); //Context of the original attributes is gone here so this should be moved to replaceNode
                    //}
                    node.ReplaceChild(newNode, list[index]);
                }
                else
                {
                    node.AppendChild(newNode);
                }

            }
        }
        private static void AppendOrOverrideChild(XmlNode newFather, XmlNode fatherOfChildren, string name)
        {
            Dictionary<string, XmlNode> dict = new Dictionary<string, XmlNode>();
            string value = "";
            foreach (XmlNode child in fatherOfChildren.ChildNodes)
            {
                if (child.NodeType == XmlNodeType.Element)
                {
                    value = child.Attributes[name].Value;
                    try
                    {
                        dict.Add(value, child);
                    }
                    catch
                    {
                        throw new InvalidOperationException("Duplicate node with name \"" + name + "\"=\"" + value + "\" found.");
                    }
                }
            }

            foreach (XmlNode child in dict.Values)
            {
                bool duplicate = false;

                XmlNode old = null;
                foreach (XmlNode xn in newFather.ChildNodes)
                {
                    if (xn.NodeType != XmlNodeType.Element)
                        continue;

                    if (xn.Attributes[name].Value == child.Attributes[name].Value)
                    {
                        duplicate = true;
                        old = xn;
                        break;
                    }
                }
                if (duplicate)
                {
                    newFather.ReplaceChild(child.CloneNode(true), old);
                }
                else
                {
                    newFather.AppendChild(child.CloneNode(true));
                }
            }

            dict.Clear();
        }
        //Append or override report child node
        private static void AppendOrOverrideChildNode(XmlNode newFather, XmlNode importChild, string name)
        {
            string value = importChild.Attributes[name].Value;
            bool duplicate = false;

            XmlNode old = null;
            foreach (XmlNode xn in newFather.ChildNodes)
            {
                if (xn.NodeType != XmlNodeType.Element)
                    continue;
                if (xn.Name != importChild.Name)
                    continue;
                if (xn.Attributes[name].Value == value)
                {
                    duplicate = true;
                    old = xn;
                    break;
                }
            }
            if (duplicate)
            {
                newFather.ReplaceChild(importChild.CloneNode(true), old);
            }
            else
            {
                newFather.AppendChild(importChild.CloneNode(true));
            }
        }
 private static XmlNode HandleCaseOfNoAncestorChild(XmlMerger merger, XmlNode ours, XmlNode ourChild, XmlNode theirChild)
 {
     var mergeSituation = merger.MergeSituation;
     var pathToFileInRepository = mergeSituation.PathToFileInRepository;
     var mergeStrategyForChild = merger.MergeStrategies.GetElementStrategy(ourChild ?? theirChild);
     if (ourChild == null)
     {
         // they added child.
         merger.EventListener.ChangeOccurred(new XmlAdditionChangeReport(pathToFileInRepository, theirChild));
         ours.AppendChild(theirChild);
         return ours;
     }
     if (theirChild == null)
     {
         // We added child.
         merger.EventListener.ChangeOccurred(new XmlAdditionChangeReport(pathToFileInRepository, ourChild));
         return ours;
     }
     // Both added child.
     if (XmlUtilities.AreXmlElementsEqual(ourChild, theirChild))
     {
         // Both are the same.
         merger.EventListener.ChangeOccurred(new XmlBothAddedSameChangeReport(pathToFileInRepository, ourChild));
         return ours;
     }
     // Both are different.
     if (XmlUtilities.IsTextLevel(ourChild, theirChild, null))
     {
         if (merger.MergeSituation.ConflictHandlingMode == MergeOrder.ConflictHandlingModeChoices.WeWin)
         {
             merger.ConflictOccurred(new XmlTextBothAddedTextConflict(ourChild.Name, ourChild, theirChild, mergeSituation,
                                                                      mergeStrategyForChild, mergeSituation.AlphaUserId));
         }
         else
         {
             merger.ConflictOccurred(new XmlTextBothAddedTextConflict(theirChild.Name, theirChild, ourChild, mergeSituation,
                                                                      mergeStrategyForChild, mergeSituation.BetaUserId));
             ours.ReplaceChild(ours.OwnerDocument.ImportNode(theirChild, true), ourChild);
         }
     }
     else
     {
         if (merger.MergeSituation.ConflictHandlingMode == MergeOrder.ConflictHandlingModeChoices.WeWin)
         {
             var ourChildClone = MakeClone(ourChild);
             var theirChildClone = MakeClone(theirChild);
             if (XmlUtilities.AreXmlElementsEqual(ourChildClone, theirChildClone))
             {
                 merger.EventListener.ChangeOccurred(new XmlAdditionChangeReport(pathToFileInRepository, ourChild));
                 var ourChildReplacement = ourChild;
                 merger.MergeInner(ref ourChildReplacement, theirChild, null);
                 if (!ReferenceEquals(ourChild, ourChildReplacement))
                 {
                     ours.ReplaceChild(ours.OwnerDocument.ImportNode(ourChildReplacement, true), ourChild);
                 }
             }
             else
             {
                 merger.ConflictOccurred(new BothAddedMainElementButWithDifferentContentConflict(ourChild.Name, ourChild, theirChild,
                                                                                                 mergeSituation, mergeStrategyForChild,
                                                                                                 mergeSituation.AlphaUserId));
             }
         }
         else
         {
             var ourChildClone = MakeClone(ourChild);
             var theirChildClone = MakeClone(theirChild);
             if (XmlUtilities.AreXmlElementsEqual(ourChildClone, theirChildClone))
             {
                 merger.EventListener.ChangeOccurred(new XmlAdditionChangeReport(pathToFileInRepository, theirChild));
                 var ourChildReplacement = ourChild;
                 merger.MergeInner(ref ourChildReplacement, theirChild, null);
                 if (!ReferenceEquals(ourChild, ourChildReplacement))
                 {
                     ours.ReplaceChild(ours.OwnerDocument.ImportNode(ourChildReplacement, true), ourChild);
                 }
             }
             else
             {
                 merger.ConflictOccurred(new BothAddedMainElementButWithDifferentContentConflict(theirChild.Name, theirChild, ourChild,
                                                                                                 mergeSituation, mergeStrategyForChild,
                                                                                                 mergeSituation.BetaUserId));
                 ours.ReplaceChild(ours.OwnerDocument.ImportNode(theirChild, true), ourChild);
             }
         }
     }
     return ours;
 }