public static string MetaBuild()
    {
        var sb = new StringBuilder();

            sb.AppendLine("\\\\ hello");

            foreach (var proj in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.*proj"))
            {
                sb.AppendLine("\\\\ file: " + proj);

                var xml = new XmlDocument();
                xml.Load(proj);
                var nm = new XmlNamespaceManager(xml.NameTable);
                nm.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");

                foreach (var reference in xml.SelectNodes(@"x:Project\x:ItemGroup\x:Reference"))
                {
                    sb.AppendLine("\\\\" + reference);
                }
                foreach (var reference in xml.SelectNodes(@"x:Project\x:ItemGroup\x:Reference"))
                {
                    sb.AppendLine("\\\\" + reference);
                }
            }
            return sb.ToString();
    }
Exemple #2
1
  protected void GenerateAction_Click(object sender, EventArgs e)
  {
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(Resources.MyResourceStrings.MyDocument);

    XmlNode TextNode;
    XmlNamespaceManager NsMgr = new XmlNamespaceManager(doc.NameTable);
    NsMgr.AddNamespace("ns1", "uri:AspNetPro20/Chapter16/Demo1");
    NsMgr.AddNamespace("w", "http://schemas.microsoft.com/office/word/2003/wordml");

    TextNode = doc.SelectSingleNode("//ns1:Firstname//w:p", NsMgr);
    TextNode.InnerXml = string.Format("<w:r><w:t>{0}</w:t></w:r>", TextFirstname.Text);

    TextNode = doc.SelectSingleNode("//ns1:Lastname//w:p", NsMgr);
    TextNode.InnerXml = string.Format("<w:r><w:t>{0}</w:t></w:r>", TextLastname.Text);

    TextNode = doc.SelectSingleNode("//ns1:Age//w:p", NsMgr);
    TextNode.InnerXml = string.Format("<w:r><w:t>{0}</w:t></w:r>", TextAge.Text);

    // Clear the response
    Response.Clear();
    Response.ContentType = "application/msword";
    Response.Write(doc.OuterXml);
    Response.End();
  }
        public CompiledIdentityConstraint(XmlSchemaIdentityConstraint constraint, XmlNamespaceManager nsmgr) {
            this.name = constraint.QualifiedName;

            //public Asttree (string xPath, bool isField, XmlNamespaceManager nsmgr)
            try {
                this.selector = new Asttree(constraint.Selector.XPath, false, nsmgr);
            }
            catch (XmlSchemaException e) {
                e.SetSource(constraint.Selector);
                throw e;
            }
            XmlSchemaObjectCollection fields = constraint.Fields;
            Debug.Assert(fields.Count > 0);
            this.fields = new Asttree[fields.Count];
            for(int idxField = 0; idxField < fields.Count; idxField ++) {
                try {
                    this.fields[idxField] = new Asttree(((XmlSchemaXPath)fields[idxField]).XPath, true, nsmgr);
                }
                catch (XmlSchemaException e) {
                    e.SetSource(constraint.Fields[idxField]);
                    throw e;
                }
            }
            if (constraint is XmlSchemaUnique) {
                this.role = ConstraintRole.Unique;
            } 
            else if (constraint is XmlSchemaKey) {
                this.role = ConstraintRole.Key;
            } 
            else {             // XmlSchemaKeyref
                this.role = ConstraintRole.Keyref;
                this.refer = ((XmlSchemaKeyref)constraint).Refer; 
            }
        }
 public static void DumpProjRefs(string projectFilename, string baseDirectory)
 {
     List<string> files = new List<string>();
     var stream = new MemoryStream(File.ReadAllBytes(projectFilename)); // cache file in memoty
     var document = XDocument.Load(stream);
     var xmlNamespaceManager = new XmlNamespaceManager(new NameTable());
     xmlNamespaceManager.AddNamespace("ns", namespaceName);
     IEnumerable<XElement> listOfSourceFiles = document.XPathSelectElements("/ns:Project/ns:ItemGroup/ns:ProjectReference[@Include]", xmlNamespaceManager);
     foreach (var el in listOfSourceFiles)
     {
         files.Add(el.Attribute("Include").Value);
     }
     string separator = new string(Path.DirectorySeparatorChar, 1);
     string projDir = (new FileInfo(projectFilename)).Directory.FullName;
     foreach (string relativeName in files)
     {
         var correctedRelativeName = relativeName.Replace("\\", separator);
         string fullFileName = Path.Combine(projDir, correctedRelativeName);
         fullFileName = new FileInfo(fullFileName).FullName;
         string shortName;
         if (fullFileName.StartsWith(baseDirectory, StringComparison.InvariantCulture))
         {
             shortName = fullFileName.Substring(baseDirectory.Length);
             if (shortName.StartsWith(separator, StringComparison.InvariantCulture))
             {
                 shortName = shortName.Substring(1);
             }
         }
         else
         {
             shortName = fullFileName;
         }
         Console.WriteLine(shortName);
     }
 }
	void ConfirmSettings() {
		XmlNode newAppendNode;
		XmlElement newAppendElement;
		XmlAttribute newAttribute;
		string xmlNamespace = "http://schemas.android.com/apk/res/android";

		PlayerSettings.bundleIdentifier = bundleIdentifier;
		xmlDoc.Load(rootPath + ANDROID_MANIFEST_PATH);
		XmlNamespaceManager nameSpaceMgr = new XmlNamespaceManager(xmlDoc.NameTable);
		nameSpaceMgr.AddNamespace ("android", xmlNamespace);

		// Xml Manifest node
		XmlNode manifestNode = xmlDoc.SelectSingleNode("descendant::manifest", nameSpaceMgr);
		XmlElement packageElement = (XmlElement)manifestNode;
		packageElement.SetAttribute("package", bundleIdentifier);

		// uses-sdk node
		XmlNode usesSdkNode = xmlDoc.SelectSingleNode("descendant::manifest/uses-sdk", nameSpaceMgr);
		if (usesSdkNode != null) {
			XmlElement minSdkElement = (XmlElement)usesSdkNode;
			minSdkElement.SetAttribute("android:minSdkVersion", "8");
		} else {
			newAppendElement = xmlDoc.CreateElement("uses-sdk");
			newAttribute = CreateXmlAttribute(xmlDoc, "android", "minSdkVersion", xmlNamespace, "8");
			newAppendElement.Attributes.Append(newAttribute);
			newAttribute = CreateXmlAttribute(xmlDoc, "android", "targetSdkVersion", xmlNamespace, "17");
			newAppendElement.Attributes.Append(newAttribute);
			newAppendNode = (XmlNode)newAppendElement;
			manifestNode.AppendChild(newAppendNode);
		}

		xmlDoc.Save(rootPath + ANDROID_MANIFEST_PATH);
	}
Exemple #6
0
        private void Init()
        {
            _nsManager = reader.NamespaceManager;
            if (_nsManager == null)
            {
                _nsManager = new XmlNamespaceManager(NameTable);
                _bManageNamespaces = true;
            }
            _validationStack = new HWStack(STACK_INCREMENT);
            textValue = new StringBuilder();
            _attPresence = new Hashtable();
            schemaInfo = new SchemaInfo();
            checkDatatype = false;
            _processContents = XmlSchemaContentProcessing.Strict;
            Push(XmlQualifiedName.Empty);

            //Add common strings to be compared to NameTable
            _nsXmlNs = NameTable.Add(XmlReservedNs.NsXmlNs);
            _nsXs = NameTable.Add(XmlReservedNs.NsXs);
            _nsXsi = NameTable.Add(XmlReservedNs.NsXsi);
            _xsiType = NameTable.Add("type");
            _xsiNil = NameTable.Add("nil");
            _xsiSchemaLocation = NameTable.Add("schemaLocation");
            _xsiNoNamespaceSchemaLocation = NameTable.Add("noNamespaceSchemaLocation");
            _xsdSchema = NameTable.Add("schema");
        }
    static void Main(string[] args)
    {
        if (args.Length > 0 && args[0] == "-refsonly")
            onlyRefs = true;

        var nsStr = "http://schemas.microsoft.com/developer/msbuild/2003";
        nsManager = new XmlNamespaceManager(new NameTable());
        nsManager.AddNamespace("p", nsStr);
        ns = nsStr;

        //FeatureSamples.Core
        var coreCsproj = @"Samples/FeatureSamples/Core/Urho.Samples.csproj";
        var coreDoc = XDocument.Load(coreCsproj);
        RemovePackagesConfig(coreDoc);
        ReplaceRef(coreDoc, "Urho", "{641886db-2c6c-4d33-88da-97bec0ec5f86}", @"..\..\..\Bindings\Urho.csproj");
        coreDoc.Save(coreCsproj);

        //FeatureSamples.Droid
        var droidCsproj = @"Samples/FeatureSamples/Android/Urho.Samples.Droid.csproj";
        var droidDoc = XDocument.Load(droidCsproj);
        RemovePackagesConfig(droidDoc);
        ReplaceRef(droidDoc, "Urho", "{f0c1189b-75f7-4bd8-b394-a23d5b03eff6}", @"..\..\..\Bindings\Urho.Droid.csproj");
        droidDoc.Save(droidCsproj);

        //FeatureSamples.iOS
        var iosCsproj = @"Samples/FeatureSamples/iOS/Urho.Samples.iOS.csproj";
        var iosDoc = XDocument.Load(iosCsproj);
        RemovePackagesConfig(iosDoc);
        ReplaceRef(iosDoc, "Urho", "{9ae80bd9-e1e2-41da-bb6f-712b35028bd9}", @"..\..\..\Bindings\Urho.iOS.csproj");
        iosDoc.Save(iosCsproj);

        //FeatureSamples.Mac
        var desktopCsproj = @"Samples/FeatureSamples/Mac/Urho.Samples.Mac.csproj";
        var desktopDoc = XDocument.Load(desktopCsproj);
        RemovePackagesConfig(desktopDoc);
        ReplaceRef(desktopDoc, "Urho", "{F0359D5E-D6D4-47D3-A9F0-5A97C31DC476}", @"..\..\..\Bindings\Urho.Desktop.csproj");
        RemoveTargets(desktopDoc);
        desktopDoc.Save(desktopCsproj);

        //FormsSample.Core
        var formsCoreCsproj = @"Samples/FormsSample/FormsSample/FormsSample.csproj";
        var formsCoreDoc = XDocument.Load(formsCoreCsproj);
        RemovePackagesConfig(formsCoreDoc);
        ReplaceRef(formsCoreDoc, "Urho.Forms", "{D599C47F-B9E0-4A58-82E8-6286E0442E8F}", @"..\..\..\Bindings\Urho.Forms.csproj");
        formsCoreDoc.Save(formsCoreCsproj);

        //FormsSample.Droid
        var formsDroidCsproj = @"Samples/FormsSample/FormsSample.Droid/FormsSample.Droid.csproj";
        var formsDroidDoc = XDocument.Load(formsDroidCsproj);
        RemovePackagesConfig(formsDroidDoc);
        ReplaceRef(formsDroidDoc, "Urho.Forms", "{8BAE491B-46F0-4A51-A456-D7A3B332BDC4}", @"..\..\..\Bindings\Urho.Forms.Droid.csproj");
        formsDroidDoc.Save(formsDroidCsproj);

        //FormsSample.iOS
        var formsIosCsproj = @"Samples/FormsSample/FormsSample.iOS/FormsSample.iOS.csproj";
        var formsIosDoc = XDocument.Load(formsIosCsproj);
        RemovePackagesConfig(formsIosDoc);
        ReplaceRef(formsIosDoc, "Urho.Forms", "{8F3352BA-BF6A-49F8-81D6-58D54B3EA72B}", @"..\..\..\Bindings\Urho.Forms.iOS.csproj");
        formsIosDoc.Save(formsIosCsproj);
    }
    public void Adjust(string fileName)
    {
        try
        {
            string path = Path.GetDirectoryName(Application.dataPath+"..");
            if (File.Exists(path+"/"+fileName))
            {
                TextReader tx = new StreamReader(path+"/"+fileName);
                if (doc == null)
                    doc = new XmlDocument();
                doc.Load(tx);
                tx.Close();
                if (doc!=null && doc.DocumentElement!=null)
                {
                    string xmlns = doc.DocumentElement.Attributes["xmlns"].Value;
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                    nsmgr.AddNamespace("N",xmlns);

                    SetNode("TargetFrameworkVersion","v4.0", nsmgr);
                    // SetNode("DefineConstants","TRACE;UNITY_3_5_6;UNITY_3_5;UNITY_EDITOR;ENABLE_PROFILER;UNITY_STANDALONE_WIN;ENABLE_GENERICS;ENABLE_DUCK_TYPING;ENABLE_TERRAIN;ENABLE_MOVIES;ENABLE_WEBCAM;ENABLE_MICROPHONE;ENABLE_NETWORK;ENABLE_CLOTH;ENABLE_WWW;ENABLE_SUBSTANCE", nsmgr);

                    TextWriter txs = new StreamWriter(path+"/"+fileName);
                    doc.Save(txs);
                    txs.Close();
                }
            }
        }
        catch(System.Exception)
        {
        }
    }
Exemple #9
0
        internal void StartParsing(XmlReader reader, string targetNamespace, SchemaInfo schemaInfo) {
            this.reader = reader;
            positionInfo = PositionInfo.GetPositionInfo(reader);
            this.namespaceManager = reader.NamespaceManager;
            if (this.namespaceManager == null) {
                this.namespaceManager = new XmlNamespaceManager(this.nameTable);
                this.isProcessNamespaces = true;
            } 
            else {
                this.isProcessNamespaces = false;
            }
            while (this.reader.NodeType != XmlNodeType.Element && this.reader.Read()) {}

            this.markupDepth = int.MaxValue;
			this.schemaXmlDepth = reader.Depth;
            XmlQualifiedName qname = new XmlQualifiedName(this.reader.LocalName, XmlSchemaDatatype.XdrCanonizeUri(this.reader.NamespaceURI, this.nameTable, this.schemaNames));
            if (this.schemaNames.IsXDRRoot(qname)) {
                Debug.Assert(schemaInfo != null);
                schemaInfo.SchemaType = SchemaType.XDR;
                this.schema = null;
                this.builder = new XdrBuilder(reader, this.namespaceManager, schemaInfo, targetNamespace, this.nameTable, this.schemaNames, this.validationEventHandler);
            }
            else if (this.schemaNames.IsXSDRoot(qname)) {
                if (schemaInfo != null) {
                    schemaInfo.SchemaType = SchemaType.XSD;
                }
                this.schema = new XmlSchema();
                this.schema.BaseUri = reader.BaseURI;
                this.builder = new XsdBuilder(reader, this.namespaceManager, this.schema, this.nameTable, this.schemaNames, this.validationEventHandler);
            }
            else { 
                throw new XmlSchemaException(Res.Sch_SchemaRootExpected, reader.BaseURI, positionInfo.LineNumber, positionInfo.LinePosition);
            }
                
        }
    /// <summary>
    /// Gets the time zone.
    /// </summary>
    /// <param name="offset">The offset.</param>
    /// <returns></returns>
    private static string GetTimeZone(double offset)
    {
        //Adjust result based on the server time zone
        string timeZoneKey = "timeOffset" + offset.ToString("F");
        string result = (CallContext.GetData(timeZoneKey) ?? "").ToString();
        if (result.Length == 0)
        {
            string zonesDocPath = HttpRuntime.AppDomainAppPath +"app_data/TimeZones.xml";
            XPathDocument timeZonesDoc = new XPathDocument(zonesDocPath);
            try
            {
                string xPath = "/root/option[@value='" + offset.ToString("F") + "']";
                XPathNavigator searchNavigator = timeZonesDoc.CreateNavigator();
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(searchNavigator.NameTable);
                XPathNodeIterator iterator = searchNavigator.Select(xPath, nsmgr);
                if (iterator.MoveNext())
                {
                    result = iterator.Current.Value;
                    if (!string.IsNullOrEmpty(result))
                    {
                        CallContext.SetData(timeZoneKey, result);
                    }
                }

            }
            catch (Exception ex)
            {
                return  ex.Message;
            }
        }

        return result;
    }
Exemple #11
0
        public void StartParsing(XmlReader reader, string targetNamespace) {
            this.reader = reader;
            positionInfo = PositionInfo.GetPositionInfo(reader);
            namespaceManager = reader.NamespaceManager;
            if (namespaceManager == null) {
                namespaceManager = new XmlNamespaceManager(nameTable);
                isProcessNamespaces = true;
            } 
            else {
                isProcessNamespaces = false;
            }
            while (reader.NodeType != XmlNodeType.Element && reader.Read()) {}

            markupDepth = int.MaxValue;
            schemaXmlDepth = reader.Depth;
            SchemaType rootType = schemaNames.SchemaTypeFromRoot(reader.LocalName, reader.NamespaceURI);
            
            string code;
            if (!CheckSchemaRoot(rootType, out code)) {
                throw new XmlSchemaException(code, reader.BaseURI, positionInfo.LineNumber, positionInfo.LinePosition);
            }
            
            if (schemaType == SchemaType.XSD) {
                schema = new XmlSchema();
                schema.BaseUri = new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute);
                builder = new XsdBuilder(reader, namespaceManager, schema, nameTable, schemaNames, eventHandler);
            }
            else {  
                Debug.Assert(schemaType == SchemaType.XDR);
                xdrSchema = new SchemaInfo();
                xdrSchema.SchemaType = SchemaType.XDR;
                builder = new XdrBuilder(reader, namespaceManager, xdrSchema, targetNamespace, nameTable, schemaNames, eventHandler);
                ((XdrBuilder)builder).XmlResolver = xmlResolver;
            }
        }
