Пример #1
0
        internal ExcelPicture(ExcelDrawings drawings, XmlNode node, Image image)
            : base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/@name")
        {
            XmlElement picNode = node.OwnerDocument.CreateElement("xdr", "pic", ExcelPackage.schemaSheetDrawings);
            node.InsertAfter(picNode,node.SelectSingleNode("xdr:to",NameSpaceManager));
            picNode.InnerXml = PicStartXml();

            node.InsertAfter(node.OwnerDocument.CreateElement("xdr", "clientData", ExcelPackage.schemaSheetDrawings), picNode);

            Package package = drawings.Worksheet.xlPackage.Package;
            //Get the picture if it exists or save it if not.
            _image = image;
            string relID = SavePicture(image);

            //Create relationship
            node.SelectSingleNode("xdr:pic/xdr:blipFill/a:blip/@r:embed", NameSpaceManager).Value = relID;

            SetPosDefaults(image);
            package.Flush();
        }
Пример #2
0
	    /// <summary>
	    /// Sorts the children of the parentNode that match the xpath selector 
	    /// </summary>
	    /// <param name="parentNode"></param>
	    /// <param name="childXPathSelector">An xpath expression used to select child nodes of the XmlElement</param>
	    /// <param name="childSelector">An expression that returns true if the XElement passed in is a valid child node to be sorted</param>
	    /// <param name="orderByValue">The value to order the results by</param>
	    internal static void SortNodes(
            XmlNode parentNode, 
            string childXPathSelector, 
            Func<XElement, bool> childSelector,
            Func<XElement, object> orderByValue)
	    {

            var xElement = parentNode.ToXElement();
            var children = xElement.Elements().Where(x => childSelector(x)).ToArray(); //(DONT conver to method group, the build server doesn't like it)
            
            var data = children
                .OrderByDescending(orderByValue)     //order by the sort order desc
                .Select(x => children.IndexOf(x))   //store the current item's index (DONT conver to method group, the build server doesn't like it)
                .ToList();

            //get the minimum index that a content node exists  in the parent
            var minElementIndex = xElement.Elements()
                .TakeWhile(x => childSelector(x) == false)
                .Count();

	        //if the minimum index is zero, then it is the very first node inside the parent,
            // if it is not, we need to store the child property node that exists just before the 
            // first content node found so we can insert elements after it when we're sorting.
            var insertAfter = minElementIndex == 0 ? null : parentNode.ChildNodes[minElementIndex - 1];

            var selectedChildren = parentNode.SelectNodes(childXPathSelector);
            if (selectedChildren == null)
            {
                throw new InvalidOperationException(string.Format("The childXPathSelector value did not return any results {0}", childXPathSelector));
            }

            var childElements = selectedChildren.Cast<XmlElement>().ToArray();

            //iterate over the ndoes starting with the node with the highest sort order.
            //then we insert this node at the begginning of the parent so that by the end
            //of the iteration the node with the least sort order will be at the top.
            foreach (var node in data.Select(index => childElements[index]))
            {
                if (insertAfter == null)
                {
                    parentNode.PrependChild(node);
                }
                else
                {
                    parentNode.InsertAfter(node, insertAfter);
                }
            }
        }
Пример #3
0
    private void checkAndCalculateProtectedID(XmlDocument message, XmlNode invoice)
    {
      // field ProtectedID is mandatory, but if it is not suplied it is going to be calculated!
      XmlNodeList protectedIDs = (invoice as XmlElement).GetElementsByTagName("fu:ProtectedID");
      if (protectedIDs.Count == 0)
      {
        ProtectiveMark pm = new ProtectiveMark();
        string protectedIDValue = pm.Calculate(invoice as XmlElement, Settings.CryptoProvider);

        // ProtectedID is not the last element in XML Schema, so we must put it in the right spot
        //    we are going from bottom up, searching for the right spot
        XmlNode protectedIDNode = XmlHelperFunctions.CreateElement(message, this.Settings.FursXmlNamespace, "ProtectedID", protectedIDValue);

        XmlNode currentNode = invoice.LastChild;
        while ((currentNode != null) && (this.isNodeAfterProtectedID(currentNode)))
          currentNode = currentNode.PreviousSibling;

        if (currentNode != null)
          invoice.InsertAfter(protectedIDNode, currentNode);
      }
    }
Пример #4
0
        internal ExcelPicture(ExcelDrawings drawings, XmlNode node, FileInfo imageFile, Uri hyperlink)
            : base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/@name")
        {
            XmlElement picNode = node.OwnerDocument.CreateElement("xdr", "pic", ExcelPackage.schemaSheetDrawings);
            node.InsertAfter(picNode, node.SelectSingleNode("xdr:to", NameSpaceManager));
            _hyperlink = hyperlink;
            picNode.InnerXml = PicStartXml();

            node.InsertAfter(node.OwnerDocument.CreateElement("xdr", "clientData", ExcelPackage.schemaSheetDrawings), picNode);

            //Changed to stream 2/4-13 (issue 14834). Thnx SClause
            var package = drawings.Worksheet._package.Package;
            ContentType = GetContentType(imageFile.Extension);
            var imagestream = new FileStream(imageFile.FullName, FileMode.Open, FileAccess.Read);
            _image = Image.FromStream(imagestream);
            ImageConverter ic = new ImageConverter();
            var img = (byte[])ic.ConvertTo(_image, typeof(byte[]));
            imagestream.Close();

            UriPic = GetNewUri(package, "/xl/media/{0}" + imageFile.Name);
            var ii = _drawings._package.AddImage(img, UriPic, ContentType);
            string relID;
            if(!drawings._hashes.ContainsKey(ii.Hash))
            {
                Part = ii.Part;
                RelPic = drawings.Part.CreateRelationship(UriHelper.GetRelativeUri(drawings.UriDrawing, ii.Uri), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/image");
                relID = RelPic.Id;
                _drawings._hashes.Add(ii.Hash, relID);
                AddNewPicture(img, relID);
            }
            else
            {
                relID = drawings._hashes[ii.Hash];
                var rel = _drawings.Part.GetRelationship(relID);
                UriPic = UriHelper.ResolvePartUri(rel.SourceUri, rel.TargetUri);
            }
            ImageHash = ii.Hash;
            _height = Image.Height;
            _width = Image.Width;
            SetPosDefaults(Image);
            //Create relationship
            node.SelectSingleNode("xdr:pic/xdr:blipFill/a:blip/@r:embed", NameSpaceManager).Value = relID;
            package.Flush();
        }
        /// <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;
            }
        }
