private void MakeContentFile(ContentURI uri, string packageId, IDictionary <string, string> args, ref string contentNewPath, ref string errorMsg) { string[] arrValues = { }; int i = 0; string sArg = string.Empty; string sRelPartPath = string.Empty; string sMimeType = string.Empty; //need an editable navigator XmlDocument xmlContentDoc = new XmlDocument(); XmlReader reader = Helpers.FileStorageIO.GetXmlReader(uri, contentNewPath); if (reader != null) { using (reader) { xmlContentDoc.Load(reader); } XPathNavigator navContentDoc = xmlContentDoc.CreateNavigator(); //move to package navContentDoc.MoveToFirstChild(); navContentDoc.CreateAttribute(string.Empty, "unique-identifier", string.Empty, packageId); //move to meta navContentDoc.MoveToFirstChild(); //move to manifest navContentDoc.MoveToNext(XPathNodeType.Element); //two default items navContentDoc.MoveToChild(XPathNodeType.Element); bool bHasMoved = navContentDoc.MoveToNext(XPathNodeType.Element); if (bHasMoved) { string sKey = string.Empty; string sValue = string.Empty; foreach (KeyValuePair <string, string> kvp in args) { sKey = kvp.Key; sValue = kvp.Value; if (sValue != "-p") { //clients use same relative paths as server //convert the absolute path of partFullPath into a path relative to the package root (getcurrentdirectory) sRelPartPath = AppSettings.ConvertAbsPathToRelPath(CurrentDirectory, sKey); sMimeType = AppHelpers.Resources.GetMimeTypeFromFileExt(Path.GetExtension(sRelPartPath), ref errorMsg); //add this href attribute to a new item element child of manifest element navContentDoc.InsertElementAfter(string.Empty, "item", string.Empty, string.Empty); navContentDoc.MoveToNext(); navContentDoc.CreateAttribute(string.Empty, "id", string.Empty, i.ToString()); navContentDoc.CreateAttribute(string.Empty, "href", string.Empty, sRelPartPath); navContentDoc.CreateAttribute(string.Empty, "media-type", string.Empty, sMimeType); i++; } } } } string sContainerNewPath = Path.Combine(Path.GetDirectoryName(contentNewPath), CONTAINER_FILE); Helpers.FileStorageIO.MoveURIs(uri, contentNewPath, sContainerNewPath); contentNewPath = sContainerNewPath; }
public static void AddAllNewAttributes( XPathNavigator fromNav, XPathNavigator toNav) { if (fromNav != null && toNav != null) { string sFromNodeName = fromNav.Name; RemoveAllAttributes(toNav); if (fromNav.HasAttributes) { fromNav.MoveToFirstAttribute(); toNav.CreateAttribute(string.Empty, fromNav.Name, string.Empty, fromNav.Value); while (fromNav.MoveToNextAttribute()) { toNav.CreateAttribute(string.Empty, fromNav.Name, string.Empty, fromNav.Value); } if (fromNav.Name != sFromNodeName) { fromNav.MoveToParent(); } } } }
/// <summary> /// Rewires the configuration section. /// </summary> /// <param name="configNode">The original configuration node, received from the site manager it registered with</param> /// <param name="createNewIfNotPresent">if set to <c>true</c> request a new node from the site manager, if none exists.</param> /// <returns> /// A node containing the new settings /// </returns> public IXPathNavigable RewireConfig(IXPathNavigable configNode, bool createNewIfNotPresent) { XmlNode tempConfig = (XmlNode)configNode; if (tempConfig == null) { if (createNewIfNotPresent) { tempConfig = (XmlNode)this.configmanager.CreateNewSection(this); } else { throw new ArgumentException(Strings.CreationOfNewConfigSection); } } else { tempConfig.RemoveAll(); } if (this.configmanager.AllowExternalSource) { XPathNavigator nav = tempConfig.CreateNavigator(); nav.CreateAttribute(null, "configSource", null, this.healthMonExtSource); } else { throw new NotImplementedException(Strings.LoggingAutoWiringOnly); } return(tempConfig); }
// // PRIVATE METHODS // private void CreateReport() { if (string.IsNullOrEmpty(this.Xml)) { return; } // Get ESRI Namespace XPathDocument document = new XPathDocument(this.Xml, XmlSpace.None); XPathNavigator navigator = document.CreateNavigator(); navigator.MoveToFirstChild(); string esriNamespace = navigator.LookupNamespace("esri"); // Open XSL XmlDocument schemaDocument = new XmlDocument(); schemaDocument.LoadXml(Resources.FILE_SCHEMA_REPORT); // Add Namespaces to Schema Document XPathNavigator navigator2 = schemaDocument.CreateNavigator(); bool ok = navigator2.MoveToFirstChild(); navigator2.CreateAttribute("xmlns", "esri", null, esriNamespace); // Store XSL this.Xsl = schemaDocument.OuterXml; // Fire Invalidate Event so that the Report Tabbed Document can Reload this.OnInvalidated(new EventArgs()); }
protected bool SetXmlStringValue(XPathNavigator navigator, string valueName, string newValue) { if (navigator == null || String.IsNullOrEmpty(valueName)) { return(false); } try { XPathNavigator factory = navigator.Clone(); do { factory.MoveToFirstAttribute(); if (String.Compare(factory.Name, valueName) == 0) { factory.SetValue(newValue); return(true); } }while (!factory.MoveToNextAttribute()); navigator.CreateAttribute(String.Empty, valueName, String.Empty, newValue); return(true); } catch (Exception ex) { this.WriteMessage(MessageLevel.Error, ex); return(false); } }
private static void RawSetAttribute(this XPathNavigator element, XName name, string value) { var attNav = element.MoveCloneToAttribute(name); var hasAttribute = attNav != null; if (value == null) { if (hasAttribute) { attNav.DeleteSelf(); } // Otherwise, the attribute didn't exist anyway. } else { if (hasAttribute) { // Update existing attribute attNav.SetValue(value); } else { // Create new attribute element.CreateAttribute(null, name.LocalName, name.NamespaceName, value); } } }
public static bool SetXmlStringValue(XPathNavigator parentNode, string valueName, string newValue) { if (parentNode == null || String.IsNullOrEmpty(valueName)) { return(false); } try { XPathNavigator factory = parentNode.Clone(); do { factory.MoveToFirstAttribute(); if (String.Compare(factory.Name, valueName) == 0) { factory.SetValue(newValue); return(true); } }while (!factory.MoveToNextAttribute()); parentNode.CreateAttribute(String.Empty, valueName, String.Empty, newValue); return(true); } catch (ArgumentNullException) { } catch (InvalidOperationException) { } return(false); }
public void SetXmlType(string name, string namespaceUri, XPathNavigator source) { namespaceUri = GetEffectiveNamespace(namespaceUri); var prefix = CreateNamespace(null, namespaceUri, source); source.CreateAttribute("xsi", "type", Xsi, GetQualifiedName(prefix, name)); }
public string CreateNamespace(string prefix, string namespaceUri, XPathNavigator source) { if (string.IsNullOrEmpty(namespaceUri) == false) { source = source.Clone(); source.MoveToRoot(); source.MoveToChild(XPathNodeType.Element); if (string.IsNullOrEmpty(prefix)) { prefix = AddNamespace(namespaceUri); } var existing = source.GetNamespace(prefix); if (existing == namespaceUri) { return(prefix); } if (string.IsNullOrEmpty(existing) == false) { return(null); } source.CreateAttribute("xmlns", prefix, "", namespaceUri); } return(prefix); }
public XPathNavigator CreateAttribute(string name, string namespaceUri, XPathNavigator source) { name = XmlConvert.EncodeLocalName(name); source.CreateAttribute(null, name, namespaceUri, ""); source.MoveToAttribute(name, namespaceUri ?? ""); return(source); }
public static void InsertNamespacesIntoElement(Hashtable namespacesHash, XmlElement node) { XPathNavigator nav = node.CreateNavigator(); if (string.IsNullOrEmpty(nav.Prefix) && string.IsNullOrEmpty(nav.GetAttribute("xmlns", ""))) { nav.CreateAttribute("", "xmlns", "", nav.NamespaceURI); } foreach (DictionaryEntry namespacePair in namespacesHash) { string[] attrName = ((string)namespacePair.Key).Split(':'); if (attrName.Length > 1 && !node.HasAttribute(attrName[0] + ":" + attrName[1])) { nav.CreateAttribute(attrName[0], attrName[1], "", (string)namespacePair.Value); } } }
public bool MakeNil(XPathNavigator source) { if (source.NodeType == XPathNodeType.Element && IsNil(source) == false) { source.CreateAttribute("xsi", "nil", Xsi, "true"); return(true); } return(false); }
private static XmlElement GenerateCustomReference(XmlDocument doc, XmlElement signedElement, String uri, String type, String id) { XmlElement reference = doc.CreateElement("Reference", SecurityConstants.XMLDSIG_URI); if (uri == null) { uri = string.Empty; } reference.SetAttribute("URI", uri); if (type != null) { reference.SetAttribute("Type", type); } if (id != null) { reference.SetAttribute("Id", id); } XmlElement xpathSelect = (XmlElement)signedElement.CloneNode(true); XPathNavigator xpathSelectNavigator = xpathSelect.CreateNavigator(); NormalizeNamespaces(doc.DocumentElement.CreateNavigator(), xpathSelectNavigator); xpathSelectNavigator.CreateAttribute("xmlns", "xades", SecurityConstants.XMLNS_URI, SecurityConstants.XADES_132_URI); xpathSelectNavigator.CreateAttribute("xmlns", "", SecurityConstants.XMLNS_URI, SecurityConstants.XMLDSIG_URI); XmlDocument digestDoc = new XmlDocument(doc.NameTable); digestDoc.XmlResolver = null; digestDoc.LoadXml(xpathSelect.OuterXml); byte[] md = CalculateC14nDigest(digestDoc, new SHA1Managed()); XmlElement digestMethod = doc.CreateElement("DigestMethod", SecurityConstants.XMLDSIG_URI); digestMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_SHA1); reference.AppendChild(digestMethod); XmlElement digestValue = doc.CreateElement("DigestValue", SecurityConstants.XMLDSIG_URI); digestValue.AppendChild(doc.CreateTextNode(Convert.ToBase64String(md))); reference.AppendChild(digestValue); return(reference); }
static void SetAttr(XPathNavigator node, string attr, double value) { node = node.Clone(); if (node.MoveToAttribute(attr, string.Empty)) { node.SetValue(value.ToString()); } else { node.CreateAttribute(null, attr, null, value.ToString()); } }
public static void SetOrCreateXmlAttribute(XPathNavigator node, string localName, string namespaceURI, string value) { if (node.MoveToAttribute(localName, namespaceURI)) { node.SetValue(value); node.MoveToParent(); } else { node.CreateAttribute("", localName, namespaceURI, value); } }
public bool MakeNil(XPathNavigator source) { if (source.NodeType == XPathNodeType.Element && IsNil(source) == false) { if (source.LookupPrefix(Xsi) != "xsi") { CreateNamespace("xsi", Xsi, source); } source.CreateAttribute("xsi", "nil", Xsi, "true"); return(true); } return(false); }
public XPathNavigator CreateAttribute(string name, string namespaceUri, XPathNavigator source) { string prefix; name = XmlConvert.EncodeLocalName(name); if (IsRootNamespace(namespaceUri, out prefix)) { prefix = CreateNamespace(prefix, namespaceUri, source); } source.CreateAttribute(prefix, name, namespaceUri, ""); source.MoveToAttribute(name, namespaceUri ?? ""); return(source); }
private static void NormalizeNamespaces(XPathNavigator src, XPathNavigator dest) { IDictionary <string, string> dictLocal = src.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); IDictionary <string, string> dictExclude = dest.GetNamespacesInScope(XmlNamespaceScope.Local); foreach (KeyValuePair <string, string> pair in dictLocal) { if (!dictExclude.ContainsKey(pair.Key)) { dest.CreateAttribute("xmlns", pair.Key, "http://www.w3.org/2000/xmlns/", pair.Value); } } }
public static void CreateAttribute(XPathNavigator nav, string attributeName, string newAttValue) { if (nav.HasAttributes) { if (string.IsNullOrEmpty(nav.GetAttribute(attributeName, string.Empty))) { nav.CreateAttribute(string.Empty, attributeName, string.Empty, newAttValue); } else { nav.MoveToAttribute(attributeName, string.Empty); nav.SetValue(newAttValue); //move back to the element nav.MoveToParent(); } } }
static void XPathNavigatorMethods_CreateAttribute() { // XPathNavigator.CreateAttribute(string, string, string, string) //<snippet7> XmlDocument document = new XmlDocument(); document.Load("contosoBooks.xml"); XPathNavigator navigator = document.CreateNavigator(); navigator.MoveToChild("bookstore", "http://www.contoso.com/books"); navigator.MoveToChild("book", "http://www.contoso.com/books"); navigator.MoveToChild("price", "http://www.contoso.com/books"); navigator.CreateAttribute("", "discount", "", "1.00"); navigator.MoveToParent(); Console.WriteLine(navigator.OuterXml); //</snippet7> }
internal static void InsertUpdateAttibuteValue(XPathNavigator nav, string attributePath, string value) { if (string.IsNullOrEmpty(attributePath) || !attributePath.StartsWith("@")) { throw new NotSupportedException("Incorrect Attribute Path" + attributePath); } XPathNavigator node = nav.SelectSingleNode(attributePath); if (node != null) { node.SetValue(value); } else { if (value != null) { string attrName = attributePath.Remove(0, 1); nav.CreateAttribute(null, attrName, null, value); } } }
/// <summary> Добавить атрибут </summary> /// <returns> Навигатор для добавленного элемента </returns> public static XPathNavigator AddAttribute(this XPathNavigator navigator, string name, string val = "") { navigator.CreateAttribute("", name, "", val); return(navigator.SelectSingleNode("@" + name)); }
static void ScanPath( String path ) { string ] files = Directory.GetFiles( path, ".vcxproj", SearchOption.AllDirectories ); foreach( String file in files ) { bool updated = false; if( file.Contains( "INSTALL.vcxproj" ) ) continue; if( file.Contains( "ZERO_CHECK.vcxproj" ) ) continue; if( file.Contains( "ALL_BUILD.vcxproj" ) ) continue; if( file.Contains( "PACKAGE.vcxproj" ) ) continue; if( file.Contains( "bag.externals.vcxproj" ) ) continue; XmlDocument xd = new XmlDocument(); try { xd.Load( file ); } catch { continue; } XPathNavigator xn = xd.CreateNavigator(); xn.MoveToFirst(); String target_framework = null; bool okay; bool found_project_import = false; bool found_target = false; okay = xn.MoveToFirstChild(); while( xn.NodeType == XPathNodeType.Comment ) okay = xn.MoveToNext(); for( okay = xn.MoveToFirstChild(); okay; okay = xn.MoveToNext() ) { retry: if( xn.Name == "Import" ) { bool ok2; bool ever_ok2 = false; bool found_condition = false; for( ok2 = xn.MoveToFirstAttribute(); ok2; ok2 = xn.MoveToNextAttribute() ) { ever_ok2 = true; if( xn.Name == "Project" && xn.Value == "$(VCTargetsPath)\\Microsoft.Cpp.targets" ) { found_project_import = true; found_target = false; } } if( ever_ok2 ) { xn.MoveToParent(); } } else if( xn.Name == "Target" ) { found_target = true; } else if( xn.Name == "ImportGroup" ) { if( found_project_import && !found_target ) { xn.InsertElementBefore( null, "Target", null, null ); xn.MoveToPrevious(); xn.CreateAttribute( null, "Name", null, "GenerateTargetFrameworkMonikerAttribute" ); xn.MoveToNext(); updated = true; } } else if( xn.Name == "PropertyGroup" ) { bool found_outpath = false; bool found_intermed_1 = false; bool found_intermed_2 = false; bool found_base_output = false; bool found_framework = false; bool ok2; bool ever_ok2 = false; bool found_condition = false; for( ok2 = xn.MoveToFirstAttribute(); ok2; ok2 = xn.MoveToNextAttribute() ) { ever_ok2 = true; if( xn.Name == "Label" ) { if( xn.Value == "Globals" ) found_condition = true; break; } } if( ever_ok2 ) xn.MoveToParent(); bool found_support = false; bool found_version = false; ever_ok2 = false; for( ok2 = xn.MoveToFirstChild(); ok2; ok2 = xn.MoveToNext() ) { ever_ok2 = true; if( xn.Name == "TargetFrameworkVersion" ) { found_framework = true; if( found_condition ) { xn.SetValue( "v4.0" ); updated = true; } } if( xn.Name == "CLRSupport" ) { found_support = true; if( found_condition ) { xn.SetValue( "true" ); updated = true; } else { xn.DeleteSelf(); xn.MoveToFirstChild(); } } // < TargetFrameworkVersion Condition = "'$(TargetFrameworkVersion)'==''" > v2.0 </ TargetFrameworkVersion > } if( ever_ok2 ) { xn.MoveToParent(); if( found_condition ) { if( !found_support ) { xn.AppendChildElement( null, "CLRSupport", null, "true" ); updated = true; } if( !found_framework ) { xn.AppendChildElement( null, "TargetFrameworkVersion", null, "v4.0" ); updated = true; } } } found_condition = false; } } if( updated ) { //listBox1.Items.Add( file ); if( !File.Exists( file + ".backup" ) ) File.Copy( file, file + ".backup" ); xd.Save( file ); } //else // listBox1.Items.Add( "Ignore:"+file ); //listBox1.Refresh(); } }
public static void CreateAttribute(this XPathNavigator navigator, string name, string value) { navigator.CreateAttribute("", name, "", value); }
/// <summary> /// Look up the shared content elements, find their corresponding shared content item and replace the /// elements with the content item value. /// </summary> /// <param name="key">The document key</param> /// <param name="document">The document containing the topic</param> /// <param name="start">The XPath navigator to search for content elements</param> /// <remarks>This method will replace content items within other content items recursively</remarks> private void ResolveContent(string key, XmlDocument document, XPathNavigator start) { List <string> parameters = new List <string>(); // For each kind of shared content element... foreach (SharedContentElement element in elements) { // Find all such elements, convert to an array so as not to cause an error when manipulating the // document, and process each element. foreach (XPathNavigator node in start.Select(element.Path).ToArray()) { // Get the item key string item = node.Evaluate(element.Item).ToString(); // Check for a missing item key if (String.IsNullOrEmpty(item)) { this.WriteMessage(key, MessageLevel.Warn, "A shared content element did not specify an item"); } else { // Extract any parameters parameters.Clear(); XPathNodeIterator parameterNodes = node.Select(element.Parameters); foreach (XPathNavigator parameterNode in parameterNodes) { parameters.Add(parameterNode.GetInnerXml()); } // Find the content item and format the parameters into the value string contentValue = null; if (content.TryGetValue(item, out contentValue)) { try { contentValue = String.Format(CultureInfo.InvariantCulture, contentValue, parameters.ToArray()); } catch (FormatException) { this.WriteMessage(key, MessageLevel.Error, "The shared content item '{0}' " + "could not be formatted with {1} parameters.", item, parameters.Count); } } // Check for missing content if (contentValue == null) { this.WriteMessage(key, MessageLevel.Warn, "Missing shared content item. Tag: " + "'{0}'; Id:'{1}'.", node.LocalName, item); } else { // Store the content in a document fragment XmlDocumentFragment fragment = document.CreateDocumentFragment(); fragment.InnerXml = contentValue; // Resolve any shared content in the fragment this.ResolveContent(key, document, fragment.CreateNavigator()); // Look for an attribute name string attribute = node.Evaluate(element.Attribute).ToString(); // Insert the resolved content... if (String.IsNullOrEmpty(attribute)) { // ...as mixed content XmlWriter writer = node.InsertAfter(); fragment.WriteTo(writer); writer.Close(); } else { // ...as an attribute XPathNavigator parent = node.CreateNavigator(); parent.MoveToParent(); parent.CreateAttribute(String.Empty, attribute, String.Empty, fragment.InnerText); } } } // Keep a reference to the parent element XPathNavigator parentElement = node.CreateNavigator(); parentElement.MoveToParent(); // Remove the node node.DeleteSelf(); // If there is no content left in the parent element, make sure it is self-closing if (!parentElement.HasChildren && !parentElement.IsEmptyElement) { // If the node was already the root then we will have a blank node now and // doing an InsertAfter() will throw an exception. if (parentElement.Name.Length > 0) { // Create a new element XmlWriter attributeWriter = parentElement.InsertAfter(); attributeWriter.WriteStartElement(parentElement.Prefix, parentElement.LocalName, parentElement.NamespaceURI); // Copy attributes to it XmlReader attributeReader = parentElement.ReadSubtree(); attributeReader.Read(); attributeWriter.WriteAttributes(attributeReader, false); attributeReader.Close(); // Close it attributeWriter.WriteEndElement(); attributeWriter.Close(); // Delete the old element parentElement.DeleteSelf(); } else { // If we are inside a tag such as title, removing the content will leave it in the // form "<title />" which is not allowed in HTML. Since this usually means there is // a problem with the shared content or the transforms leading up to this, we will // just report the error here. this.WriteMessage(key, MessageLevel.Error, "Error replacing item. Root document " + "element encountered."); } } } } }
private void MakeNavigationFile( ContentURI uri, string packageFilePathName, IDictionary <string, string> args, ref string contentNewPath, ref string errorMsg) { string sPackagePartValue = Path.GetFileName(packageFilePathName); string sPartFullPath = string.Empty; string sRelPartPath = string.Empty; string sMimeType = string.Empty; //need an editable navigator XmlDocument xmlNavigationDoc = new XmlDocument(); XmlReader reader = Helpers.FileStorageIO.GetXmlReader(uri, contentNewPath); if (reader != null) { using (reader) { xmlNavigationDoc.Load(reader); } XPathNavigator navNavigationDoc = xmlNavigationDoc.CreateNavigator(); //move to ncx navNavigationDoc.MoveToFirstChild(); //move to navMap navNavigationDoc.MoveToFirstChild(); //move to navPoint bool bHasMoved = navNavigationDoc.MoveToFirstChild(); if (bHasMoved) { string sKey = string.Empty; string sValue = string.Empty; int j = 2; foreach (KeyValuePair <string, string> kvp in args) { sKey = kvp.Key; sValue = kvp.Value; if (sValue == sPackagePartValue) { if (string.IsNullOrEmpty(sKey) == false) { //clients use same relative paths as server //convert the absolute path of partFullPath into a path relative to the package root (getcurrentdirectory) sRelPartPath = AppSettings.ConvertAbsPathToRelPath(CurrentDirectory, sKey); navNavigationDoc.InsertElementAfter(string.Empty, "navPoint", string.Empty, string.Empty); navNavigationDoc.MoveToNext(); navNavigationDoc.CreateAttribute(string.Empty, "id", string.Empty, j.ToString()); navNavigationDoc.CreateAttribute(string.Empty, "playOrder", string.Empty, j.ToString()); navNavigationDoc.AppendChildElement(string.Empty, "navLabel", string.Empty, string.Empty); navNavigationDoc.MoveToChild(XPathNodeType.Element); navNavigationDoc.AppendChildElement(string.Empty, "text", string.Empty, Path.GetFileNameWithoutExtension(sRelPartPath)); navNavigationDoc.InsertElementAfter(string.Empty, "content", string.Empty, string.Empty); navNavigationDoc.MoveToNext(); navNavigationDoc.CreateAttribute(string.Empty, "src", string.Empty, sRelPartPath); //move to navPoint navNavigationDoc.MoveToParent(); j++; } } } } string sTocNewPath = Path.Combine(Path.GetDirectoryName(contentNewPath), NCX_FILE); Helpers.FileStorageIO.MoveURIs(uri, contentNewPath, sTocNewPath); contentNewPath = sTocNewPath; } }
private void ResolveContent(XmlDocument document, XPathNavigator start) { if (_pathSelector == null) { return; } // find all such elements XPathNodeIterator nodeIterator = start.Select(_pathSelector); if (nodeIterator == null || nodeIterator.Count == 0) { return; } // convert to an array so as not to cause an error when manipulating the document XPathNavigator[] nodes = ToArray(nodeIterator); // process each element int nodeCount = nodes.Length; for (int i = 0; i < nodeCount; i++) { XPathNavigator node = nodes[i]; // get the key string item = node.Evaluate(_itemSelector).ToString(); // check for missing key if (String.IsNullOrEmpty(item)) { LogMessage(BuildLoggerLevel.Warn, "A shared content element did not specify an item."); } else { // extract parameters List <string> parameters = new List <string>(); XPathNodeIterator parameter_nodes = node.Select(_parametersSelector); foreach (XPathNavigator parameter_node in parameter_nodes) { string parameter = GetInnerXml(parameter_node); parameters.Add(parameter); } // get the content string content = GetContent(item, parameters.ToArray()); // check for missing content if (content == null) { if (_warnIfNotFound) { LogMessage(BuildLoggerLevel.Warn, String.Format( "Missing shared content item. Tag:'{0}'; Id:'{1}'.", node.LocalName, item)); } if (_deleteIfNotFound) { node.DeleteSelf(); } } else { // store the content in a document fragment XmlDocumentFragment fragment = document.CreateDocumentFragment(); fragment.InnerXml = content; // resolve any shared content in the fragment ResolveContent(document, fragment.CreateNavigator()); // look for an attribute name string attribute = node.Evaluate(_attributeSelector).ToString(); // insert the resolved content if (String.IsNullOrEmpty(attribute)) { // as mixed content XmlWriter writer = node.InsertAfter(); fragment.WriteTo(writer); writer.Close(); } else { // as an attribute XPathNavigator parent = node.CreateNavigator(); parent.MoveToParent(); parent.CreateAttribute(String.Empty, attribute, String.Empty, fragment.InnerText); } } } // keep a reference to the parent element XPathNavigator parentElement = node.CreateNavigator(); parentElement.MoveToParent(); // remove the node node.DeleteSelf(); // if there is no content left in the parent element, make sure it is self-closing if (!parentElement.HasChildren && !parentElement.IsEmptyElement) { //If 'node' was already the root then we will have a blank node now and //doing an InsertAfter() will throw an exception. if (parentElement.Name.Length > 0) { // create a new element XmlWriter attributeWriter = parentElement.InsertAfter(); attributeWriter.WriteStartElement(parentElement.Prefix, parentElement.LocalName, parentElement.NamespaceURI); // copy attributes to it XmlReader attributeReader = parentElement.ReadSubtree(); attributeReader.Read(); attributeWriter.WriteAttributes(attributeReader, false); attributeReader.Close(); // close it attributeWriter.WriteEndElement(); attributeWriter.Close(); // delete the old element parentElement.DeleteSelf(); } else { //if we are inside a tag such as title, removing the content will make it in the //form of <title /> which is not allowed in html. //Since this usually means there is a problem with the shared content or the transforms //leading up to this we will just report the error here. LogMessage(BuildLoggerLevel.Error, "Error replacing item."); } } } }
/// <inheritdoc /> public override void Apply(XmlDocument document, string key) { currentKey = key; XPathNavigator targetDoc = document.CreateNavigator(); foreach (CopySet copySet in copySets) { XPathExpression targetExpression = copySet.GetTargetExpression(targetDoc, key); // get the target nodes in the document XPathNavigator targetNode = targetDoc.SelectSingleNode(targetExpression); while (targetNode != null) { string targetId = targetNode.Value; int pound = (String.IsNullOrEmpty(targetId)) ? -1 : targetId.IndexOf('#'); string bkeyword = (pound == -1) ? "" : targetId.Substring(pound + 1); if (bkeyword.Length == 0) { base.WriteMessage(key, MessageLevel.Warn, "Invalid id '{0}' in topic '{1}'.", targetId, currentKey); // delete this target and get the next target node targetNode.DeleteSelf(); targetNode = targetDoc.SelectSingleNode(targetExpression); continue; } List <string> idList; if (!bKeywordMap.TryGetValue(bkeyword, out idList)) { base.WriteMessage(key, MessageLevel.Warn, "B-keyword not found '{0}' in topic '{1}'.", targetId, currentKey); // delete this target and get the next target node targetNode.DeleteSelf(); targetNode = targetDoc.SelectSingleNode(targetExpression); continue; } if (idList.Count > 1) { Console.Write(""); } // create a 'tasks' node to replace the target XPathNavigator tasksNode = document.CreateElement("tasks").CreateNavigator(); tasksNode.CreateAttribute(string.Empty, "bkeyword", string.Empty, bkeyword); foreach (string topicId in idList) { //create a task node for this source topic XPathNavigator taskNode = document.CreateElement("task").CreateNavigator(); taskNode.CreateAttribute(string.Empty, "topicId", string.Empty, topicId); // get the source document for the topic id string filepath; if (!index.TryGetValue(topicId, out filepath)) { base.WriteMessage(key, MessageLevel.Warn, "No file found for topicId '{0}' for " + "B-keyword '{1}'. Source topic: '{2}'.", topicId, bkeyword, currentKey); continue; } XPathNavigator sourceDoc = new XPathDocument(filepath).CreateNavigator(); XPathNavigator sourceNode = sourceDoc.SelectSingleNode(valueQuery); if (sourceNode == null) { continue; } XPathNodeIterator sources = sourceNode.Select(copySet.SourceExpression); // append the source nodes to the target node if (sources.Count > 0) { foreach (XPathNavigator source in sources) { taskNode.AppendChild(source); } } tasksNode.AppendChild(taskNode); } targetNode.ReplaceSelf(tasksNode); // get the next target node targetNode = targetDoc.SelectSingleNode(targetExpression); } } }
/** * Sets the XORed or hashed password * * @param xobj the xmlbeans object which Contains the password attributes * @param password the password, if null, the password attributes will be Removed * @param hashAlgo the hash algorithm, if null the password will be XORed * @param prefix the prefix of the password attributes, may be null */ public static void SetPassword(XmlNode xobj, String password, HashAlgorithm hashAlgo, String prefix) { XPathNavigator cur = xobj.CreateNavigator(); if (password == null) { //dose the prefix is namespace? check it!!! if (cur.MoveToAttribute("password", prefix)) { cur.DeleteSelf(); } if (cur.MoveToAttribute("algorithmName", prefix)) { cur.DeleteSelf(); } if (cur.MoveToAttribute("hashValue", prefix)) { cur.DeleteSelf(); } if (cur.MoveToAttribute("saltValue", prefix)) { cur.DeleteSelf(); } if (cur.MoveToAttribute("spinCount", prefix)) { cur.DeleteSelf(); } return; } //cur.ToFirstContentToken(); if (hashAlgo == null) { int hash = CryptoFunctions.CreateXorVerifier1(password); cur.CreateAttribute(prefix, "password", null, String.Format("{0:X4}", hash).ToUpper()); //cur.InsertAttributeWithValue(GetAttrName(prefix, "password"), // String.Format("{0:X}", hash).ToUpper()); } else { SecureRandom random = new SecureRandom(); byte[] salt = random.GenerateSeed(16); // Iterations specifies the number of times the hashing function shall be iteratively run (using each // iteration's result as the input for the next iteration). int spinCount = 100000; // Implementation Notes List: // --> In this third stage, the reversed byte order legacy hash from the second stage shall // be Converted to Unicode hex string representation byte[] hash = CryptoFunctions.HashPassword(password, hashAlgo, salt, spinCount, false); cur.CreateAttribute(prefix, "algorithmName", null, hashAlgo.jceId); cur.CreateAttribute(prefix, "hashValue", null, Convert.ToBase64String(hash)); cur.CreateAttribute(prefix, "saltValue", null, Convert.ToBase64String(salt)); cur.CreateAttribute(prefix, "spinCount", null, "" + spinCount); //cur.InsertAttributeWithValue(GetAttrName(prefix, "algorithmName"), hashAlgo.jceId); //cur.InsertAttributeWithValue(GetAttrName(prefix, "hashValue"), Convert.ToBase64String(hash)); //cur.InsertAttributeWithValue(GetAttrName(prefix, "saltValue"), Convert.ToBase64String(salt)); //cur.InsertAttributeWithValue(GetAttrName(prefix, "spinCount"), "" + spinCount); } //cur.Dispose(); }
/// <summary> /// Annotate an xml document with a sort key suitable for xslt version 1 sorting algorithms (use lang='en') /// </summary> /// <param name="document">input to add sort keys to</param> /// <param name="xpathSortKeySource">an xpath that selects the source to use to create a sort key</param> /// <param name="sortKeyGenerator">delegate that returns a SortKey given a string</param> /// <param name="xpathElementToPutSortKeyAttributeIn">a relative xpath (from the source) that selects the element to put the sortkey attribute in</param> /// <param name="prefix">The prefix of the sort-key attribute</param> /// <param name="attribute">The sort key attribute</param> /// <param name="namespaceUri">The namespace of the sortkey attribute</param> public static void AddSortKeys( XPathNavigator document, string xpathSortKeySource, SortKeyGenerator sortKeyGenerator, string xpathElementToPutSortKeyAttributeIn, string prefix, string attribute, string namespaceUri) { if (document == null) { throw new ArgumentNullException("document"); } if (xpathSortKeySource == null) { throw new ArgumentNullException("xpathSortKeySource"); } if (sortKeyGenerator == null) { throw new ArgumentNullException("sortKeyGenerator"); } if (xpathElementToPutSortKeyAttributeIn == null) { throw new ArgumentNullException("xpathElementToPutSortKeyAttributeIn"); } if (attribute == null) { throw new ArgumentNullException("attribute"); } if (prefix != null | namespaceUri != null) // if both are null it's okay but if only one it's an error { if (prefix == null) { throw new ArgumentNullException("prefix"); } if (prefix.Length == 0) { throw new ArgumentException("Invalid prefix. Prefix cannot be empty."); } if (namespaceUri == null) { throw new ArgumentNullException("prefix"); } if (namespaceUri.Length == 0) { throw new ArgumentException("Invalid namespace URI. Cannot be empty."); } } XPathExpression compiledXpathElementToPutSortKeyAttributeIn = XPathExpression.Compile(xpathElementToPutSortKeyAttributeIn); foreach (XPathNavigator sortKeySource in document.Select(xpathSortKeySource)) { byte[] sortKeyData = sortKeyGenerator(sortKeySource.Value).KeyData; string sortKeyBase32 = Base32Convert.ToBase32HexString(sortKeyData, Base32FormattingOptions.None); XPathNavigator elementToPutSortKeyAttributeIn = sortKeySource.SelectSingleNode(compiledXpathElementToPutSortKeyAttributeIn); if (elementToPutSortKeyAttributeIn.MoveToAttribute(attribute, namespaceUri ?? string.Empty)) { //now we point at the attribute that already exists elementToPutSortKeyAttributeIn.DeleteSelf(); } elementToPutSortKeyAttributeIn.CreateAttribute(prefix, attribute, namespaceUri, sortKeyBase32); } }