Exemple #12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Load document
        string booksFile = Server.MapPath("books.xml");

        XmlDocument document = new XmlDocument();
        document.Load(booksFile);
        XPathNavigator nav = document.CreateNavigator();

        //Add a namespace prefix that can be used in the XPath expression
        XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(nav.NameTable);
        namespaceMgr.AddNamespace("b", "http://example.books.com");

        //All books whose price is not greater than 10.00
        foreach (XPathNavigator node in
            nav.Select("//b:book[not(b:price[. > 10.00])]/b:price",
            namespaceMgr))
        {
            Decimal price = (decimal)node.ValueAs(typeof(decimal));
            node.SetTypedValue(price * 1.2M);
            Response.Write(String.Format("Price raised from {0} to {1}<BR/>",
                price,
                node.ValueAs(typeof(decimal))));
        }
    }
 public static XmlNodeList SelectNodes(this XmlNode node, string xpath, XmlNamespaceManager nsmgr)
 {
     XPathNavigator navigator = CreateNavigator(node);
     if (navigator == null)
         return null;
     return new XPathNodeList(navigator.Select(xpath, nsmgr));
 }
Exemple #14
0
	static int Main ()
	{
		try {
			FaultService svc = new FaultService ();
			svc.Url = "http://" + IPAddress.Loopback.ToString () + ":8081/FaultService.asmx";
			svc.Run ();
			return 1;
		} catch (SoapException ex) {
			if (ex.Actor != "Mono Web Service")
				return 2;
			if (ex.Code != SoapException.ServerFaultCode)
				return 3;
			if (ex.Detail == null)
				return 4;
			if (ex.Detail.LocalName != "detail")
				return 5;
			if (ex.Detail.NamespaceURI != string.Empty)
				return 6;

			XmlNamespaceManager nsMgr = new XmlNamespaceManager (ex.Detail.OwnerDocument.NameTable);
			nsMgr.AddNamespace ("se", "http://www.mono-project/System");

			XmlElement systemError = (XmlElement) ex.Detail.SelectSingleNode (
				"se:systemerror", nsMgr);
			if (systemError == null)
				return 7;
			if (ex.InnerException != null)
				return 8;
			if (ex.Message != "Failure processing request.")
				return 9;
			return 0;
		}
	}