Пример #6
0
        private static void WriteNode(XmlWriter writer, XmlNode nodeToWrite)
        {
            if (nodeToWrite.NodeType == XmlNodeType.Comment)
                writer.WriteComment(nodeToWrite.Value);
            else if (nodeToWrite.NodeType == XmlNodeType.Text)
            {
                writer.WriteValue(nodeToWrite.Value);
            }
            else if (nodeToWrite.NodeType == XmlNodeType.Whitespace)
            {
                writer.WriteWhitespace(nodeToWrite.Value);
            }
            else if (nodeToWrite.NodeType == XmlNodeType.SignificantWhitespace)
            {
                Console.WriteLine("SignificantWhitespace ignored");
            }
            else if (nodeToWrite.NodeType == XmlNodeType.Element)
            {
                string nodeName = nodeToWrite.Name;
                if (nodeName == "interface")
                    nodeName = "glade-interface";
                else if (nodeName == "object")
                    nodeName = "widget";

                writer.WriteStartElement(nodeName);
                // Write all attributes
                foreach (XmlAttribute attr in nodeToWrite.Attributes)
                {
                    // Add tab attribute as packing child (Fix for Glade#)
                    if (attr.Name == "type" && attr.Value == "tab")
                    {
                        XmlNode packingNode = nodeToWrite.SelectSingleNode("packing");
                        if (packingNode != null)
                        {
                            XmlElement propNode = nodeToWrite.OwnerDocument.CreateElement("property");
                            XmlAttribute attrType = nodeToWrite.OwnerDocument.CreateAttribute("name");
                            attrType.Value = "type";
                            propNode.Attributes.Append(attrType);
                            propNode.AppendChild(nodeToWrite.OwnerDocument.CreateTextNode("tab"));
                            packingNode.AppendChild(propNode);
                        }
                    }
                    else
                        writer.WriteAttributeString(attr.Name, attr.Value);
                }

                // Move accelerator after signal (Fix for Glade#)
                XmlNode acceleratorNode = nodeToWrite.SelectSingleNode("accelerator");
                if (acceleratorNode != null)
                {
                    XmlNodeList signalNodeList = nodeToWrite.SelectNodes("signal");
                    if (signalNodeList != null && signalNodeList.Count > 0)
                        nodeToWrite.InsertAfter(acceleratorNode, signalNodeList[signalNodeList.Count - 1]);
                }

                // Write all child nodes
                foreach (XmlNode childNode in nodeToWrite.ChildNodes)
                {
                    WriteNode(writer, childNode);
                }
                writer.WriteEndElement();
            }
        }
        /// <summary>
        /// Reorder type parameters.
        /// </summary>
        /// <param name="xmlNode">
        /// The xml node.
        /// </param>
        /// <param name="typeParameters">
        /// The type parameters.
        /// </param>
        private static void ReorderTypeParams(XmlNode xmlNode, IList<ITypeParameter> typeParameters)
        {
            XmlNode refChild = null;

            for (int i = 0; i < typeParameters.Count; i++)
            {
                ITypeParameter typeParameter = typeParameters[i];
                XmlNode node = xmlNode.SelectSingleNode(string.Format("//typeparam[@name='{0}']", typeParameter.ShortName));

                if (i == 0)
                {
                    refChild = node.PreviousSibling;
                }

                xmlNode.InsertAfter(node, refChild);
                refChild = node;
            }
        }
Пример #8
0
		public static void InsertNodeUsingDefinedOrder(XmlNode parent, XmlNode newChild, IComparer<XmlNode> nodeOrderComparer)
		{
			if (newChild.NodeType == XmlNodeType.Attribute)
			{
				XmlAttribute insertAfterNode = null;
				foreach (XmlAttribute childNode in parent.Attributes)
				{
					if (nodeOrderComparer.Compare(newChild, childNode) < 0)
					{
						break;
					}
					insertAfterNode = childNode;
				}
				parent.Attributes.InsertAfter((XmlAttribute)newChild, insertAfterNode);
			}
			else
			{
				XmlNode insertAfterNode = null;
				foreach (XmlNode childNode in parent.ChildNodes)
				{
					if (nodeOrderComparer.Compare(newChild, childNode) < 0)
					{
						break;
					}
					insertAfterNode = childNode;
				}
				parent.InsertAfter(newChild, insertAfterNode);
			}
		}
Пример #9
0
        internal ExcelPicture(ExcelDrawings drawings, XmlNode node, FileInfo imageFile)
            : base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/@name")
        {
            XmlElement picNode = node.OwnerDocument.CreateElement("xdr", "pic", ExcelPackage.schemaSheetDrawings);
            node.InsertAfter(picNode, node.SelectSingleNode("xdr:to", NameSpaceManager));
            picNode.InnerXml = PicStartXml();

            node.InsertAfter(node.OwnerDocument.CreateElement("xdr", "clientData", ExcelPackage.schemaSheetDrawings), picNode);

            Package package = drawings.Worksheet.xlPackage.Package;
            SetContentType(imageFile.Extension);
            _image = Image.FromFile(imageFile.FullName);
            ImageConverter ic = new ImageConverter();
            byte[] img = (byte[])ic.ConvertTo(_image, typeof(byte[]));

            string relID = GetPictureRelID(img);

            if (relID == "")
            {
                UriPic = GetNewUri(package, "/xl/media/image{0}" + imageFile.Extension);
                Part = package.CreatePart(UriPic, ContentType, CompressionOption.NotCompressed);

                //Save the picture to package.
                byte[] file = File.ReadAllBytes(imageFile.FullName);
                var strm = Part.GetStream(FileMode.Create, FileAccess.Write);
                strm.Write(file, 0, file.Length);

                PackageRelationship picRelation = drawings.Part.CreateRelationship(UriPic, TargetMode.Internal, ExcelPackage.schemaRelationships + "/image");
                relID = picRelation.Id;
                AddNewPicture(img, relID);

            }
            else
            {
                var rel = _drawings.Part.GetRelationship(relID);
                UriPic = rel.TargetUri;
            }
            SetPosDefaults(Image);
            //Create relationship
            node.SelectSingleNode("xdr:pic/xdr:blipFill/a:blip/@r:embed", NameSpaceManager).Value = relID;
            package.Flush();
        }
Пример #10
0
        private static void InsertClickOnceDependency(EnvConfig envConfig, XmlNode dependencyList, XmlNode lastPrerequisite, string file, XmlNamespaceManager nsmgr)
        {
            var deployTarget = Path.Combine(GetClickOnceOutputPath(envConfig), file);
            var doc = dependencyList.OwnerDocument;

            // avoid the pseudo/testing resource assemblies, as clickonce client dies on unknown cultures
            if (file.ToLowerInvariant().EndsWith(".resources.dll") || file.ToLowerInvariant().EndsWith(".resources.dll.deploy") || file.ToLowerInvariant().EndsWith(".resources.exe") || file.ToLowerInvariant().EndsWith(".resources.exe.deploy"))
            {
                if (file.ToLowerInvariant().Contains("x-zb-"))
                {
                    Program.LogDetail("Skipping pseudo culture file: [{0}]", file);
                    return;
                }
            }

            if (file.EndsWith(".dll") || file.EndsWith(".dll.deploy") || file.EndsWith(".exe") || file.EndsWith(".exe.deploy"))
            {
                // TODO: do not deploy fallback to client and remove this.
                if (file.Contains("Fallback")) return;

                var dependency = doc.CreateNode(XmlNodeType.Element, "dependency", ASMv2_NS);
                var dependentAssembly = doc.CreateNode(XmlNodeType.Element, "dependentAssembly", ASMv2_NS);
                SetOrReplaceAttribute(dependentAssembly, "dependencyType", null, "install");
                SetOrReplaceAttribute(dependentAssembly, "allowDelayedBinding", null, "true");
                SetOrReplaceAttribute(dependentAssembly, "codebase", null, file.Replace('/', '\\'));
                SetOrReplaceAttribute(dependentAssembly, "size", null, string.Format(CultureInfo.InvariantCulture, "{0}", new FileInfo(file).Length));

                var assemblyIdentity = doc.CreateNode(XmlNodeType.Element, "assemblyIdentity", ASMv2_NS);

                FillClickOnceAssemblyId(System.Reflection.Assembly.ReflectionOnlyLoadFrom(file), assemblyIdentity);
                dependentAssembly.AppendChild(assemblyIdentity);

                var hash = CreateHashNode(file, nsmgr, doc);

                dependentAssembly.AppendChild(hash);
                dependency.AppendChild(dependentAssembly);
                dependencyList.InsertAfter(dependency, lastPrerequisite);

                deployTarget += ".deploy";
            }
            else if (file.EndsWith(".manifest"))
            {
                var dependency = doc.CreateNode(XmlNodeType.Element, "dependency", ASMv2_NS);
                var dependentAssembly = doc.CreateNode(XmlNodeType.Element, "dependentAssembly", ASMv2_NS);
                SetOrReplaceAttribute(dependentAssembly, "dependencyType", null, "install");
                SetOrReplaceAttribute(dependentAssembly, "codebase", null, file.Replace('/', '\\'));
                SetOrReplaceAttribute(dependentAssembly, "size", null, string.Format(CultureInfo.InvariantCulture, "{0}", new FileInfo(file).Length));

                var manifest = new XmlDocument();
                manifest.Load(file);
                var manifestNsmgr = CreateDefaultXmlNsmgr(manifest);
                var srcAssemblyId = manifest.SelectSingleNode("/asmv1:assembly/asmv1:assemblyIdentity", manifestNsmgr);

                var assemblyIdentity = doc.CreateNode(XmlNodeType.Element, "assemblyIdentity", ASMv2_NS);
                foreach (var attrName in new[] { "name", "version", "language", "processorArchitecture", "publicKeyToken", "type" })
                {
                    SetOrReplaceAttribute(assemblyIdentity, attrName, null, srcAssemblyId.Attributes[attrName].Value);
                }

                dependentAssembly.AppendChild(assemblyIdentity);

                var hash = CreateHashNode(file, nsmgr, doc);

                dependentAssembly.AppendChild(hash);
                dependency.AppendChild(dependentAssembly);
                dependencyList.InsertAfter(dependency, lastPrerequisite);
            }
            else
            {
                var fileNode = doc.CreateNode(XmlNodeType.Element, "file", ASMv2_NS);
                SetOrReplaceAttribute(fileNode, "name", null, file.Replace('/', '\\'));
                SetOrReplaceAttribute(fileNode, "size", null, string.Format(CultureInfo.InvariantCulture, "{0}", new FileInfo(file).Length));

                var hash = doc.CreateNode(XmlNodeType.Element, "hash", ASMv2_NS);
                var transforms = doc.CreateNode(XmlNodeType.Element, "Transforms", XMLDSIG_NS);
                var transform = doc.CreateNode(XmlNodeType.Element, "Transform", XMLDSIG_NS);
                SetOrReplaceAttribute(transform, "Algorithm", null, XMLDSIG_IDENTITY);
                transforms.AppendChild(transform);
                hash.AppendChild(transforms);
                var digestMethod = doc.CreateNode(XmlNodeType.Element, "DigestMethod", XMLDSIG_NS);
                hash.AppendChild(digestMethod);
                var digestValue = doc.CreateNode(XmlNodeType.Element, "DigestValue", XMLDSIG_NS);
                hash.AppendChild(digestValue);

                UpdateSha1(hash, file, nsmgr);

                fileNode.AppendChild(hash);

                dependencyList.InsertAfter(fileNode, lastPrerequisite);

                deployTarget += ".deploy";
            }

            Directory.CreateDirectory(Path.GetDirectoryName(deployTarget));
            File.Copy(file, deployTarget, true);
        }