Exemple #15
0
 internal void Preprocess(XmlSchema schema, string targetNamespace) {          
     this.namespaceManager = new XmlNamespaceManager(this.nameTable);
     this.schema = schema;
     this.ids = schema.Ids;
     this.identityConstraints = schema.IdentityConstraints;
     ValidateIdAttribute(schema);
     Preprocess(schema, targetNamespace, Compositor.Root);
 }
Exemple #16
0
    /// <summary>
    /// Creates a namespace manager needed for XML XPath queries
    /// </summary>
    /// <param name="prefix"></param>
    /// <returns></returns>
    public static XmlNamespaceManager CreateTableauXmlNamespaceManager(string prefix)
    {
        var msTable = new NameTable();
        var ns = new XmlNamespaceManager(msTable);
        ns.AddNamespace(prefix, "http://tableausoftware.com/api");

        return ns;
    }
 public Environment ParseFromFile(String filename)
 {
     XmlDocument xmlDoc = new XmlDocument ();
     xmlDoc.Load (filename);
     XmlNamespaceManager nsman = new XmlNamespaceManager (xmlDoc.NameTable);
     nsman.AddNamespace ("ns", xmlDoc.DocumentElement.NamespaceURI);
     return Parse(xmlDoc, nsman);
 }
	// Test namespace manager construction.
	public void TestXmlNamespaceManagerConstruct()
			{
				try
				{
					XmlNamespaceManager ns = new XmlNamespaceManager(null);
				}
				catch(ArgumentNullException)
				{
				}
			}
 public AmazonSearchBookResult(XDocument lookupResult)
 {
     this.RawData = lookupResult;
     this._NameSpaceManager = new Lazy<XmlNamespaceManager>(() => {
         var nameTable = RawData.Root.CreateReader().NameTable;
         var nsmgr = new XmlNamespaceManager(nameTable);
         nsmgr.AddNamespace("ns", this.RawData.Root.Name.NamespaceName);
         return nsmgr;
     });
 }
    public List<FeedData> ReadData()
    {
        //Load the document
        XmlDocument doc = new XmlDocument();
        XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
        namespaces.AddNamespace("ns", "urn:hl7-org:v3");
        doc.Load(_masterFile);

        var nodeList = doc.DocumentElement.SelectNodes("channel/item");

        foreach (XmlNode node in nodeList)
        {
            string title = node["title"]?.InnerText;
            string description = node["description"]?.InnerText;

            string link = string.Empty;
            string pubdate = string.Empty;

            if (node["link"] != null)
            {
                link = node["link"]?.InnerText;
            }
            else if (node["a10:link"] != null)
            {
                link = node["a10:link"].Attributes[0].InnerText;
                //link = node["a10:link"].InnerText;
            }

            if (node["pubDate"] != null)
            {
                pubdate = node["pubDate"].InnerText;
            }
            else if (node["a10:updated"] != null)
            {
                pubdate = node["a10:updated"].InnerText;
            }

            fdata = new FeedData();
            fdata.publishdate = Convert.ToDateTime(pubdate);
            fdata.link = link;
            fdata.title = title;
            if (Regex.Replace(description, "<[^>]*>", "").Length > 300)
            {
                fdata.description = Regex.Replace(description, "<[^>]*>", "").Substring(0, 299) + "...";
            }
            else
            {
                fdata.description = Regex.Replace(description, "<[^>]*>", "");
            }
            feedData.Add(fdata);
        }

        return feedData;

    }
Exemple #21
0
            public bool IsValid()
            {
                bool status = false;

                XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
                manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
                XmlNodeList nodeList = xmlDoc.SelectNodes("//ds:Signature", manager);

                SignedXml signedXml = new SignedXml(xmlDoc);
                signedXml.LoadXml((XmlElement)nodeList[0]);
                return signedXml.CheckSignature(certificate.cert, true);
            }
Exemple #22
0
  public void Run ()
  {
    if (templateFile == null || templateFile.Length == 0 ||
	targetDir == null || targetDir.Length == 0)
      throw new ApplicationException ("Missing or invalid installation data");

    XmlDocument doc = new XmlDocument ();
    doc.Load (templateFile);
    nsmgr = new XmlNamespaceManager (doc.NameTable);
    nsmgr.AddNamespace ("def", "http://schemas.microsoft.com/developer/vstemplate/2005");
    
    ReadTemplateData (doc);
    InstallProject (doc);
  }
 private void Init() {
     nsManager = reader.NamespaceManager;
     if (nsManager == null) {
         nsManager = new XmlNamespaceManager(NameTable);
         isProcessContents = true;
     }
     validationStack = new HWStack(STACK_INCREMENT);
     textValue = new StringBuilder();
     name = XmlQualifiedName.Empty;
     attPresence = new Hashtable();
     Push(XmlQualifiedName.Empty);
     schemaInfo = new SchemaInfo();
     checkDatatype = false;
 }
Exemple #24
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            XmlDocument docForecasts = LoadAllForecasts();

            XPathNavigator navigator = docForecasts.CreateNavigator();
            namespaceManager = new XmlNamespaceManager(navigator.NameTable);
            namespaceManager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
            XmlNodeList channels = docForecasts.SelectNodes("/rss/channel");

            ForecastsView.DataSource = channels;
            ForecastsView.DataBind();
        }
        catch (Exception) { }
    }
	// Test the default namespace manager properties.
	public void TestXmlNamespaceManagerDefaults()
			{
				NameTable table = new NameTable();
				XmlNamespaceManager ns = new XmlNamespaceManager(table);
				AssertEquals("Defaults (1)",
							 "http://www.w3.org/XML/1998/namespace",
							 ns.LookupNamespace("xml"));
				AssertEquals("Defaults (2)",
							 "http://www.w3.org/2000/xmlns/",
							 ns.LookupNamespace("xmlns"));
				AssertEquals("Defaults (3)", "", ns.LookupNamespace(""));
				Assert("Defaults (4)",
					   ReferenceEquals(table, ns.NameTable));
				AssertEquals("Defaults (5)", "", ns.DefaultNamespace);
				AssertNull("Defaults (6)", ns.LookupNamespace("foo"));
			}
	// Test parser context creation.
	public void TestXmlParserContextConstruct()
			{
				NameTable nt = new NameTable();
				NameTable nt2 = new NameTable();
				XmlNamespaceManager ns = new XmlNamespaceManager(nt);
				XmlParserContext ctx;

				// Try to construct with the wrong name table.
				try
				{
					ctx = new XmlParserContext(nt2, ns, null, XmlSpace.None);
					Fail("Construct (1)");
				}
				catch(XmlException)
				{
					// Success
				}

				// Check default property values.
				ctx = new XmlParserContext(null, ns, null, XmlSpace.None);
				AssertEquals("Construct (2)", "", ctx.BaseURI);
				AssertEquals("Construct (3)", "", ctx.DocTypeName);
				AssertEquals("Construct (4)", null, ctx.Encoding);
				AssertEquals("Construct (5)", "", ctx.InternalSubset);
				AssertEquals("Construct (6)", nt, ctx.NameTable);
				AssertEquals("Construct (7)", ns, ctx.NamespaceManager);
				AssertEquals("Construct (8)", "", ctx.PublicId);
				AssertEquals("Construct (9)", "", ctx.SystemId);
				AssertEquals("Construct (10)", "", ctx.XmlLang);
				AssertEquals("Construct (11)", XmlSpace.None, ctx.XmlSpace);

				// Check overridden property values.
				ctx = new XmlParserContext(nt, null, "doctype",
										   "pubid", "sysid", "internal",
										   "base", "lang", XmlSpace.Preserve,
										   Encoding.UTF8);
				AssertEquals("Construct (12)", "base", ctx.BaseURI);
				AssertEquals("Construct (13)", "doctype", ctx.DocTypeName);
				AssertEquals("Construct (14)", Encoding.UTF8, ctx.Encoding);
				AssertEquals("Construct (15)", "internal", ctx.InternalSubset);
				AssertEquals("Construct (16)", nt, ctx.NameTable);
				AssertEquals("Construct (17)", null, ctx.NamespaceManager);
				AssertEquals("Construct (18)", "pubid", ctx.PublicId);
				AssertEquals("Construct (19)", "sysid", ctx.SystemId);
				AssertEquals("Construct (20)", "lang", ctx.XmlLang);
				AssertEquals("Construct (21)", XmlSpace.Preserve, ctx.XmlSpace);
			}