Пример #11
0
        internal ExcelPicture(ExcelDrawings drawings, XmlNode node, FileInfo imageFile, Uri hyperlink) :
            base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/@name")
        {
            XmlElement picNode = node.OwnerDocument.CreateElement("xdr", "pic", ExcelPackage.schemaSheetDrawings);
            node.InsertAfter(picNode, node.SelectSingleNode("xdr:to", NameSpaceManager));
            _hyperlink = hyperlink;
            picNode.InnerXml = PicStartXml();

            node.InsertAfter(node.OwnerDocument.CreateElement("xdr", "clientData", ExcelPackage.schemaSheetDrawings), picNode);

            Package package = drawings.Worksheet._package.Package;
            ContentType = GetContentType(imageFile.Extension);
            _image = Image.FromFile(imageFile.FullName);
            ImageConverter ic = new ImageConverter();
            byte[] img = (byte[])ic.ConvertTo(_image, typeof(byte[]));


            UriPic = GetNewUri(package, "/xl/media/{0}" + imageFile.Name);
            var ii = _drawings._package.AddImage(img, UriPic, ContentType);
            //string relID = GetPictureRelID(img);

            //if (relID == "")
            string relID;
            if(!drawings._hashes.ContainsKey(ii.Hash))
            {
                //UriPic = GetNewUri(package, "/xl/media/image{0}" + imageFile.Extension);
                //Part =  package.CreatePart(UriPic, ContentType, CompressionOption.NotCompressed);

                ////Save the picture to package.
                //byte[] file = File.ReadAllBytes(imageFile.FullName);
                //var strm = Part.GetStream(FileMode.Create, FileAccess.Write);
                //strm.Write(file, 0, file.Length);
                Part = ii.Part;
                RelPic = drawings.Part.CreateRelationship(PackUriHelper.GetRelativeUri(drawings.UriDrawing, ii.Uri), TargetMode.Internal, ExcelPackage.schemaRelationships + "/image");
                relID = RelPic.Id;
                _drawings._hashes.Add(ii.Hash, relID);
                AddNewPicture(img, relID);

            }
            else
            {
                relID = drawings._hashes[ii.Hash];
                var rel = _drawings.Part.GetRelationship(relID);
                UriPic = PackUriHelper.ResolvePartUri(rel.SourceUri, rel.TargetUri);
            }
            SetPosDefaults(Image);
            //Create relationship
            node.SelectSingleNode("xdr:pic/xdr:blipFill/a:blip/@r:embed", NameSpaceManager).Value = relID;
            package.Flush();
        }
        private void Paste(XmlNode parentNode)
        {
            if (parentNode.NodeType == XmlNodeType.Element)
            {
                XmlNode xmlNode = null;
                if (parentNode.OwnerDocument != TreeEditorViewModel.CopiedElement.OwnerDocument)
                {
                    xmlNode = parentNode.OwnerDocument.ImportNode(TreeEditorViewModel.CopiedElement, true);
                }
                else
                {
                    xmlNode = TreeEditorViewModel.CopiedElement;
                }
                parentNode.InsertAfter(xmlNode, parentNode.LastChild);
                Copy(TreeEditorViewModel.CopiedElement);

            }
        }
Пример #13
0
        /*
        // 删除一个方案
        // return:
        //	0	not found
        //	1	found and deleted
        //	2	canceld	因此project没有被删除
        public int DeleteProject(string strProjectNamePath,
            bool bWarning,
            out XmlNode parentXmlNode)
        {
            string strCodeFileName;
            bool bDeleteCodeFile = true;
            parentXmlNode = null;

            XmlNode nodeThis = LocateProjectNode(strProjectNamePath);

            if (nodeThis == null)
                return 0;

            strCodeFileName = DomUtil.GetAttr(nodeThis, "codeFileName");

            if (strCodeFileName != "") 
            {

                // 看看源文件是否被多个project引用
                ArrayList aFound = new ArrayList();
                XmlNodeList nodes = dom.DocumentElement.SelectNodes("//project");
                for(int i=0;i<nodes.Count;i++) 
                {
                    string strFilePath = DomUtil.GetAttr(nodes[i], "codeFileName");

                    if (String.Compare(strCodeFileName, strFilePath, true) == 0)
                    {
                        if (nodes[i] != nodeThis)
                            aFound.Add(nodes[i]);
                    }
                }

                if (aFound.Count > 0) 
                {
                    if (bWarning == true) 
                    {
                        string strText = "系统发现,源代码文件 "
                            + strCodeFileName 
                            + " 除了被您即将删除的方案 "+
                            strProjectNamePath 
                            +" 使用外,还被下列方案引用:\r\n---\r\n";

                        for(int i=0;i<aFound.Count;i++)
                        {
                            strText += GetNodePathName((XmlNode)aFound[i]) + "\r\n";
                        }

                        strText += "---\r\n\r\n这意味着,如果删除这个源代码文件,上述方案将不能正常运行。\r\n\r\n请问,在删除方案" +strProjectNamePath+ "时,是否保留源代码文件 " + strCodeFileName + "?";

                        DialogResult msgResult = MessageBox.Show(//this,
                            strText,
                            "script",
                            MessageBoxButtons.YesNoCancel,
                            MessageBoxIcon.Question,
                            MessageBoxDefaultButton.Button1);

                        if (msgResult == DialogResult.Yes)
                            bDeleteCodeFile = false;
                        if (msgResult == DialogResult.Cancel)
                            return 2;	// cancel
                    }
                    else 
                    {
                        bDeleteCodeFile = false;	// 自动采用最保险的方式
                    }

                }
            }

            // 从Dom上删除节点
            parentXmlNode = nodeThis.ParentNode;
            parentXmlNode.RemoveChild(nodeThis);

            if (bDeleteCodeFile == true
                && strCodeFileName != "")
                File.Delete(strCodeFileName);

            m_bChanged = true;

            return 1;
        }
        */


        // 上下移动节点
        // return:
        //	0	not found
        //	1	found and moved
        //	2	cant move
        public int MoveNode(string strNodeNamePath,
            bool bUp,
            out XmlNode parentXmlNode)
        {
            parentXmlNode = null;

            XmlNode nodeThis = LocateAnyNode(strNodeNamePath);

            if (nodeThis == null)
                return 0;

            XmlNode nodeInsert = null;


            if (bUp == true)
            {
                nodeInsert = nodeThis.PreviousSibling;
                if (nodeInsert == null)
                    return 2;
            }
            else
            {
                nodeInsert = nodeThis.NextSibling;
                if (nodeInsert == null)
                    return 2;
            }

            // 从Dom上删除节点
            parentXmlNode = nodeThis.ParentNode;
            parentXmlNode.RemoveChild(nodeThis);

            // 插入到特定位置
            if (bUp == true)
            {
                parentXmlNode.InsertBefore(nodeThis, nodeInsert);
            }
            else
            {
                parentXmlNode.InsertAfter(nodeThis, nodeInsert);
            }

            m_bChanged = true;

            return 1;
        }
// Methods
    internal override void Apply( XmlNode parent, ref XmlNode currentPosition )
    {
        if ( !_bSubtree )
        {
            Debug.Assert( _sourceNodes.Count == 1 );

			XmlNode remNode = _sourceNodes.Item(0);
            ApplyChildren( remNode );

            currentPosition = remNode.PreviousSibling;
        }

        IEnumerator e = _sourceNodes.GetEnumerator();
        e.Reset();
        while ( e.MoveNext() )
        {
            XmlNode node = (XmlNode)e.Current;

            Debug.Assert( node.ParentNode == parent ||
                        ( node.ParentNode == null && node.NodeType == XmlNodeType.Attribute ) ||
                        ( node.NodeType == XmlNodeType.XmlDeclaration && node.ParentNode == node.OwnerDocument ) ||
                        ( node.NodeType == XmlNodeType.DocumentType && node.ParentNode == node.OwnerDocument) );
            
            if ( node.NodeType == XmlNodeType.Attribute )
            {
                Debug.Assert( parent.NodeType == XmlNodeType.Element );
                ((XmlElement)parent).RemoveAttributeNode( (XmlAttribute) node );
            }
            else
            {
                if ( !_bSubtree )
                {
                    // move all children to grandparent
                    while ( node.FirstChild != null )
                    {
                        XmlNode child = node.FirstChild;
                        node.RemoveChild( child );
                        parent.InsertAfter( child, currentPosition );
                        currentPosition = child;
                    }
                }

                // remove node
                node.ParentNode.RemoveChild( node );  // this is node.ParentNode instead of node.parent because of the xml declaration
            }
        }
    }
// Methods
    internal override void Apply( XmlNode parent, ref XmlNode currentPosition )
    {
        XmlDocument doc = parent.OwnerDocument;

        IEnumerator enumerator = _nodes.GetEnumerator();
        while ( enumerator.MoveNext() ) 
        {
            XmlNode newNode = doc.ImportNode( (XmlNode)enumerator.Current, true );
            parent.InsertAfter( newNode, currentPosition );
            currentPosition = newNode;
        }
    }
Пример #16
0
        private static void InsertFilterElement(XmlNode resultNode, TestFilter filter)
        {
            // Convert the filter to an XmlNode
            var tempNode = XmlHelper.CreateXmlNode(filter.Text);

            // Don't include it if it's an empty filter
            if (tempNode.ChildNodes.Count > 0)
            {
                var doc = resultNode.OwnerDocument;
                var filterElement = doc.ImportNode(tempNode, true);
                resultNode.InsertAfter(filterElement, null);
            }
        }
        /// <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;
            }
        }