Exemple #27
0
 // perform the Amazon search with REST and return results as a DataTable
 public static DataTable GetAmazonDataWithRest()
 {
     // The response data table
     DataTable responseTable = GetResponseTable();
     // Compose the Amazon REST request URL
     string amazonRequest = string.Format("{0}&SubscriptionId={1}&Operation=ItemSearch&Keywords={2}&SearchIndex={3}&ResponseGroup={4}", BalloonShopConfiguration.AmazonRestUrl, BalloonShopConfiguration.SubscriptionId, BalloonShopConfiguration.SearchKeywords, BalloonShopConfiguration.SearchIndex, BalloonShopConfiguration.ResponseGroups);
     // If any problems occur, we prefer to send back empty result set
     // instead of throwing exception
     try
     {
       // Load the Amazon response
       XmlDocument responseXmlDoc = new XmlDocument();
       responseXmlDoc.Load(amazonRequest);
       // Prepare XML document for searching
       XmlNamespaceManager xnm = new XmlNamespaceManager
     (responseXmlDoc.NameTable);
       xnm.AddNamespace("amz", "http://webservices.amazon.com/AWSECommerceService/2005-10-05");
       // Get the list of Item nodes
       XmlNodeList itemNodes = responseXmlDoc.SelectNodes("/amz:ItemSearchResponse/amz:Items/amz:Item", xnm);
       // Copy node data to the DataTable
       foreach (XmlNode itemNode in itemNodes)
       {
     try
     {
       // Create a new datarow and populate it with data
       DataRow dataRow = responseTable.NewRow();
       dataRow["ASIN"] = itemNode["ASIN"].InnerText;
       dataRow["ProductName"] = itemNode["ItemAttributes"]["Title"].InnerText;
       dataRow["ProductImageUrl"] = itemNode["SmallImage"]["URL"].InnerText;
       dataRow["ProductPrice"] = itemNode["OfferSummary"]
     ["LowestNewPrice"]["FormattedPrice"].InnerText;
       // Add the row to the results table
       responseTable.Rows.Add(dataRow);
     }
     catch
     {
       // Ignore products with incomplete information
     }
       }
     }
     catch
     {
       // Ignore all possible errors
     }
     return responseTable;
 }
Exemple #28
0
    //gets the weather from yahoo and parses it for wind speed. if wind speed is greater than ten will display message to get engineering
    public void getWeather()
    {
        XmlDocument myXmlDocument = new XmlDocument();
        myXmlDocument.Load("http://weather.yahooapis.com/forecastrss?w=21125");

        XmlNamespaceManager ns = new XmlNamespaceManager(myXmlDocument.NameTable);
        ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");

        XmlNode node = myXmlDocument.SelectSingleNode("/rss/channel/yweather:wind", ns);

        string windSpeed = node.Attributes.GetNamedItem("speed").Value;
        int windSpeedInt = Convert.ToInt16(windSpeed);

        if (windSpeedInt > 10)
        {
            lblWindSpeed.Text = windSpeed;
            pnlWeather.Visible = true;
        }
    }
    private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        string slnFileContent;
        string utGuid;
        string slnGuid;
        string currentDir = Directory.GetCurrentDirectory ();
        string slnPath = Path.Combine (currentDir, SOLUTION_FILENAME);
        string utFullPath = Path.Combine (UNIT_TEST_PRJ_PATH, UNIT_TEST_PRJ_FILENAME);

        try {

            // check if project is already in the sln
            slnFileContent = File.ReadAllText (slnPath);
            Regex prjRegex = new Regex (UNIT_TEST_PRJ_FILENAME);
            if (prjRegex.IsMatch (slnFileContent))
                return;

            // get unit test project guid
            XmlDocument unitTestPrj = new XmlDocument ();
            unitTestPrj.LoadXml (File.ReadAllText (Path.Combine (currentDir, utFullPath)));
            XmlNamespaceManager nsmgr = new XmlNamespaceManager (unitTestPrj.NameTable);
            nsmgr.AddNamespace ("ms", MSBUILD_SCHEMA);
            utGuid = unitTestPrj.SelectSingleNode ("//ms:ProjectGuid", nsmgr).InnerText;

            // get slnGuid
            Regex slnGuidRegex = new Regex ("Project[(]\"(.*)\"[)]");
            var m = slnGuidRegex.Match (slnFileContent);
            slnGuid = m.Groups [1].ToString ();

            // inject project
            int idx = slnFileContent.IndexOf ("Global");
            slnFileContent = slnFileContent.Insert (idx, string.Format (PRJ_TEMPLATE, slnGuid, UNIT_TEST_PRJ_NAME, utFullPath, utGuid));

            // inject build config
            idx = slnFileContent.IndexOf (BUILD_CONFIG_LINE) + BUILD_CONFIG_LINE.Length;
            slnFileContent = slnFileContent.Insert (idx, string.Format (BUILD_CONFIG_TEMPLATE, utGuid));

            File.WriteAllText (slnPath, slnFileContent);

        } catch (Exception ex) {
            UnityEngine.Debug.LogErrorFormat ("UnitTestSolutionPostProcessor: {0}\n{1}", ex.Message, ex.StackTrace);
        }
    }
Exemple #30
0
        internal Validator(XmlNameTable nameTable, SchemaNames schemaNames, XmlValidatingReader reader) {
            this.nameTable = nameTable;
            this.schemaNames = schemaNames;
            this.reader = reader;
            positionInfo = PositionInfo.GetPositionInfo(reader);
            nsManager = reader.NamespaceManager;
            if (nsManager == null) {
                nsManager = new XmlNamespaceManager(nameTable);
                isProcessContents = true;
            }
            SchemaInfo = new SchemaInfo(schemaNames);

            validationStack = new HWStack(STACK_INCREMENT);
            textValue = new StringBuilder();
            this.name = XmlQualifiedName.Empty;
            attPresence = new Hashtable();
            context = null;
            attnDef = null;
        }
Exemple #31
0
        protected override void EventServerEvent(EventServerUpnp obj, EventArgsEvent e)
        {
            if (e.SubscriptionId != SubscriptionId)
            {
                // This event is for a different subscription than the current. This can happen as follows:
                //
                // 1. Events A & B are received and queued up in the event server
                // 2. Event A is processed and is out of sequence - an unsubscribe/resubscribe is triggered
                // 3. By the time B is processed, the unsubscribe/resubscribe has completed and the SID is now different
                //
                // The upshot is that this event is ignored
                return;
            }

            lock (iLock)
            {
                if (e.SequenceNo != iExpectedSequenceNumber)
                {
                    // An out of sequence event is being processed - log, resubscribe and discard
                    UserLog.WriteLine("EventServerEvent(ServiceExakt): " + SubscriptionId + " Out of sequence event received. Expected " + iExpectedSequenceNumber + " got " + e.SequenceNo);

                    // resubscribing means that the initial event will be resent
                    iExpectedSequenceNumber = 0;

                    Unsubscribe();
                    Subscribe();
                    return;
                }
                else
                {
                    iExpectedSequenceNumber++;
                }
            }

            XmlNode variable;

            XmlNamespaceManager nsmanager = new XmlNamespaceManager(e.Xml.NameTable);

            nsmanager.AddNamespace("e", kNamespaceUpnpService);

            bool eventDeviceList = false;

            variable = e.Xml.SelectSingleNode(kBasePropertyPath + "DeviceList", nsmanager);

            if (variable != null)
            {
                string value = "";

                XmlNode child = variable.FirstChild;

                if (child != null)
                {
                    value = child.Value;
                }

                DeviceList = value;

                eventDeviceList = true;
            }

            bool eventConnectionStatus = false;

            variable = e.Xml.SelectSingleNode(kBasePropertyPath + "ConnectionStatus", nsmanager);

            if (variable != null)
            {
                string value = "";

                XmlNode child = variable.FirstChild;

                if (child != null)
                {
                    value = child.Value;
                }

                ConnectionStatus = value;

                eventConnectionStatus = true;
            }

            bool eventVersion = false;

            variable = e.Xml.SelectSingleNode(kBasePropertyPath + "Version", nsmanager);

            if (variable != null)
            {
                string value = "";

                XmlNode child = variable.FirstChild;

                if (child != null)
                {
                    value = child.Value;
                }

                Version = value;

                eventVersion = true;
            }



            if (eventDeviceList)
            {
                if (EventStateDeviceList != null)
                {
                    try
                    {
                        EventStateDeviceList(this, EventArgs.Empty);
                    }
                    catch (Exception ex)
                    {
                        UserLog.WriteLine("Exception caught in EventStateDeviceList: " + ex);
                        Assert.CheckDebug(false);
                    }
                }
            }

            if (eventConnectionStatus)
            {
                if (EventStateConnectionStatus != null)
                {
                    try
                    {
                        EventStateConnectionStatus(this, EventArgs.Empty);
                    }
                    catch (Exception ex)
                    {
                        UserLog.WriteLine("Exception caught in EventStateConnectionStatus: " + ex);
                        Assert.CheckDebug(false);
                    }
                }
            }

            if (eventVersion)
            {
                if (EventStateVersion != null)
                {
                    try
                    {
                        EventStateVersion(this, EventArgs.Empty);
                    }
                    catch (Exception ex)
                    {
                        UserLog.WriteLine("Exception caught in EventStateVersion: " + ex);
                        Assert.CheckDebug(false);
                    }
                }
            }

            if (EventState != null)
            {
                EventState(this, EventArgs.Empty);
            }

            EventHandler <EventArgs> eventInitial = null;

            lock (iLock)
            {
                if (!iInitialEventReceived && e.SequenceNo == 0)
                {
                    iInitialEventReceived = true;
                    eventInitial          = iEventInitial;
                }
            }

            if (eventInitial != null)
            {
                eventInitial(this, EventArgs.Empty);
            }
        }