Пример #18
0
        /// <summary>
        /// Make sure soil nodes have a ASC_Order and ASC_Sub-order nodes.
        /// </summary>
        private static void ToVersion32(XmlNode Node)
        {
            if (Node.Name.ToLower() == "soil")
            {
                if (XmlUtilities.FindByType(Node, "ASC_Order") == null)
                {
                    XmlNode NewNode = XmlUtilities.EnsureNodeExists(Node, "ASC_Order");
                    XmlUtilities.SetAttribute(NewNode, "description", "Australian Soil Classification Order");
                    NewNode.ParentNode.InsertBefore(NewNode, NewNode.FirstChild);
                }
                if (XmlUtilities.FindByType(Node, "ASC_Sub-order") == null)
                {
                    XmlNode NewNode = XmlUtilities.EnsureNodeExists(Node, "ASC_Sub-order");
                    XmlUtilities.SetAttribute(NewNode, "description", "Australian Soil Classification Sub-Order");
                    Node.InsertAfter(NewNode, XmlUtilities.FindByType(Node, "ASC_Order"));
                }
                XmlNode SoilType = XmlUtilities.EnsureNodeExists(Node, "SoilType");
                XmlUtilities.SetAttribute(SoilType, "description", "Soil description");
                Node.InsertAfter(SoilType, XmlUtilities.FindByType(Node, "ASC_Sub-order"));

                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "LocalName"), XmlUtilities.FindByType(Node, "SoilType"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "Site"), XmlUtilities.FindByType(Node, "LocalName"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "NearestTown"), XmlUtilities.FindByType(Node, "Site"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "Region"), XmlUtilities.FindByType(Node, "NearestTown"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "State"), XmlUtilities.FindByType(Node, "Region"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "Country"), XmlUtilities.FindByType(Node, "State"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "NaturalVegetation"), XmlUtilities.FindByType(Node, "Country"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "ApsoilNumber"), XmlUtilities.FindByType(Node, "NaturalVegetation"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "Latitude"), XmlUtilities.FindByType(Node, "ApsoilNumber"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "Longitude"), XmlUtilities.FindByType(Node, "Latitude"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "LocationAccuracy"), XmlUtilities.FindByType(Node, "Longitude"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "DataSource"), XmlUtilities.FindByType(Node, "LocationAccuracy"));
                Node.InsertAfter(XmlUtilities.EnsureNodeExists(Node, "Comments"), XmlUtilities.FindByType(Node, "DataSource"));
            }
        }
Пример #19
0
        private XmlNode SetStains(XmlNode tableNodeSS,
			XmlNode rowStainHeaderNode,
			XmlNode rowTestHeaderNode,
			XmlNode insertAfterRowSS,
			XmlNode rowSpecialStainNode,
			SurgicalSpecimen surgicalSpecimen,
			YellowstonePathology.Business.SpecialStain.StainResultItemCollection stainResultCollection)
        {
            XmlNode rowStainHeaderNodeClone = rowStainHeaderNode.Clone();
            tableNodeSS.InsertAfter(rowStainHeaderNodeClone, insertAfterRowSS);
            insertAfterRowSS = rowStainHeaderNodeClone;

            XmlNode rowTestHeaderNodeClone = rowTestHeaderNode.Clone();
            tableNodeSS.InsertAfter(rowTestHeaderNodeClone, insertAfterRowSS);
            insertAfterRowSS = rowTestHeaderNodeClone;

            foreach (YellowstonePathology.Business.SpecialStain.StainResultItem stainResultItem in stainResultCollection)
            {
                XmlNode rowSpecialStainClone = rowSpecialStainNode.Clone();
                string stainDescription = stainResultItem.ProcedureName;
                string stainResult = stainResultItem.Result;

                if (string.IsNullOrEmpty(stainResult) == true)
                {
                    stainResult = "Pending";
                }
                else if (stainResult.ToUpper() == "SEE COMMENT")
                {
                    stainResult = stainResultItem.ReportComment;
                }
                else
                {
                    string specialStainReportComment = stainResultItem.ReportComment;

                    if (!string.IsNullOrEmpty(specialStainReportComment))
                    {
                        stainResult += " - " + specialStainReportComment;
                    }
                }

                rowSpecialStainClone.SelectSingleNode("descendant::w:r[w:t='stain_description']/w:t", this.m_NameSpaceManager).InnerText = stainDescription;
                rowSpecialStainClone.SelectSingleNode("descendant::w:r[w:t='stain_result']/w:t", this.m_NameSpaceManager).InnerText = stainResult;

                string block = surgicalSpecimen.GetBlockFromTestOrderId(stainResultItem.TestOrderId);
                rowSpecialStainClone.SelectSingleNode("descendant::w:r[w:t='block_description']/w:t", this.m_NameSpaceManager).InnerText = block;

                tableNodeSS.InsertAfter(rowSpecialStainClone, insertAfterRowSS);
                insertAfterRowSS = rowSpecialStainClone;
            }

            return insertAfterRowSS;
        }
Пример #20
0
 private static XmlNode InsertAfter(XmlNode parent, XmlNode newChild, XmlNode refChild)
 {
     Assert.NotNull(parent);
     Assert.NotNull(newChild);
     return parent.InsertAfter(newChild, refChild);
 }
Пример #21
0
        private static void SetField(
            XmlNode parentNode, ref XmlNode previousSibling,
            string tagName, string tagValue, string nspace)
        {
            // obtain a pointer to the XmlDocument object.  This is used
            // in a few places in this method.
            XmlDocument doc = parentNode.OwnerDocument;

            // create an XmlText object to hold the field's value.
            XmlText text = doc.CreateTextNode(tagValue);

            // look for the field.
            XmlNode node = GetNode(doc, tagName, nspace);

            // if the field does not exist,...
            if (node == null)
            {
                // create an element for it and inside this element,
                // insert the XmlText object we created earlier.
                node = doc.CreateElement(tagName, nspace);
                node.AppendChild(text);

                // if there is a previous sibling, insert the new node
                // after it.
                if (previousSibling != null)
                {
                    parentNode.InsertAfter(node, previousSibling);
                }
                // else, the new node becomes the first child.
                else
                {
                    parentNode.PrependChild(node);
                }
            }
            // else, if the field already exists, replace its value.
            else
            {
                // if the field does have a value, replace it with
                // the XmlText object we created earlier.
                if (node.HasChildNodes)
                {
                    node.ReplaceChild(text, node.ChildNodes[0]);
                }
                // else, if it's empty, append the XmlText object
                // we created earlier.
                else
                {
                    node.AppendChild(text);
                }
            }

            // the next node to be added will be after this node.  So, we
            // set previousSibling to this node.
            previousSibling = node;
        }
        /// <summary>
        /// Reorder parameters.
        /// </summary>
        /// <param name="xmlNode">
        /// The xml node.
        /// </param>
        /// <param name="parameters">
        /// The parameters.
        /// </param>
        private static void ReorderParams(XmlNode xmlNode, IList<IParameterDeclaration> parameters)
        {
            XmlNode refChild = null;

            for (int i = 0; i < parameters.Count; i++)
            {
                IParameterDeclaration parameter = parameters[i];
                XmlNode node = xmlNode.SelectSingleNode(string.Format("//param[@name='{0}']", parameter.DeclaredName));

                if (i == 0)
                {
                    if (node.ParentNode.Name == "member")
                    {
                        refChild = node.PreviousSibling;
                    }
                    else
                    {
                        refChild = node.ParentNode;
                    }
                }

                xmlNode.InsertAfter(node, refChild);
                refChild = node;
            }
        }
Пример #23
0
        public void añadir(List<Premios> premios)
        {

            documento = new XmlDocument();
            if (File.Exists(this.nombreFichero))
            {

                documento.Load(this.nombreFichero);
                raiz = documento.DocumentElement;
                XmlNodeList tmp = documento.GetElementsByTagName("Resultados");
                if (tmp.Count < 1)
                {
                    raiz.InsertAfter(crearNodo(premios),documento.GetElementsByTagName("Recaudacion")[0]);
                    documento.Save(this.nombreFichero);
                }
            }
        }
Пример #24
0
        /// <summary>
        /// writes data to xml
        /// </summary>
        /// <param name="doc">document to add</param>
        /// <param name="root">root to add</param>
        public void WriteXml(XmlDocument doc, XmlNode root)
        {
            XmlElement newProduct = doc.CreateElement("Product");
            XmlElement newId = doc.CreateElement("id");
            XmlText identifier = doc.CreateTextNode(this.id.ToString());
            newId.AppendChild(identifier);
            XmlElement newPrice = doc.CreateElement("price");
            XmlText cost = doc.CreateTextNode(this.price.ToString());
            newPrice.AppendChild(cost);
            newProduct.AppendChild(newId);
            newProduct.AppendChild(newPrice);

            root.InsertAfter(newProduct, root.LastChild);
        }
Пример #25
0
        private static void GenerateHeadTags(ITemplateParsingState templateParsingState, XmlNode headNode)
        {
            SortedDictionary<double, LinkedList<XmlNode>> headerNodes = templateParsingState.HeaderNodes;

            foreach (double loc in headerNodes.Keys)
                if (loc < 0)
                    foreach (XmlNode xmlNode in headerNodes[loc])
                        headNode.PrependChild(xmlNode);
                else
                    foreach (XmlNode xmlNode in headerNodes[loc])
                        headNode.InsertAfter(xmlNode, headNode.LastChild);

            // handle oc:title, if present
            // TODO:  Use XPATH
            XmlNodeList ocTitleNodes = headNode.OwnerDocument.GetElementsByTagName("title", templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace);

            if (ocTitleNodes.Count > 1)
                for (int ctr = 1; ctr < ocTitleNodes.Count; ctr++)
                {
                    XmlNode ocTitleNode = ocTitleNodes[ctr];
                    ocTitleNode.ParentNode.RemoveChild(ocTitleNode);
                }

            if (ocTitleNodes.Count > 0)
            {
                XmlNode ocTitleNode = ocTitleNodes[0];

                bool titleNodePresent = false;
                foreach (XmlNode titleNode in headNode.OwnerDocument.GetElementsByTagName("title", headNode.NamespaceURI))
                    if (titleNode.ParentNode == ocTitleNode.ParentNode)
                        titleNodePresent = true;

                if (!titleNodePresent)
                {
                    XmlNode titleNode = headNode.OwnerDocument.CreateElement("title", headNode.NamespaceURI);

                    foreach (XmlNode subNode in ocTitleNode.ChildNodes)
                        titleNode.AppendChild(subNode);

                    foreach (XmlAttribute attribute in ocTitleNode.Attributes)
                        titleNode.Attributes.Append(attribute);

                    ocTitleNode.ParentNode.InsertAfter(titleNode, ocTitleNode);
                }

                ocTitleNode.ParentNode.RemoveChild(ocTitleNode);
            }
        }
        public void BuildHeader()
        {
            try
            {
                //
                string test = "<?xml version='1.0' encoding='UTF-8'?><" + ConfigurationManager.AppSettings["GSADTD"] + "><gsafeed></gsafeed>";
                //set to null else .net will try to validate the xml against the dtd type and it will fail
                doc.XmlResolver = null;
                doc.LoadXml(test);

                root = doc.DocumentElement;

                //create header node
                XmlNode headerNode = doc.CreateNode(XmlNodeType.Element, "header", "");

                XmlElement datasrc  = doc.CreateElement("datasource");
                //build	 the GSA xml datashource from
                //extract all no alphanumerics for datasource as some char can cause
                //the GSA to barf!!!

                Regex stripper = new Regex("[^a-zA-Z0-9]");
                datasrc.InnerText = HttpUtility.UrlEncode( stripper.Replace(DataSource, "" ));

                XmlElement feedtype = doc.CreateElement("feedtype");
                feedtype.InnerText = feederType;

                //insert data source and feedtype nodes into the neader node
                headerNode.InsertAfter(datasrc, headerNode.FirstChild);
                headerNode.InsertAfter(feedtype, headerNode.LastChild);

                //insert header into document
                root.InsertAfter(headerNode, root.FirstChild);

                //create the group node to contain our content records
                groupNode = doc.CreateNode(XmlNodeType.Element, "group", "");
                //create group attributes
                //XmlNode attr = doc.CreateNode(XmlNodeType.Attribute, "lock", "");
                //attr.Value = "1";

                //Add the attribute to the document.
                //groupNode.Attributes.SetNamedItem(attr);

                //insert group into document
                root.InsertAfter(groupNode, root.FirstChild);
            }
            catch (Exception ex)
            {
                log.Error("Error  XmlGSAFeed.BuildHeader()");
                log.Error(ex.Message);
                log.Error(ex.StackTrace);
            }
        }