Exemple #32
0
        public async Task <SatIpTunerHostInfo> GetInfo(string url, CancellationToken cancellationToken)
        {
            Uri    locationUri      = new Uri(url);
            string devicetype       = "";
            string friendlyname     = "";
            string uniquedevicename = "";
            string manufacturer     = "";
            string manufacturerurl  = "";
            string modelname        = "";
            string modeldescription = "";
            string modelnumber      = "";
            string modelurl         = "";
            string serialnumber     = "";
            string presentationurl  = "";
            //string capabilities = "";
            string     m3u      = "";
            var        document = XDocument.Load(locationUri.AbsoluteUri);
            var        xnm      = new XmlNamespaceManager(new NameTable());
            XNamespace n1       = "urn:ses-com:satip";
            XNamespace n0       = "urn:schemas-upnp-org:device-1-0";

            xnm.AddNamespace("root", n0.NamespaceName);
            xnm.AddNamespace("satip:", n1.NamespaceName);
            if (document.Root != null)
            {
                var deviceElement = document.Root.Element(n0 + "device");
                if (deviceElement != null)
                {
                    var devicetypeElement = deviceElement.Element(n0 + "deviceType");
                    if (devicetypeElement != null)
                    {
                        devicetype = devicetypeElement.Value;
                    }
                    var friendlynameElement = deviceElement.Element(n0 + "friendlyName");
                    if (friendlynameElement != null)
                    {
                        friendlyname = friendlynameElement.Value;
                    }
                    var manufactureElement = deviceElement.Element(n0 + "manufacturer");
                    if (manufactureElement != null)
                    {
                        manufacturer = manufactureElement.Value;
                    }
                    var manufactureurlElement = deviceElement.Element(n0 + "manufacturerURL");
                    if (manufactureurlElement != null)
                    {
                        manufacturerurl = manufactureurlElement.Value;
                    }
                    var modeldescriptionElement = deviceElement.Element(n0 + "modelDescription");
                    if (modeldescriptionElement != null)
                    {
                        modeldescription = modeldescriptionElement.Value;
                    }
                    var modelnameElement = deviceElement.Element(n0 + "modelName");
                    if (modelnameElement != null)
                    {
                        modelname = modelnameElement.Value;
                    }
                    var modelnumberElement = deviceElement.Element(n0 + "modelNumber");
                    if (modelnumberElement != null)
                    {
                        modelnumber = modelnumberElement.Value;
                    }
                    var modelurlElement = deviceElement.Element(n0 + "modelURL");
                    if (modelurlElement != null)
                    {
                        modelurl = modelurlElement.Value;
                    }
                    var serialnumberElement = deviceElement.Element(n0 + "serialNumber");
                    if (serialnumberElement != null)
                    {
                        serialnumber = serialnumberElement.Value;
                    }
                    var uniquedevicenameElement = deviceElement.Element(n0 + "UDN");
                    if (uniquedevicenameElement != null)
                    {
                        uniquedevicename = uniquedevicenameElement.Value;
                    }
                    var presentationUrlElement = deviceElement.Element(n0 + "presentationURL");
                    if (presentationUrlElement != null)
                    {
                        presentationurl = presentationUrlElement.Value;
                    }
                    var capabilitiesElement = deviceElement.Element(n1 + "X_SATIPCAP");
                    if (capabilitiesElement != null)
                    {
                        //_capabilities = capabilitiesElement.Value;
                        if (capabilitiesElement.Value.Contains(','))
                        {
                            string[] capabilities = capabilitiesElement.Value.Split(',');
                            foreach (var capability in capabilities)
                            {
                                ReadCapability(capability);
                            }
                        }
                        else
                        {
                            ReadCapability(capabilitiesElement.Value);
                        }
                    }
                    else
                    {
                        _supportsDVBS   = true;
                        _tunerCountDVBS = 1;
                    }
                    var m3uElement = deviceElement.Element(n1 + "X_SATIPM3U");
                    if (m3uElement != null)
                    {
                        m3u = m3uElement.Value;
                    }
                }
            }

            var result = new SatIpTunerHostInfo
            {
                Url             = url,
                Id              = uniquedevicename,
                IsEnabled       = true,
                Type            = SatIpHost.DeviceType,
                Tuners          = _tunerCountDVBS,
                TunersAvailable = _tunerCountDVBS,
                M3UUrl          = m3u
            };

            result.FriendlyName = friendlyname;
            if (string.IsNullOrWhiteSpace(result.Id))
            {
                throw new NotImplementedException();
            }

            else if (!result.M3UUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                var fullM3uUrl = url.Substring(0, url.LastIndexOf('/'));
                result.M3UUrl = fullM3uUrl + "/" + result.M3UUrl.TrimStart('/');
            }

            _logger.Debug("SAT device result: {0}", _json.SerializeToString(result));

            return(result);
        }
Exemple #33
0
        /// <summary>
        /// プロパティを読み込みます
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="propertiesTable"></param>
        /// <returns>取得したプロパティ一覧</returns>
        public Dictionary <string, string> ReadProperties(ClsFilePropertyList list, string fileType, string str_exception)  // 20171011 修正(ファイル読込時のエラー理由を保存)
        {
            Dictionary <string, string> retTable = new Dictionary <string, string>();

            System.IO.FileInfo fi = new System.IO.FileInfo(list.filePath);
            if (fi.Length == 0)
            {
                // ファイルサイズがゼロの場合プロパティが存在しないのでエラー
                // 20171011 追加 (読取専用、ファイ存在しない以外のエラー)
                //error_reason = ListForm.LIST_VIEW_NA;
                return(retTable);
            }

            SpreadsheetDocument    excel = null;
            WordprocessingDocument word  = null;
            PresentationDocument   ppt   = null;

            CoreFilePropertiesPart coreFileProperties;

            // 20171011 修正(xlsxとdocxのみファイルを開いている状態でファイルアクセスするとエラーになる為の回避対応)
            try
            {
                // ファイルのプロパティ領域を開く
                switch (fileType)
                {
                case "Excel":     // エクセルの場合
                    excel = SpreadsheetDocument.Open(list.filePath, false);
                    coreFileProperties = excel.CoreFilePropertiesPart;
                    break;

                case "Word":     // ワードの場合
                    word = WordprocessingDocument.Open(list.filePath, false);
                    coreFileProperties = word.CoreFilePropertiesPart;
                    break;

                case "PowerPoint":     // パワポの場合
                    ppt = PresentationDocument.Open(list.filePath, false);
                    coreFileProperties = ppt.CoreFilePropertiesPart;
                    break;

                default:
                    // 異常なファイル
                    // 20171228 追加(エラー理由保存)
                    //error_reason = ListForm.LIST_VIEW_NA;
                    return(retTable);
                }
                NameTable           nt        = new NameTable();
                XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
                nsManager.AddNamespace(PropertiesKeyList.STR_TAG_CP, PropertiesSchemaList.CorePropertiesSchema);
                nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DC, PropertiesSchemaList.DcPropertiesSchema);
                nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DCTRMS, PropertiesSchemaList.DctermsPropertiesSchema);
                nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DCMITYPE, PropertiesSchemaList.DcmitypePropertiesSchema);
                nsManager.AddNamespace(PropertiesKeyList.STR_TAG_XSI, PropertiesSchemaList.XsiPropertiesSchema);

                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(coreFileProperties.GetStream());

                // プロパティのキーリストを作成
                List <string> propertieslist = PropertiesKeyList.getPropertiesKeyList();

                // 全キーリストを見て存在するデータを取得
                foreach (string key in propertieslist)
                {
                    // 書き込み先のキーワードを指定
                    string searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", key);
                    // 書き込み先を検索
                    XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager);

                    if (xNode != null)
                    {
                        // 読み込む
                        retTable.Add(key, xNode.InnerText);
                    }
                }

                // ファイルのプロパティ領域を閉じる
                if (excel != null)
                {
                    excel.Close();
                }
                if (word != null)
                {
                    word.Close();
                }
                if (ppt != null)
                {
                    ppt.Close();
                }

                // プロパティ取得
                string[] propertyData = null;
                if (retTable.ContainsKey(PropertiesKeyList.STR_KEYWORDS) != false)
                {
                    propertyData = retTable[PropertiesKeyList.STR_KEYWORDS].Split(';');
                }

                if (propertyData != null)
                {
                    list.fileSecrecy = propertyData[0].TrimEnd();

                    // 機密区分が登録されているか判定
                    if (!string.IsNullOrEmpty(list.fileSecrecy))
                    {
                        // 登録あり
                        if (propertyData.Count() >= 1)
                        {
                            list.fileClassification = propertyData[1].TrimEnd();
                        }
                        if (propertyData.Count() >= 2)
                        {
                            list.fileOfficeCode = propertyData[2].TrimEnd();
                        }

                        // 他事務所ファイル判定
                        if (Globals.ThisAddIn.clsCommonSettings.strOfficeCode != list.fileOfficeCode.Trim())
                        {
                            // 他事務所ファイルの場合、登録なし扱にする
                            list.fileSecrecy = "";
                        }
                    }
                }
                else
                {
                    list.fileSecrecy = "Notting";
                }
            }