Пример #27
0
        private static void InsertCommandLineElement(XmlNode resultNode)
        {
            var doc = resultNode.OwnerDocument;

            XmlNode cmd = doc.CreateElement("command-line");
            resultNode.InsertAfter(cmd, null);

            var cdata = doc.CreateCDataSection(Environment.CommandLine);
            cmd.AppendChild(cdata);
        }
Пример #28
0
        internal XmlElement AppendField(XmlNode rowsNode, int index, string fieldNodeText, string indexAttrText)
        {
            XmlElement prevField = null, newElement;
            foreach (XmlElement field in rowsNode.ChildNodes)
            {
                string x = field.GetAttribute(indexAttrText);
                int fieldIndex;
                if(int.TryParse(x, out fieldIndex))
                {
                    if (fieldIndex == index)    //Row already exist
                    {
                        return field;
                    }
                    else if (fieldIndex > index)
                    {
                        newElement = rowsNode.OwnerDocument.CreateElement(fieldNodeText, ExcelPackage.schemaMain);
                        newElement.SetAttribute(indexAttrText, index.ToString());
                        rowsNode.InsertAfter(newElement, field);
                    }
                }
                prevField=field;
            }
            newElement = rowsNode.OwnerDocument.CreateElement(fieldNodeText, ExcelPackage.schemaMain);
            newElement.SetAttribute(indexAttrText, index.ToString());
            rowsNode.InsertAfter(newElement, prevField);

            return newElement;
        }
Пример #29
0
        private static void InsertSettingsElement(XmlNode resultNode, IDictionary<string, object> settings)
        {
            var doc = resultNode.OwnerDocument;

            XmlNode settingsNode = doc.CreateElement("settings");
            resultNode.InsertAfter(settingsNode, null);

            foreach (string name in settings.Keys)
            {
                string value = settings[name].ToString();
                XmlNode settingNode = doc.CreateElement("setting");
                settingNode.AddAttribute("name", name);
                settingNode.AddAttribute("value", value);
                settingsNode.AppendChild(settingNode);
            }
        }
Пример #30
0
        /// <summary>
        /// Insert the new node before any of the nodes in the comma separeted list
        /// </summary>
        /// <param name="parentNode">Parent node</param>
        /// <param name="beforeNodes">comma separated list containing nodes to insert after. Left to right order</param>
        /// <param name="newNode">The new node to be inserterd</param>
        internal void InserAfter(XmlNode parentNode, string beforeNodes, XmlNode newNode)
        {
            string[] nodePaths = beforeNodes.Split(',');

            foreach (string nodePath in nodePaths)
            {
                XmlNode node = parentNode.SelectSingleNode(nodePath, NameSpaceManager);
                if (node != null)
                {
                    parentNode.InsertAfter(newNode, node);
                    return;
                }
            }
            parentNode.InsertAfter(newNode, null);
        }
Пример #31
0
        internal override void Close(WriteState currentState)
        {
            if (currentState == WriteState.Error)
            {
                return;
            }
            try
            {
                switch (_type)
                {
                case DocumentXmlWriterType.InsertSiblingAfter:
                    XmlNode parent = _start.ParentNode;
                    if (parent == null)
                    {
                        throw new InvalidOperationException(SR.Xpn_MissingParent);
                    }
                    for (int i = _fragment.Count - 1; i >= 0; i--)
                    {
                        parent.InsertAfter(_fragment[i], _start);
                    }
                    break;

                case DocumentXmlWriterType.InsertSiblingBefore:
                    parent = _start.ParentNode;
                    if (parent == null)
                    {
                        throw new InvalidOperationException(SR.Xpn_MissingParent);
                    }
                    for (int i = 0; i < _fragment.Count; i++)
                    {
                        parent.InsertBefore(_fragment[i], _start);
                    }
                    break;

                case DocumentXmlWriterType.PrependChild:
                    for (int i = _fragment.Count - 1; i >= 0; i--)
                    {
                        _start.PrependChild(_fragment[i]);
                    }
                    break;

                case DocumentXmlWriterType.AppendChild:
                    for (int i = 0; i < _fragment.Count; i++)
                    {
                        _start.AppendChild(_fragment[i]);
                    }
                    break;

                case DocumentXmlWriterType.AppendAttribute:
                    CloseWithAppendAttribute();
                    break;

                case DocumentXmlWriterType.ReplaceToFollowingSibling:
                    if (_fragment.Count == 0)
                    {
                        throw new InvalidOperationException(SR.Xpn_NoContent);
                    }
                    CloseWithReplaceToFollowingSibling();
                    break;
                }
            }
            finally
            {
                _fragment.Clear();
            }
        }