#if false
            #region HyperLink修復

            // ■ ADD TSE Kitada
            // HyperLinkが破損している場合に、そのリンクを書き直して正常にOPEN出来るようにする。
            // 但し、ドキュメントの中身を直接書き換える処理のため、見送る。
            catch (OpenXmlPackageException ope)
            {
                if (ope.ToString().Contains("Invalid Hyperlink"))
                {
                    // HyperLinkの破損が原因なので、内部のリンクを修正する
                    using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        UriFixer.FixInvalidUri(fs, brokenUri => FixUri(brokenUri));
                    }

                    if (count >= 1)
                    {
                        // 2回実行してダメだったので終了
                        error_reason = ListForm.LIST_VIEW_NA;
                    }
                    else
                    {
                        // もう一度トライ
                        retTable = ReadProperties(filePath, filetype, ref error_reason, ref str_exception, 1);
                    }
                }

                if (excel != null)
                {
                    excel.Close();
                }
                if (word != null)
                {
                    word.Close();
                }
                if (ppt != null)
                {
                    ppt.Close();
                }
            }
            #endregion
#endif
            catch (Exception e)
            {
                str_exception += "file : " + list.filePath + "\r\n\r\n";
                str_exception += "error : " + e.ToString();
                // xlsxとdocxのみファイルを開いている状態でファイルアクセスした場合
                // ファイルが開かれている場合のエラー
                //error_reason = ListForm.LIST_VIEW_NA;

                if (excel != null)
                {
                    excel.Close();
                }
                if (word != null)
                {
                    word.Close();
                }
                if (ppt != null)
                {
                    ppt.Close();
                }

                return(retTable);
            }
            return(retTable);
        }
Exemple #34
0
        public static CT_Workbook Parse(XmlNode node, XmlNamespaceManager namespaceManager)
        {
            if (node == null)
            {
                return(null);
            }
            CT_Workbook ctObj = new CT_Workbook();

            ctObj.fileRecoveryPr = new List <CT_FileRecoveryPr>();
            foreach (XmlNode childNode in node.ChildNodes)
            {
                if (childNode.LocalName == "fileVersion")
                {
                    ctObj.fileVersion = CT_FileVersion.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "fileSharing")
                {
                    ctObj.fileSharing = CT_FileSharing.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "workbookPr")
                {
                    ctObj.workbookPr = CT_WorkbookPr.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "workbookProtection")
                {
                    ctObj.workbookProtection = CT_WorkbookProtection.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "bookViews")
                {
                    ctObj.bookViews = CT_BookViews.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "sheets")
                {
                    ctObj.sheets = CT_Sheets.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "functionGroups")
                {
                    ctObj.functionGroups = CT_FunctionGroups.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "externalReferences")
                {
                    ctObj.externalReferences = CT_ExternalReferences.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "definedNames")
                {
                    ctObj.definedNames = CT_DefinedNames.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "calcPr")
                {
                    ctObj.calcPr = CT_CalcPr.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "oleSize")
                {
                    ctObj.oleSize = CT_OleSize.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "customWorkbookViews")
                {
                    ctObj.customWorkbookViews = CT_CustomWorkbookViews.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "pivotCaches")
                {
                    ctObj.pivotCaches = CT_PivotCaches.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "smartTagPr")
                {
                    ctObj.smartTagPr = CT_SmartTagPr.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "smartTagTypes")
                {
                    ctObj.smartTagTypes = CT_SmartTagTypes.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "webPublishing")
                {
                    ctObj.webPublishing = CT_WebPublishing.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "webPublishObjects")
                {
                    ctObj.webPublishObjects = CT_WebPublishObjects.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "extLst")
                {
                    ctObj.extLst = CT_ExtensionList.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "fileRecoveryPr")
                {
                    ctObj.fileRecoveryPr.Add(CT_FileRecoveryPr.Parse(childNode, namespaceManager));
                }
            }
            return(ctObj);
        }
Exemple #35
0
        public static object ChangeType(XmlSchemaType xmlType, object value, SequenceType type,
                                        XmlNameTable nameTable, XmlNamespaceManager nsmgr)
        {
            if (type.TypeCode == XmlTypeCode.AnyAtomicType || xmlType.TypeCode == type.TypeCode)
            {
                return(value);
            }
            try
            {
                switch (xmlType.TypeCode)
                {
                case XmlTypeCode.String:
                case XmlTypeCode.UntypedAtomic:
                    switch (type.TypeCode)
                    {
                    case XmlTypeCode.UntypedAtomic:
                        return(new UntypedAtomic(value.ToString()));

                    case XmlTypeCode.String:
                        return(value.ToString());

                    case XmlTypeCode.DateTime:
                        return(DateTimeValue.Parse(value.ToString()));

                    case XmlTypeCode.Date:
                        return(DateValue.Parse(value.ToString()));

                    case XmlTypeCode.Time:
                        return(TimeValue.Parse(value.ToString()));

                    case XmlTypeCode.GYearMonth:
                        return(GYearMonthValue.Parse(value.ToString()));

                    case XmlTypeCode.GYear:
                        return(GYearValue.Parse(value.ToString()));

                    case XmlTypeCode.GMonth:
                        return(GMonthValue.Parse(value.ToString()));

                    case XmlTypeCode.GMonthDay:
                        return(GMonthDayValue.Parse(value.ToString()));

                    case XmlTypeCode.GDay:
                        return(GDayValue.Parse(value.ToString()));

                    case XmlTypeCode.Duration:
                        return(DurationValue.Parse(value.ToString()));

                    case XmlTypeCode.QName:
                        if (xmlType.TypeCode == XmlTypeCode.UntypedAtomic)
                        {
                            throw new XPath2Exception("XPTY0004", Resources.XPTY0004,
                                                      new SequenceType(xmlType, XmlTypeCardinality.One, null), type);
                        }
                        return(QNameValue.Parse(value.ToString(), nsmgr));

                    case XmlTypeCode.Notation:
                        return(NotationValue.Parse(value.ToString(), nsmgr));

                    case XmlTypeCode.AnyUri:
                        return(new AnyUriValue(value.ToString()));

                    default:
                    {
                        string text = value.ToString();
                        object res  = type.SchemaType.Datatype.ParseValue(text, nameTable, nsmgr);
                        switch (type.TypeCode)
                        {
                        case XmlTypeCode.Integer:
                        case XmlTypeCode.PositiveInteger:
                        case XmlTypeCode.NegativeInteger:
                        case XmlTypeCode.NonPositiveInteger:
                        case XmlTypeCode.NonNegativeInteger:
                            return((Integer)Convert.ToDecimal(res));

                        case XmlTypeCode.DayTimeDuration:
                            return(new DayTimeDurationValue((TimeSpan)res));

                        case XmlTypeCode.YearMonthDuration:
                            return(new YearMonthDurationValue((TimeSpan)res));

                        case XmlTypeCode.HexBinary:
                            return(new HexBinaryValue((byte[])res));

                        case XmlTypeCode.Base64Binary:
                            if (text.EndsWith("==") &&
                                (text.Length < 3 || "AQgw".IndexOf(text[text.Length - 3]) == -1))
                            {
                                throw new XPath2Exception("FORG0001", Resources.FORG0001, value);
                            }
                            return(new Base64BinaryValue((byte[])res));

                        case XmlTypeCode.Idref:
                            if (type.SchemaType == SequenceType.XmlSchema.IDREFS)
                            {
                                return(new IDREFSValue((string[])res));
                            }
                            goto default;

                        case XmlTypeCode.NmToken:
                            if (type.SchemaType == SequenceType.XmlSchema.NMTOKENS)
                            {
                                return(new NMTOKENSValue((string[])res));
                            }
                            goto default;

                        case XmlTypeCode.Entity:
                            if (type.SchemaType == SequenceType.XmlSchema.ENTITIES)
                            {
                                return(new ENTITIESValue((string[])res));
                            }
                            goto default;

                        default:
                            return(res);
                        }
                    }
                    }

                case XmlTypeCode.Boolean:
                    switch (type.TypeCode)
                    {
                    case XmlTypeCode.Decimal:
                    case XmlTypeCode.Float:
                    case XmlTypeCode.Double:
                    case XmlTypeCode.Integer:
                    case XmlTypeCode.NonPositiveInteger:
                    case XmlTypeCode.NegativeInteger:
                    case XmlTypeCode.Long:
                    case XmlTypeCode.Int:
                    case XmlTypeCode.Short:
                    case XmlTypeCode.Byte:
                    case XmlTypeCode.NonNegativeInteger:
                    case XmlTypeCode.UnsignedLong:
                    case XmlTypeCode.UnsignedInt:
                    case XmlTypeCode.UnsignedShort:
                    case XmlTypeCode.UnsignedByte:
                    case XmlTypeCode.PositiveInteger:
                        return(ChangeType(value, type.ItemType));

                    case XmlTypeCode.String:
                        return(ToString((bool)value));

                    case XmlTypeCode.UntypedAtomic:
                        return(new UntypedAtomic(ToString((bool)value)));
                    }
                    break;

                case XmlTypeCode.Integer:
                case XmlTypeCode.NonPositiveInteger:
                case XmlTypeCode.NegativeInteger:
                case XmlTypeCode.Long:
                case XmlTypeCode.Int:
                case XmlTypeCode.Short:
                case XmlTypeCode.Byte:
                case XmlTypeCode.NonNegativeInteger:
                case XmlTypeCode.UnsignedLong:
                case XmlTypeCode.UnsignedInt:
                case XmlTypeCode.UnsignedShort:
                case XmlTypeCode.UnsignedByte:
                case XmlTypeCode.PositiveInteger:
                case XmlTypeCode.Decimal:
                case XmlTypeCode.Float:
                case XmlTypeCode.Double:
                    switch (type.TypeCode)
                    {
                    case XmlTypeCode.String:
                        return(ToString(value));

                    case XmlTypeCode.UntypedAtomic:
                        return(new UntypedAtomic(ToString(value)));

                    case XmlTypeCode.Boolean:
                        return(CoreFuncs.BooleanValue(value));

                    case XmlTypeCode.AnyUri:
                        throw new XPath2Exception("XPTY0004", Resources.XPTY0004,
                                                  new SequenceType(xmlType, XmlTypeCardinality.One, null), type);

                    default:
                        return(ChangeType(value, type.ItemType));
                    }

                default:
                {
                    IXmlConvertable convert = value as IXmlConvertable;
                    if (convert != null)
                    {
                        return(convert.ValueAs(type, nsmgr));
                    }
                    if (type.TypeCode == XmlTypeCode.String)
                    {
                        return(ToString(value));
                    }
                    if (type.TypeCode == XmlTypeCode.UntypedAtomic)
                    {
                        return(new UntypedAtomic(ToString(value)));
                    }
                    return(type.SchemaType.Datatype.ChangeType(value, type.ValueType));
                }
                }
            }
            catch (XmlSchemaException ex)
            {
                throw new XPath2Exception(ex.Message, ex);
            }
            catch (InvalidCastException)
            {
                throw new XPath2Exception("XPTY0004", Resources.XPTY0004,
                                          new SequenceType(xmlType, XmlTypeCardinality.One, null), type);
            }
            catch (FormatException)
            {
                throw new XPath2Exception("XPTY0004", Resources.XPTY0004,
                                          new SequenceType(xmlType, XmlTypeCardinality.One, null), type);
            }
            throw new XPath2Exception("XPTY0004", Resources.XPTY0004,
                                      new SequenceType(xmlType, XmlTypeCardinality.One, null), type);
        }
Exemple #36
0
        public static object ValueAs(object value, SequenceType type,
                                     XmlNameTable nameTable, XmlNamespaceManager nsmgr)
        {
            if (value == Undefined.Value)
            {
                return(value);
            }
            if (value == null)
            {
                value = CoreFuncs.False;
            }
            if (type.TypeCode == XmlTypeCode.None)
            {
                throw new XPath2Exception("XPTY0004", Resources.XPTY0004,
                                          new SequenceType(value.GetType(), XmlTypeCardinality.One), "empty-sequence()");
            }
            if (value.GetType() != type.ItemType)
            {
                UntypedAtomic untypedAtomic = value as UntypedAtomic;
                if (untypedAtomic != null)
                {
                    return(ChangeType(SequenceType.XmlSchema.UntypedAtomic, value, type, nameTable, nsmgr));
                }
                switch (type.TypeCode)
                {
                case XmlTypeCode.Double:
                    if (value is Single)
                    {
                        return(Convert.ToDouble((float)value));
                    }
                    if (value is Int32)
                    {
                        return(Convert.ToDouble((int)value));
                    }
                    if (value is Int64)
                    {
                        return(Convert.ToDouble((long)value));
                    }
                    if (value is Decimal)
                    {
                        return(Convert.ToDouble((decimal)value));
                    }
                    if (value is Integer)
                    {
                        return(Convert.ToDouble((decimal)(Integer)value));
                    }
                    if (value is Int16)
                    {
                        return(Convert.ToDouble((short)value));
                    }
                    if (value is SByte)
                    {
                        return(Convert.ToDouble((sbyte)value));
                    }
                    break;

                case XmlTypeCode.Float:
                    if (value is Double)
                    {
                        return(Convert.ToSingle((double)value));
                    }
                    if (value is Int32)
                    {
                        return(Convert.ToSingle((int)value));
                    }
                    if (value is Int64)
                    {
                        return(Convert.ToSingle((long)value));
                    }
                    if (value is Decimal)
                    {
                        return(Convert.ToSingle((decimal)value));
                    }
                    if (value is Integer)
                    {
                        return(Convert.ToSingle((decimal)(Integer)value));
                    }
                    if (value is Int16)
                    {
                        return(Convert.ToSingle((short)value));
                    }
                    if (value is SByte)
                    {
                        return(Convert.ToSingle((sbyte)value));
                    }
                    break;

                case XmlTypeCode.Integer:
                    if (Integer.IsDerivedSubtype(value))
                    {
                        return(Integer.ToInteger(value));
                    }
                    break;

                case XmlTypeCode.Decimal:
                    if (value is Integer)
                    {
                        return((decimal)(Integer)value);
                    }
                    if (Integer.IsDerivedSubtype(value))
                    {
                        return((decimal)Integer.ToInteger(value));
                    }
                    break;

                case XmlTypeCode.Int:
                    if (value is Int16)
                    {
                        return((int)(short)value);
                    }
                    if (value is UInt16)
                    {
                        return((int)(ushort)value);
                    }
                    if (value is SByte)
                    {
                        return((int)(sbyte)value);
                    }
                    if (value is Byte)
                    {
                        return((int)(byte)value);
                    }
                    if (value is Integer)
                    {
                        return((int)(Integer)value);
                    }
                    break;

                case XmlTypeCode.Long:
                    if (value is Int32)
                    {
                        return((long)(int)value);
                    }
                    if (value is Int16)
                    {
                        return((long)(short)value);
                    }
                    if (value is SByte)
                    {
                        return((long)(sbyte)value);
                    }
                    if (value is Integer)
                    {
                        return((long)(Integer)value);
                    }
                    break;
                }
                if (type.TypeCode == XmlTypeCode.AnyUri && value is String)
                {
                    return(new AnyUriValue((string)value));
                }
                if (type.TypeCode == XmlTypeCode.String && value is AnyUriValue)
                {
                    return(value.ToString());
                }
                if (type.TypeCode == XmlTypeCode.Duration &&
                    (value is YearMonthDurationValue || value is DayTimeDurationValue))
                {
                    return(value);
                }
                throw new XPath2Exception("XPTY0004", Resources.XPTY0004,
                                          new SequenceType(value.GetType(), XmlTypeCardinality.One), type);
            }
            return(value);
        }
Exemple #37
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="worksheet">worksheet that owns the validation</param>
 /// <param name="itemElementNode">Xml top node (dataValidations) when importing xml</param>
 /// <param name="validationType">Data validation type</param>
 /// <param name="address">address for data validation</param>
 /// <param name="namespaceManager">Xml Namespace manager</param>
 internal ExcelDataValidation(ExcelWorksheet worksheet, string address, ExcelDataValidationType validationType, XmlNode itemElementNode, XmlNamespaceManager namespaceManager)
     : base(namespaceManager != null ? namespaceManager : worksheet.NameSpaceManager)
 {
     Require.Argument(address).IsNotNullOrEmpty("address");
     address = CheckAndFixRangeAddress(address);
     if (itemElementNode == null)
     {
         //var xmlDoc = worksheet.WorksheetXml;
         TopNode = worksheet.WorksheetXml.SelectSingleNode("//d:dataValidations", worksheet.NameSpaceManager);
         // did not succeed using the XmlHelper methods here... so I'm creating the new node using XmlDocument...
         var nsUri = NameSpaceManager.LookupNamespace("d");
         //itemElementNode = TopNode.OwnerDocument.CreateElement(_itemElementNodeName, nsUri);
         itemElementNode = TopNode.OwnerDocument.CreateElement(_itemElementNodeName.Split(':')[1], nsUri);
         TopNode.AppendChild(itemElementNode);
     }
     TopNode        = itemElementNode;
     ValidationType = validationType;
     Address        = new ExcelAddress(address);
     Init();
 }
Exemple #38
0
        public static object GetTypedValue(this XPathItem item)
        {
            XPathNavigator nav = item as XPathNavigator;

            if (nav == null)
            {
                return(item.TypedValue);
            }
            IXmlSchemaInfo schemaInfo = nav.SchemaInfo;

            if (schemaInfo == null || schemaInfo.SchemaType == null)
            {
                switch (nav.NodeType)
                {
                case XPathNodeType.Comment:
                case XPathNodeType.ProcessingInstruction:
                case XPathNodeType.Namespace:
                    return(nav.Value);

                default:
                    return(new UntypedAtomic(nav.Value));
                }
            }
            XmlTypeCode typeCode = schemaInfo.SchemaType.TypeCode;

            if (typeCode == XmlTypeCode.AnyAtomicType && schemaInfo.MemberType != null)
            {
                typeCode = schemaInfo.MemberType.TypeCode;
            }
            switch (typeCode)
            {
            case XmlTypeCode.UntypedAtomic:
                return(new UntypedAtomic(nav.Value));

            case XmlTypeCode.Integer:
            case XmlTypeCode.PositiveInteger:
            case XmlTypeCode.NegativeInteger:
            case XmlTypeCode.NonPositiveInteger:
                return((Integer)(decimal)nav.TypedValue);

            case XmlTypeCode.Date:
                return(DateValue.Parse(nav.Value));

            case XmlTypeCode.DateTime:
                return(DateTimeValue.Parse(nav.Value));

            case XmlTypeCode.Time:
                return(TimeValue.Parse(nav.Value));

            case XmlTypeCode.Duration:
                return(DurationValue.Parse(nav.Value));

            case XmlTypeCode.DayTimeDuration:
                return(new DayTimeDurationValue((TimeSpan)nav.TypedValue));

            case XmlTypeCode.YearMonthDuration:
                return(new YearMonthDurationValue((TimeSpan)nav.TypedValue));

            case XmlTypeCode.GDay:
                return(GDayValue.Parse(nav.Value));

            case XmlTypeCode.GMonth:
                return(GMonthValue.Parse(nav.Value));

            case XmlTypeCode.GMonthDay:
                return(GMonthDayValue.Parse(nav.Value));

            case XmlTypeCode.GYear:
                return(GYearValue.Parse(nav.Value));

            case XmlTypeCode.GYearMonth:
                return(GYearMonthValue.Parse(nav.Value));

            case XmlTypeCode.QName:
            case XmlTypeCode.Notation:
            {
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);
                ExtFuncs.ScanLocalNamespaces(nsmgr, nav.Clone(), true);
                if (schemaInfo.SchemaType.TypeCode == XmlTypeCode.Notation)
                {
                    return(NotationValue.Parse(nav.Value, nsmgr));
                }
                else
                {
                    return(QNameValue.Parse(nav.Value, nsmgr));
                }
            }

            case XmlTypeCode.AnyUri:
                return(new AnyUriValue(nav.Value));

            case XmlTypeCode.HexBinary:
                return(new HexBinaryValue((byte[])nav.TypedValue));

            case XmlTypeCode.Base64Binary:
                return(new Base64BinaryValue((byte[])nav.TypedValue));

            case XmlTypeCode.Idref:
                if (schemaInfo.SchemaType == SequenceType.XmlSchema.IDREFS)
                {
                    return(new IDREFSValue((string[])nav.TypedValue));
                }
                goto default;

            case XmlTypeCode.NmToken:
                if (schemaInfo.SchemaType == SequenceType.XmlSchema.NMTOKENS)
                {
                    return(new NMTOKENSValue((string[])nav.TypedValue));
                }
                goto default;

            case XmlTypeCode.Entity:
                if (schemaInfo.SchemaType == SequenceType.XmlSchema.ENTITIES)
                {
                    return(new ENTITIESValue((string[])nav.TypedValue));
                }
                goto default;

            default:
                return(nav.TypedValue);
            }
        }
Exemple #39
0
        public void XmlSchemaValidatorDoesNotEnforceIdentityConstraintsOnDefaultAttributesInSomeCases()
        {
            Initialize();
            string xml = @"<?xml version='1.0'?>
<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='idF016.xsd'>
	<uid val='test'/>	<uid/></root>"        ;

            string xsd = @"<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' elementFormDefault='qualified'>
	<xsd:element name='root'>
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref='uid' maxOccurs='unbounded'/>
			</xsd:sequence>
		</xsd:complexType>
		<xsd:unique id='foo123' name='uuid'>
			<xsd:selector xpath='.//uid'/>
			<xsd:field xpath='@val'/>
		</xsd:unique>
	</xsd:element>
	<xsd:element name='uid' nillable='true'>
		<xsd:complexType>
			<xsd:attribute name='val' type='xsd:string' default='test'/>
		</xsd:complexType>
	</xsd:element>
</xsd:schema>";

            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());
            XmlSchemaSet        schemas          = new XmlSchemaSet();

            schemas.Add(null, XmlReader.Create(new StringReader(xsd)));
            schemas.Compile();
            XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints |
                                                       XmlSchemaValidationFlags.AllowXmlAttributes;
            XmlSchemaValidator validator = new XmlSchemaValidator(namespaceManager.NameTable, schemas, namespaceManager, validationFlags);

            validator.Initialize();
            using (XmlReader r = XmlReader.Create(new StringReader(xsd)))
            {
                while (r.Read())
                {
                    switch (r.NodeType)
                    {
                    case XmlNodeType.Element:
                        namespaceManager.PushScope();
                        if (r.MoveToFirstAttribute())
                        {
                            do
                            {
                                if (r.NamespaceURI == "http://www.w3.org/2000/xmlns/")
                                {
                                    namespaceManager.AddNamespace(r.LocalName, r.Value);
                                }
                            } while (r.MoveToNextAttribute());
                            r.MoveToElement();
                        }
                        validator.ValidateElement(r.LocalName, r.NamespaceURI, null, null, null, null, null);
                        if (r.MoveToFirstAttribute())
                        {
                            do
                            {
                                if (r.NamespaceURI != "http://www.w3.org/2000/xmlns/")
                                {
                                    validator.ValidateAttribute(r.LocalName, r.NamespaceURI, r.Value, null);
                                }
                            } while (r.MoveToNextAttribute());
                            r.MoveToElement();
                        }
                        validator.ValidateEndOfAttributes(null);
                        if (r.IsEmptyElement)
                        {
                            goto case XmlNodeType.EndElement;
                        }
                        break;

                    case XmlNodeType.EndElement:
                        validator.ValidateEndElement(null);
                        namespaceManager.PopScope();
                        break;

                    case XmlNodeType.Text:
                        validator.ValidateText(r.Value);
                        break;

                    case XmlNodeType.SignificantWhitespace:
                    case XmlNodeType.Whitespace:
                        validator.ValidateWhitespace(r.Value);
                        break;

                    default:
                        break;
                    }
                }
                validator.EndValidation();
            }
            XmlReaderSettings rs = new XmlReaderSettings();

            rs.ValidationType = ValidationType.Schema;
            rs.Schemas.Add(null, XmlReader.Create(new StringReader(xsd)));

            using (XmlReader r = XmlReader.Create(new StringReader(xml), rs))
            {
                try
                {
                    while (r.Read())
                    {
                        ;
                    }
                }
                catch (XmlSchemaValidationException e) { _output.WriteLine(e.Message); return; }
            }
            Assert.True(false);
        }
Exemple #40
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            _id   = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl);
            _uri  = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl);
            _type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl);

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            // Transforms
            TransformChain = new TransformChain();
            XmlElement transformsElement = value.SelectSingleNode("ds:Transforms", nsm) as XmlElement;

            if (transformsElement != null)
            {
                XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm);
                if (transformNodes != null)
                {
                    foreach (XmlNode transformNode in transformNodes)
                    {
                        XmlElement transformElement = transformNode as XmlElement;
                        string     algorithm        = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
                        Transform  transform        = CryptoHelpers.CreateFromName(algorithm) as Transform;
                        if (transform == null)
                        {
                            throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform);
                        }
                        AddTransform(transform);
                        // let the transform read the children of the transformElement for data
                        transform.LoadInnerXml(transformElement.ChildNodes);
                        // Hack! this is done to get around the lack of here() function support in XPath
                        if (transform is XmlDsigEnvelopedSignatureTransform)
                        {
                            // Walk back to the Signature tag. Find the nearest signature ancestor
                            // Signature-->SignedInfo-->Reference-->Transforms-->Transform
                            XmlNode     signatureTag  = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm);
                            XmlNodeList signatureList = transformElement.SelectNodes("//ds:Signature", nsm);
                            if (signatureList != null)
                            {
                                int position = 0;
                                foreach (XmlNode node in signatureList)
                                {
                                    position++;
                                    if (node == signatureTag)
                                    {
                                        ((XmlDsigEnvelopedSignatureTransform)transform).SignaturePosition = position;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // DigestMethod
            XmlElement digestMethodElement = value.SelectSingleNode("ds:DigestMethod", nsm) as XmlElement;

            if (digestMethodElement == null)
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestMethod");
            }
            _digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);

            // DigestValue
            XmlElement digestValueElement = value.SelectSingleNode("ds:DigestValue", nsm) as XmlElement;

            if (digestValueElement == null)
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestValue");
            }
            _digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText));

            // cache the Xml
            _cachedXml = value;
        }