Esempio n. 1
1
 /// <include file='doc\XmlParserContext.uex' path='docs/doc[@for="XmlParserContext.XmlParserContext3"]/*' />
 public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String docTypeName,
                   String pubId, String sysId, String internalSubset, String baseURI,
                   String xmlLang, XmlSpace xmlSpace, Encoding enc)
 {
     
     if (nsMgr != null) {
         if (nt == null) {
             _nt = nsMgr.NameTable;
         }
         else {
             if ( (object)nt != (object)  nsMgr.NameTable ) {
                 throw new XmlException(Res.Xml_NotSameNametable);
             }
             _nt = nt;
         }
     }
     else {
         _nt = nt;
     }
     
     _nsMgr              = nsMgr;
     _docTypeName        = (null == docTypeName ? String.Empty : docTypeName);
     _pubId              = (null == pubId ? String.Empty : pubId);
     _sysId              = (null == sysId ? String.Empty : sysId);
     _internalSubset     = (null == internalSubset ? String.Empty : internalSubset);
     _baseURI            = (null == baseURI ? String.Empty : baseURI);
     _xmlLang            = (null == xmlLang ? String.Empty : xmlLang);
     _xmlSpace           = xmlSpace;
     _encoding           = enc;
     
 }
Esempio n. 2
1
        public void from(XmlNode node, XmlNamespaceManager xnm, string prefix, string subfix)
        {
            Type type = this.GetType();
            FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

            foreach (FieldInfo field in fields)
            {
                string query = prefix +ObjectUtil.GetSimpleName(field) + subfix;
                try
                {
                    string value = null;
                    XmlNode tempNode;
                    if (xnm != null)
                    {
                        tempNode = node.SelectSingleNode(query, xnm);
                    }
                    else
                    {
                        tempNode = node.SelectSingleNode(query);
                    }
                    if (tempNode == null) {
                        field.SetValue(this,XML_NULL);
                        continue;
                    }
                    value = tempNode.InnerText;
                    field.SetValue(this, value);
                }
                catch (Exception ex) { }
            }
        }
Esempio n. 3
0
 public Feed(IXPathNavigable navigable)
 {
     navigator = navigable.CreateNavigator();
     manager = new XmlNamespaceManager(navigator.NameTable);
     manager.AddNamespace("f", "http://hl7.org/fhir");
     manager.AddNamespace("atom", "http://www.w3.org/2005/Atom");
 }
Esempio n. 4
0
        /// <summary>
        /// Parses source file names from a project file.
        /// </summary>
        /// <param name="projectFile">Project file name.</param>
        /// <returns>A list of source code filenames</returns>
        public virtual ReadOnlyCollection<string> Parse(string projectFile)
        {
            if (projectFile == null)
            {
                throw new ArgumentNullException("projectFile");
            }

            string projectPath = Path.GetDirectoryName(projectFile);
            List<string> sourceFiles = new List<string>();

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(projectFile);

            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
            namespaceManager.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003");

            XmlNodeList nodes = xmlDocument.SelectNodes("//ns:Compile", namespaceManager);
            foreach (XmlNode node in nodes)
            {
                XmlAttribute includeAttribute = node.Attributes["Include"];
                if (includeAttribute != null)
                {
                    if (node.SelectSingleNode("ns:Link", namespaceManager) == null)
                    {
                        string fileName = includeAttribute.Value;

                        string sourceFilePath = Path.Combine(projectPath, fileName);
                        sourceFiles.Add(sourceFilePath);
                    }
                }
            }

            return sourceFiles.AsReadOnly();
        }
        protected void TelemetryInitializerInstall(string sourceDocument, params string[] telemetryInitializerTypes)
        {
            string resourceName = "Microsoft.ApplicationInsights.Resources.ApplicationInsights.config.install.xdt";
            Stream stream = typeof(ModuleTransformTests).Assembly.GetManifestResourceStream(resourceName);
            using (StreamReader reader = new StreamReader(stream))
            {
                string transform = reader.ReadToEnd();
                XmlTransformation transformation = new XmlTransformation(transform, false, null);

                XmlDocument targetDocument = new XmlDocument();
                targetDocument.LoadXml(sourceDocument);
                transformation.Apply(targetDocument);

                XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
                manager.AddNamespace("ai", AppInsightsNamespace);
                int moduleIndex = 0;
                foreach (XPathNavigator module in targetDocument.CreateNavigator().Select("/ai:ApplicationInsights/ai:TelemetryInitializers/ai:Add/@Type", manager))
                {
                    string contextInitializerType = telemetryInitializerTypes[moduleIndex++];
                    Assert.Equal(module.Value, contextInitializerType);
                }

                Assert.Equal(moduleIndex, telemetryInitializerTypes.Length);
            }
        }
        public override bool Execute()
        {
            try {
                var document = new XmlDocument();
                document.Load(this.XmlFileName);

                var navigator = document.CreateNavigator();
                var nsResolver = new XmlNamespaceManager(navigator.NameTable);

                if (!string.IsNullOrEmpty(this.Prefix) && !string.IsNullOrEmpty(this.Namespace)) {
                    nsResolver.AddNamespace(this.Prefix, this.Namespace);
                }

                var expr = XPathExpression.Compile(this.XPath, nsResolver);

                var iterator = navigator.Select(expr);
                while (iterator.MoveNext()) {
                    iterator.Current.DeleteSelf();
                }

                using (var writer = new XmlTextWriter(this.XmlFileName, Encoding.UTF8)) {
                    writer.Formatting = Formatting.Indented;
                    document.Save(writer);
                    writer.Close();
                }
            }
            catch (Exception exception) {
                base.Log.LogErrorFromException(exception);
                return false;
            }
            base.Log.LogMessage("Updated file '{0}'", new object[] { this.XmlFileName });
            return true;
        }
Esempio n. 7
0
        public static PrintTicket ModifyPrintTicket(PrintTicket ticket, string featureName, string newValue)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException("ticket");
            }

            var xmlDoc = new XmlDocument();
            xmlDoc.Load(ticket.GetXmlStream());

            var manager = new XmlNamespaceManager(xmlDoc.NameTable);
            manager.AddNamespace(xmlDoc.DocumentElement.Prefix, xmlDoc.DocumentElement.NamespaceURI);

            var xpath = string.Format("//psf:Feature[contains(@name, 'InputBin')]/psf:Option", featureName);
            var node = xmlDoc.SelectSingleNode(xpath, manager);
            if (node != null)
            {
                node.Attributes["name"].Value = newValue;
            }

            var printTicketStream = new MemoryStream();
            xmlDoc.Save(printTicketStream);
            printTicketStream.Position = 0;
            var modifiedPrintTicket = new PrintTicket(printTicketStream);
            return modifiedPrintTicket;
        }
        public static TestResults InterpretTestResults(XmlDocument doc)
        {
            TestResults results = new TestResults();
            XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);
            nsm.AddNamespace("n", "http://microsoft.com/schemas/VisualStudio/TeamTest/2010");

            results.Outcome = doc.SelectSingleNode("n:TestRun/n:ResultSummary", nsm).Attributes["outcome"].Value;
            results.CountExecuted = int.Parse(doc.SelectSingleNode("n:TestRun/n:ResultSummary/n:Counters", nsm).Attributes["executed"].Value);
            results.CountPassed = int.Parse(doc.SelectSingleNode("n:TestRun/n:ResultSummary/n:Counters", nsm).Attributes["passed"].Value);
            results.CountFailed = int.Parse(doc.SelectSingleNode("n:TestRun/n:ResultSummary/n:Counters", nsm).Attributes["failed"].Value);

            XmlNodeList testresults = doc.SelectNodes("n:TestRun/n:Results/n:UnitTestResult[@outcome='Failed']", nsm);
            string names = string.Empty;
            foreach (XmlNode testresult in testresults)
            {
                string message = testresult.Attributes["testName"].Value;
                XmlNode xmlErrorInfoNode = testresult.SelectSingleNode("n:Output/n:ErrorInfo/n:Message", nsm);
                if (xmlErrorInfoNode != null)
                {
                    message += ": " + xmlErrorInfoNode.InnerText;
                    results.ResultCode = ExitCode.Failure;
                }

                results.FailingTests.Add(message);
            }

            return results;
        }
        public void QueryAndNamespace()
        {
            try
            {
                var output = "";
                var path = Server.MapPath("~/App_Data/bookstore.xml");
                XPathDocument document = new XPathDocument(path);
                XPathNavigator navigator = document.CreateNavigator();
                XPathExpression query = navigator.Compile("/bookstore:bookstore/bookstore:book");
                XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
                manager.AddNamespace("bookstore", "urn:newbooks-schema");
                query.SetContext(manager);
                XPathNodeIterator nodes = navigator.Select(query);

                while (nodes.MoveNext())
                {
                    output += nodes.Current.OuterXml;
                }

                Textarea4.InnerHtml = output;
            }
            catch (Exception ex)
            {
                Textarea4.InnerHtml = ex.Message;
            }
        }
Esempio n. 10
0
        public bool CancelAppointment(HackExchangeContext context, CalendarItem appointment)
        {
            var url = context.Endpoint;
            var request = new HttpRequestMessage(HttpMethod.Post, url);
            var postBodyTemplate = LoadXml("CancelAppointment");
            var postBody = string.Format(postBodyTemplate, appointment.Id, appointment.ChangeKey);
            request.Content = new StringContent(postBody, Encoding.UTF8, "text/xml");

            var clientHandler = new HttpClientHandler()
            {
                Credentials = context.Credentials
            };
            using (var client = new HttpClient(clientHandler))
            {
                var response = client.SendAsync(request).Result;
                var responseBody = response.Content.ReadAsStringAsync().Result;

                var doc = new XPathDocument(new StringReader(responseBody));
                var nav = doc.CreateNavigator();
                var nsManager = new XmlNamespaceManager(nav.NameTable);
                nsManager.AddNamespace("m", "http://schemas.microsoft.com/exchange/services/2006/messages");
                nsManager.AddNamespace("t", "http://schemas.microsoft.com/exchange/services/2006/types");

                var responseClass = EvaluateXPath(nav, nsManager, "//m:DeleteItemResponseMessage/@ResponseClass");
                return responseClass == "Success";
            }
        }
 public void Initialize(XmlDocument basedata, XmlNamespaceManager namespaces, RDFTriple rdftriple)
 {
     BaseData = basedata;
     Namespaces = namespaces;
     RDFTriple = rdftriple;
     UploadInfoToORCID1.Initialize(basedata, namespaces, rdftriple);
 }
        public string GetValue(XElement element, XmlNamespaceManager nsm)
        {
            XPathContext context = new XPathContext((NameTable)nsm.NameTable);
            XPathNavigator navigator = element.CreateNavigator();
            object result = null;

            foreach (var ns in nsm.GetNamespacesInScope(XmlNamespaceScope.All))
                context.AddNamespace(ns.Key, ns.Value);

            context.Arguments.AddParam(XPathContext.ParameterNames.CurrentNode, string.Empty, navigator.Select("."));
            result = navigator.Evaluate(this.RawValue, context);

            if (result is string)
                return (string)result;
            else if (result is XPathNodeIterator)
            {
                var iterator = ((XPathNodeIterator)result);
                var current = (XPathNavigator)((IEnumerable)iterator).Cast<object>().First();

                return current.Value;
            }
            else if (result is XAttribute)
                return ((XAttribute)result).Value;
            else if (result is XElement)
                return ((XElement)result).Value;

            return string.Empty;
        }
Esempio n. 13
0
        static void Main( string[] args )
        {
            if ( args.Length != 1 )
            {
                return;
            }
            string fileName = args[ 0 ];
            StringBuilder fileContent = new StringBuilder( System.IO.File.ReadAllText( fileName ) );

            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml( fileContent.ToString() );

            System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager( xdoc.NameTable );
            xmlnsManager.AddNamespace( "gpx", "http://www.topografix.com/GPX/1/0" );

            XmlNodeList timeNodes = xdoc.SelectNodes( "//gpx:time", xmlnsManager );
            foreach ( XmlNode timeNode in timeNodes )
            {
                string[] split1 = timeNode.InnerText.Split( 'T' );
                string[] splitDays = split1[ 0 ].Split( '-' );
                string[] splitHours = split1[ 1 ].Replace( "Z", "" ).Split( ':' );

                fileContent.Replace( timeNode.InnerText, new DateTime( int.Parse( splitDays[ 0 ] ), int.Parse( splitDays[ 1 ] ), int.Parse( splitDays[ 2 ] ),
                    int.Parse( splitHours[ 0 ] ), int.Parse( splitHours[ 1 ] ), int.Parse( splitHours[ 2 ] ) ).ToUniversalTime().ToString( "s" ) + "Z" );
            }

            System.IO.File.WriteAllText( fileName.Replace( ".gpx", "-fix.gpx" ), fileContent.ToString() );
        }
Esempio n. 14
0
    SelectRequiredSingleNode
    (
        XmlNode node,
        String xPath,
        XmlNamespaceManager xmlNamespaceManager
    )
    {
        Debug.Assert(node != null);
        Debug.Assert( !String.IsNullOrEmpty(xPath) );

        XmlNode oSelectedNode;

        if ( !TrySelectSingleNode(node, xPath, xmlNamespaceManager,
            out oSelectedNode) )
        {
            throw new XmlException( String.Format(

                "An XML node with the name \"{0}\" is missing a required"
                + " descendent node.  The XPath is \"{1}\"."
                ,
                node.Name,
                xPath
                ) );
        }

        return (oSelectedNode);
    }
Esempio n. 15
0
        public override bool IsMine(List<string> lines, string fileName)
        {
            var sb = new StringBuilder();
            lines.ForEach(line => sb.AppendLine(line));
            string xmlAsString = sb.ToString().Trim();

            if (xmlAsString.Contains("xmlns:tts=\"http://www.w3.org/2006/04"))
                return false;

            if (xmlAsString.Contains("http://www.w3.org/") &&
                xmlAsString.Contains("/ttaf1"))
            {
                var xml = new XmlDocument();
                try
                {
                    xml.LoadXml(xmlAsString);

                    var nsmgr = new XmlNamespaceManager(xml.NameTable);
                    nsmgr.AddNamespace("ttaf1", xml.DocumentElement.NamespaceURI);
                    XmlNode div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).SelectSingleNode("ttaf1:div", nsmgr);
                    if (div == null)
                        div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).FirstChild;
                    int numberOfParagraphs = div.ChildNodes.Count;
                    return numberOfParagraphs > 0;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    return false;
                }
            }
            return false;
        }
        /// <summary>
        /// Initialisiert eine Verwaltung.
        /// </summary>
        /// <param name="path">Der volle Pfad zur Projektdatei.</param>
        protected ProjectTypeHandler( FileInfo path = null )
        {
            // Remember
            FilePath = path;

            // Attach to the table
            Namespaces = new XmlNamespaceManager( Document.NameTable );

            // Create the default name space
            Namespaces.AddNamespace( "msbuild", "http://schemas.microsoft.com/developer/msbuild/2003" );

            // None
            if (path == null)
            {
                // Fake name
                AssemblyName = Guid.NewGuid().ToString( "N" ).ToUpper();

                // Done
                return;
            }

            // Load
            Document.Load( FilePath.FullName );

            // Read the name of the target
            var assemblyName = Document.SelectSingleNode( TargetNamePath, Namespaces );
            if (assemblyName != null)
                AssemblyName = assemblyName.InnerText;

            // Validate
            if (string.IsNullOrEmpty( AssemblyName ))
                AssemblyName = Path.GetFileNameWithoutExtension( path.FullName );
        }
Esempio n. 17
0
        private void CreateReport(IDictionary idc, string rptStyle)
        {
            var sp1 = new SpreadsheetClass();

            var doc = new XmlDocument();
            doc.LoadXml(rptStyle);
            var xn = new XmlNamespaceManager(doc.NameTable);
            xn.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");
            var nodes = doc.SelectNodes("//ss:Data", xn);

            //根据key替换数据
            foreach (XmlNode node in nodes)
            {
                var tmpValue = node.InnerText.Trim();
                if (tmpValue.Length > 2 && tmpValue.Substring(0, 1) == "♂")
                {
                    string val = tmpValue.Substring(1);
                    node.InnerText = idc.Contains(val) ? idc[val].ToString() : string.Empty;
                    rptStyle = rptStyle.Replace(tmpValue, node.InnerText);
                }
            }

            //sp1.XMLData = style;

            sp1.XMLData = doc.OuterXml;
            //dvShow.InnerHtml = sp1.HTMLData;

            sp1.XMLData = sp1.XMLData.ToString().Replace("<ss:Table", "<ss:Table ss:id=\"CX\"");

            Response.Write(sp1.HTMLData);
        }
Esempio n. 18
0
 public MainMenu(XmlDocument pagedata, List<ModuleParams> moduleparams, XmlNamespaceManager pagenamespaces)
     : base(pagedata, moduleparams, pagenamespaces)
 {
     menulist = new System.Text.StringBuilder();
     sm = new SessionManagement();
     ActiveNetworkRelationshipTypes.ClassURI = "";
 }
Esempio n. 19
0
        public XmlValidationRule(IXmlDocumentProvider docProvider, XmlNode node, XmlNamespaceManager nsmgr)
        {
            if (node.Attributes["name"] != null)
                Name = node.Attributes["name"].Value;
            if (node.Attributes["file"] != null)
                File = node.Attributes["file"].Value;

            if (!string.IsNullOrEmpty(File))
            {
                try
                {
                    XmlDocument doc = docProvider.Load(File);
                    if (doc != null)
                    {
                        List<ITest> tests = new List<ITest>();

                        string prefix = nsmgr.LookupPrefix("http://icalvalid.wikidot.com/validation");
                        foreach (XmlNode passNode in doc.SelectNodes("/" + prefix + ":rule/" + prefix + ":pass", nsmgr))
                            tests.Add(new XmlCalendarTest(passNode, nsmgr));
                        foreach (XmlNode failNode in doc.SelectNodes("/" + prefix + ":rule/" + prefix + ":fail", nsmgr))
                            tests.Add(new XmlCalendarTest(failNode, nsmgr));

                        Tests = tests.ToArray();
                    }
                    else throw new ValidationRuleLoadException("The file could not be found at the following path: '" + File + "'.", this);
                }
                catch (ValidationRuleLoadException) { throw; }
                catch
                {
                    throw new ValidationRuleLoadException(this);
                }
            }
        }
Esempio n. 20
0
 public static CT_Border Parse(XmlNode node, XmlNamespaceManager namespaceManager)
 {
     if (node == null)
         return null;
     CT_Border ctObj = new CT_Border();
     ctObj.diagonalUp = XmlHelper.ReadBool(node.Attributes["diagonalUp"]);
     ctObj.diagonalDown = XmlHelper.ReadBool(node.Attributes["diagonalDown"]);
     ctObj.outline = XmlHelper.ReadBool(node.Attributes["outline"]);
     foreach (XmlNode childNode in node.ChildNodes)
     {
         if (childNode.LocalName == "left")
             ctObj.left = CT_BorderPr.Parse(childNode, namespaceManager);
         else if (childNode.LocalName == "right")
             ctObj.right = CT_BorderPr.Parse(childNode, namespaceManager);
         else if (childNode.LocalName == "top")
             ctObj.top = CT_BorderPr.Parse(childNode, namespaceManager);
         else if (childNode.LocalName == "bottom")
             ctObj.bottom = CT_BorderPr.Parse(childNode, namespaceManager);
         else if (childNode.LocalName == "diagonal")
             ctObj.diagonal = CT_BorderPr.Parse(childNode, namespaceManager);
         else if (childNode.LocalName == "vertical")
             ctObj.vertical = CT_BorderPr.Parse(childNode, namespaceManager);
         else if (childNode.LocalName == "horizontal")
             ctObj.horizontal = CT_BorderPr.Parse(childNode, namespaceManager);
     }
     return ctObj;
 }
 public ResinConf(String file)
 {
   _xPathDoc = new XPathDocument(file);
   _docNavigator = _xPathDoc.CreateNavigator();
   _xmlnsMgr = new XmlNamespaceManager(_docNavigator.NameTable);
   _xmlnsMgr.AddNamespace("caucho", "http://caucho.com/ns/resin");
 }
Esempio n. 22
0
        /// <summary>
        /// Copys the same nodes under a parent node from one document to a second
        /// </summary>
        /// <param name="oDocDonor">Xml Doc to copy the nodes from</param>
        /// <param name="oDocReceiver">Xml Doc to copy the nodes to</param>
        /// <param name="xPath">Generic namespaces are automatically applied. use ns: as namespace for each node.</param>
        /// <returns></returns>
        private static int CopyNodes(XmlDocument oDocReceiver, XmlDocument oDocDonor,  string xPath)
        {
            var namespaceManagerReceiver = new XmlNamespaceManager(oDocReceiver.NameTable);
            namespaceManagerReceiver.AddNamespace("ns", oDocReceiver.DocumentElement.NamespaceURI);
            var namespaceManagerDonor = new XmlNamespaceManager(oDocDonor.NameTable);
            namespaceManagerDonor.AddNamespace("ns", oDocDonor.DocumentElement.NamespaceURI);

            var testDefinitionNode = oDocDonor.SelectSingleNode(xPath, namespaceManagerDonor);
            if (testDefinitionNode == null)
            {
                throw new InvalidDataException("Donor document misses node for xpath " + xPath);
            }
            var testDefinitionNodeReceiver = oDocReceiver.SelectSingleNode(xPath, namespaceManagerReceiver);
            if (testDefinitionNodeReceiver == null)
            {
                throw new InvalidDataException("Receiver document misses node for xpath " + xPath);
            }

            int copied = 0;
            foreach (XmlNode node in testDefinitionNode.ChildNodes)
            {
                XmlNode newChildNode = oDocReceiver.ImportNode(node, true);
                testDefinitionNodeReceiver.AppendChild(newChildNode);
                copied++;
            }
            return copied;
        }
Esempio n. 23
0
 /// <include file='doc\XmlParserContext.uex' path='docs/doc[@for="XmlParserContext.XmlParserContext1"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String docTypeName,
           String pubId, String sysId, String internalSubset, String baseURI,
           String xmlLang, XmlSpace xmlSpace) 
 : this(nt, nsMgr, docTypeName, pubId, sysId, internalSubset, baseURI, xmlLang, xmlSpace, null)
 {
     // Intentionally Empty
 }
			public TestEnvironment()
			{
				_palasoFileNames = Directory.GetFiles(GlobalWritingSystemRepositoryMigrator.PalasoLdmlPathPre0);
				_flexFileNames = Directory.GetFiles(GlobalWritingSystemRepositoryMigrator.FlexLdmlPathPre0);
				NamespaceManager = new XmlNamespaceManager(new NameTable());
				NamespaceManager.AddNamespace("palaso", "urn://palaso.org/ldmlExtensions/v1");
			}
        public bool Load(XPathNavigator source, XmlNamespaceManager manager)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(source, "source");

            //------------------------------------------------------------
            //	Attempt to extract syndication information
            //------------------------------------------------------------
            ResourceName = source.LocalName;
            Namespace = source.NamespaceURI;

            string value;
            Key = source.TryGetAttribute("key", Framework.Common.SData.Namespace, out value) ? value : null;
            Uri = source.TryGetAttribute("uri", Framework.Common.SData.Namespace, out value) && !string.IsNullOrEmpty(value) ? new Uri(value) : null;
            Uuid = source.TryGetAttribute("uuid", Framework.Common.SData.Namespace, out value) && !string.IsNullOrEmpty(value) ? new Guid(value) : (Guid?) null;
            Descriptor = source.TryGetAttribute("descriptor", Framework.Common.SData.Namespace, out value) ? value : null;
            Lookup = source.TryGetAttribute("lookup", Framework.Common.SData.Namespace, out value) ? value : null;
            IsDeleted = source.TryGetAttribute("isDeleted", Framework.Common.SData.Namespace, out value) && !string.IsNullOrEmpty(value) ? XmlConvert.ToBoolean(value) : (bool?) null;

            return source.SelectChildren(XPathNodeType.Element)
                .Cast<XPathNavigator>()
                .GroupBy(item => item.LocalName)
                .All(group => LoadItem(group.Key, group, manager));
        }
Esempio n. 26
0
        public static bool IsProject40(string projectXml)
        {
            bool result = false;
            double targetFrameworkVersion;
            XmlDocument projectDocument = new XmlDocument();
            
            projectDocument.LoadXml(projectXml);
            
            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(projectDocument.NameTable);
            namespaceManager.AddNamespace("msbd", projectDocument.DocumentElement.NamespaceURI); 
            
            XmlNodeList nodes = projectDocument.SelectNodes("//msbd:PropertyGroup//msbd:TargetFrameworkVersion", namespaceManager);
            
            Debug.Assert(nodes != null, "TargetFrameworkVersion node not foud (null).");
            Debug.Assert(nodes.Count > 0, "TargetFrameworkVersion node not foud (count = 0).");

            // Parse <TargetFrameworkVersion>v4.0<TargetFrameworkVersion/>
            if(double.TryParse(nodes[0].InnerText.Remove(0, 1),
                               out targetFrameworkVersion) && targetFrameworkVersion >= 4)
            {
                result = true;
            }
            
            return result;
        }
Esempio n. 27
0
        private static void PatchSystemFolder_Add(string typeName, params string[] additionalContentTypeNames)
        {
            var ct = ContentType.GetByName(typeName);
            var xml = new XmlDocument();
            var nsmgr = new XmlNamespaceManager(xml.NameTable);
            nsmgr.AddNamespace("x", ContentType.ContentDefinitionXmlNamespace);
            xml.Load(ct.Binary.GetStream());
            var list = new List<string>();
            var element = (XmlElement)xml.DocumentElement.SelectSingleNode("x:AllowedChildTypes", nsmgr);
            if (element == null)
            {
                var fieldsElement = (XmlElement)xml.DocumentElement.SelectSingleNode("x:Fields", nsmgr);
                //if (fieldsElement == null)
                //{
                //}
                element = xml.CreateElement("", "AllowedChildTypes", ContentType.ContentDefinitionXmlNamespace);
                xml.DocumentElement.InsertBefore(element, fieldsElement);
            }
            else
            {
                list.AddRange(element.InnerXml.Split(" \t\r\n,;".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries).Select(x=>x.Trim()));
            }

            if (additionalContentTypeNames != null && additionalContentTypeNames.Length > 0)
                list.AddRange(additionalContentTypeNames);
            element.InnerText = string.Join(" ", list);

            ContentTypeInstaller.InstallContentType(xml.OuterXml);
        }
Esempio n. 28
0
 /// <summary>
 /// Evaluates the given expression and returns the typed result.
 /// </summary>
 public static object Evaluate(string expression, XPathNavigator source,
     XmlNamespaceManager context, params XPathVariable[] variables)
 {
     XPathExpression expr = GetCompiledExpression(expression, source);
     expr.SetContext(PrepareContext(source, context, null, variables));
     return source.Evaluate(expr);
 }
Esempio n. 29
0
 /// <summary>
 /// Evaluates the given expression and returns the typed result.
 /// </summary>
 public static object Evaluate(string expression, XPathNavigator source,
     XmlNamespaceManager context)
 {
     XPathExpression expr = GetCompiledExpression(expression, source);
     expr.SetContext(context);
     return source.Evaluate(expr);
 }
        public async Task<List<Link>> GetReutersTechRss()
        {
            var list = new List<Link>();
            var data = await fetchUrl("http://feeds.reuters.com/reuters/technologyNews?format=xml");

            if (data != null)
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(data);
                var ns = new XmlNamespaceManager(xmlDoc.NameTable);
                ns.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
                ns.AddNamespace("taxo", "http://purl.org/rss/1.0/modules/taxonomy/");
                ns.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
                ns.AddNamespace("itunes", "http://www.itunes.com/dtds/podcast-1.0.dtd");
                ns.AddNamespace("feedburner", "http://rssnamespace.org/feedburner/ext/1.0");

                XmlNodeList urlList;

                urlList = xmlDoc.SelectNodes("//item", ns);

                foreach(XmlNode node in urlList)
                {
                    var myNode = node;
                    list.Add(new Link()
                    {
                        Title = node["title"].InnerText,
                        Url = node["link"].InnerText,
                        Description = node["description"].InnerText
                    });
                }
            }

            return list;
        }
Esempio n. 31
0
        /// <summary>
        /// Write this document's schema mappings from the given XML document
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="mgr">The namespace manager.</param>
        protected override void ReadSchemaMappings(System.Xml.XmlNode node, System.Xml.XmlNamespaceManager mgr)
        {
            foreach (XmlNode map in node.ChildNodes)
            {
                if (map.Name != "SchemaMapping") //NOXLATE
                {
                    continue;
                }

                var prv = map.Attributes["provider"]; //NOXLATE
                if (prv == null)
                {
                    throw new Exception(string.Format(Strings.ErrorBadDocumentExpectedAttribute, "provider"));
                }

                var sn = map.Attributes["name"];
                if (sn == null)
                {
                    throw new Exception(string.Format(Strings.ErrorBadDocumentExpectedAttribute, "name"));
                }

                foreach (XmlNode clsMap in map.ChildNodes)
                {
                    if (clsMap.Name != "complexType") //NOXLATE
                    {
                        continue;
                    }

                    var cn = clsMap.Attributes["name"]; //NOXLATE
                    if (cn == null)
                    {
                        throw new Exception(string.Format(Strings.ErrorBadDocumentExpectedAttribute, "name"));
                    }

                    var rdf = clsMap.FirstChild;
                    if (rdf == null || rdf.Name != "RasterDefinition")
                    {
                        throw new Exception(string.Format(Strings.ErrorBadDocumentExpectedElement, "RasterDefinition"));
                    }

                    RasterWmsItem item = new RasterWmsItem();
                    item.SchemaName = sn.Value;
                    item.ReadXml(rdf, mgr);

                    this.AddRasterItem(item);
                }
            }
        }
Esempio n. 32
0
        List <PointLatLng> GetRoutePoints(string url)
        {
            List <PointLatLng> points = null;

            try
            {
                string route = GetContentUsingHttp(url);

                if (!string.IsNullOrEmpty(route))
                {
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.LoadXml(route);
                    System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmldoc.NameTable);
                    xmlnsManager.AddNamespace("sm", "http://earth.google.com/kml/2.0");

                    ///Folder/Placemark/LineString/coordinates
                    var coordNode = xmldoc.SelectSingleNode("/sm:kml/sm:Document/sm:Folder/sm:Placemark/sm:LineString/sm:coordinates", xmlnsManager);

                    string[] coordinates = coordNode.InnerText.Split('\n');

                    if (coordinates.Length > 0)
                    {
                        points = new List <PointLatLng>();

                        foreach (string coordinate in coordinates)
                        {
                            if (coordinate != string.Empty)
                            {
                                string[] XY = coordinate.Split(',');
                                if (XY.Length == 2)
                                {
                                    double lat = double.Parse(XY[1], CultureInfo.InvariantCulture);
                                    double lng = double.Parse(XY[0], CultureInfo.InvariantCulture);
                                    points.Add(new PointLatLng(lat, lng));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetRoutePoints: " + ex);
            }

            return(points);
        }
Esempio n. 33
0
        /// <summary>
        /// Constructs a schema from the contents of an XML specification.
        /// </summary>
        /// <param name="fileContents">The contents of a file that specifies the schema in XML.</param>
        public DataModelSchema(string fileContents)
        {
            // Initialize the object
            this.itemList     = new List <ObjectSchema>();
            this.relationList = new SortedList <string, RelationSchema>();
            this.tableList    = new SortedList <string, TableSchema>();

            // Compile the schema to resolve all the types and qualified names.
            XmlSchemaSet  xmlSchemaSet  = new XmlSchemaSet();
            XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(fileContents));
            XmlSchema     primarySchema = XmlSchema.Read(xmlTextReader, new ValidationEventHandler(ValidationCallback));

            xmlSchemaSet.Add(primarySchema);
            xmlSchemaSet.Compile();

            // The namespace Teraque.DataModelGenerator is used to create qualified names from the XPath specifications.  These are most useful in
            // following the key schemas back to the relevant table schemas.
            this.xmlNamespaceManager = new XmlNamespaceManager(new NameTable());
            foreach (XmlSchema xmlSchema in xmlSchemaSet.Schemas())
            {
                foreach (XmlQualifiedName xmlQualifiedName in xmlSchema.Namespaces.ToArray())
                {
                    this.xmlNamespaceManager.AddNamespace(xmlQualifiedName.Name, xmlQualifiedName.Namespace);
                }
            }

            // Initialize the data structures from primary schema in the set.
            foreach (XmlSchema xmlSchema in xmlSchemaSet.Schemas(primarySchema.TargetNamespace))
            {
                this.name            = xmlSchema.Id;
                this.targetNamespace = xmlSchema.TargetNamespace;
                this.version         = Convert.ToDecimal(xmlSchema.Version);
                foreach (XmlSchemaObject xmlSchemaObject in xmlSchema.Items)
                {
                    if (xmlSchemaObject is XmlSchemaAnnotation)
                    {
                        this.itemList.Add(new AnnotationSchema(this, xmlSchemaObject as XmlSchemaAnnotation));
                    }
                }
            }

            // The schema is parsed in two passes.  The first evaluates the tables, keys and unique constraints.  The second
            // evaluates the foreign keys and associates them with the parent and child tables.
            FirstPass(xmlSchemaSet);
            SecondPass(xmlSchemaSet);
        }
Esempio n. 34
0
        private int FillFilesFromResult(XmlDocument oResult, ref List <OracleUCMFile> files)
        {
            int searchRow = -1;

            try
            {
                int startRow, endRow, totalRows;

                // Setup Namespace manager
                System.Xml.XmlNamespaceManager oNSMgr = new System.Xml.XmlNamespaceManager(oResult.NameTable);
                //Add the namespaces used in Fusion Opportunity to the XmlNamespaceManager.
                oNSMgr.AddNamespace("env", "http://schemas.xmlsoap.org/soap/envelope/");
                oNSMgr.AddNamespace("ns2", "http://www.oracle.com/UCM");


                startRow  = GetIntFromNode(oResult.SelectSingleNode("//ns2:Field[@name='StartRow']", oNSMgr));
                endRow    = GetIntFromNode(oResult.SelectSingleNode("//ns2:Field[@name='EndRow']", oNSMgr));
                totalRows = GetIntFromNode(oResult.SelectSingleNode("//ns2:Field[@name='TotalRows']", oNSMgr));
                if (endRow < totalRows)
                {
                    searchRow = endRow + 1;
                }

                System.Xml.XmlNode oResp = oResult.SelectSingleNode("//ns2:ResultSet[@name='SearchResults']", oNSMgr);
                if (oResp != null)
                {
                    foreach (XmlNode xnRow in oResp.ChildNodes)
                    {
                        OracleUCMFile tfile = new OracleUCMFile();
                        tfile.dID           = GetIntFromNode(xnRow.SelectSingleNode("./ns2:Field[@name='dID']", oNSMgr));
                        tfile.dCreateDate   = GetDateFromNode(xnRow.SelectSingleNode("./ns2:Field[@name='dCreateDate']", oNSMgr));
                        tfile.dDocTitle     = xnRow.SelectSingleNode("./ns2:Field[@name='dDocTitle']", oNSMgr).InnerText;
                        tfile.dDocType      = xnRow.SelectSingleNode("./ns2:Field[@name='dDocType']", oNSMgr).InnerText;
                        tfile.dOriginalName = xnRow.SelectSingleNode("./ns2:Field[@name='dOriginalName']", oNSMgr).InnerText;
                        tfile.VaultFileSize = GetIntFromNode(xnRow.SelectSingleNode("./ns2:Field[@name='VaultFileSize']", oNSMgr));
                        tfile.dFormat       = xnRow.SelectSingleNode("./ns2:Field[@name='dFormat']", oNSMgr).InnerText;
                        files.Add(tfile);
                    }
                }
            }
            catch (Exception ex)
            {
                searchRow = -1; LastErrorMessage = String.Format("Exception during FillFilesFromResult: {0}", ex.Message);
            }
            return(searchRow);
        }
Esempio n. 35
0
        /// <summary>
        /// Set the current element's content from the current XML node
        /// </summary>
        /// <param name="node"></param>
        /// <param name="mgr"></param>
        public void ReadXml(System.Xml.XmlNode node, System.Xml.XmlNamespaceManager mgr)
        {
            if (!node.Name.Equals("xs:schema")) //NOXLATE
            {
                throw new Exception(string.Format(Strings.ErrorBadDocumentExpectedElement, "xs:schema"));
            }

            //Description
            var docNode = node.SelectSingleNode("xs:annotation/xs:documentation", mgr); //NOXLATE

            if (docNode != null)
            {
                this.Description = docNode.InnerText;
            }

            var tns = node.Attributes["targetNamespace"];

            if (tns == null)
            {
                throw new Exception(string.Format(Strings.ErrorBadDocumentExpectedAttribute, "targetNamespace"));
            }

            int lidx = tns.Value.LastIndexOf("/") + 1; //NOXLATE

            this.Name = tns.Value.Substring(lidx);

            //TODO: Description

            //Now handle classes
            if (node.ChildNodes.Count > 0)
            {
                XmlNodeList clsNodes = node.SelectNodes("xs:complexType", mgr); //NOXLATE
                foreach (XmlNode clsNode in clsNodes)
                {
                    var nn = clsNode.Attributes["name"]; //NOXLATE
                    if (nn == null)
                    {
                        throw new Exception(string.Format(Strings.ErrorBadDocumentExpectedAttribute, "name"));            //NOXLATE
                    }
                    string          name = Utility.DecodeFDOName(nn.Value.Substring(0, nn.Value.Length - "Type".Length)); //NOXLATE
                    ClassDefinition cls  = new ClassDefinition(name, string.Empty);                                       //TODO: Description
                    ((IFdoSerializable)cls).ReadXml(clsNode, mgr);
                    this.AddClass(cls);
                }
            }
        }
 public static System.Xml.XmlNamespaceManager GenericNamespace(XmlNameTable NameTable)
 {
     try
     {
         System.Xml.XmlNamespaceManager tmp = new System.Xml.XmlNamespaceManager(NameTable);
         tmp.AddNamespace("message", message);
         tmp.AddNamespace("common", common);
         tmp.AddNamespace("generic", generic);
         tmp.AddNamespace("xsi", xsi);
         tmp.AddNamespace("schemaLocation", schemaLocation);
         return(tmp);
     }
     catch (Exception ex)
     {
         throw new Exception("Error, [Common.CommonNameSpace.GenericNamespace] " + ex.Message);
     }
 }
Esempio n. 37
0
        private async void LoadResources(string version)
        {
            resources = null;
            var themeResourcesXaml = File.ReadAllText((await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Resources/{version}/themeresources.xaml"))).Path);
            var genericXaml        = File.ReadAllText((await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Resources/{version}/generic.xaml"))).Path);
            var themeresources     = Windows.UI.Xaml.Markup.XamlReader.Load(themeResourcesXaml) as ResourceDictionary;
            var generic            = Windows.UI.Xaml.Markup.XamlReader.Load(genericXaml) as ResourceDictionary;
            var themes             = themeresources.ThemeDictionaries.ToArray();
            var dics               = themeresources.MergedDictionaries.ToArray();
            var byType             = themeresources.GroupBy(g => g.Value.GetType()).ToArray();
            List <DataModel> items = new List <DataModel>();
            XmlDocument      doc   = new XmlDocument();

            doc.LoadXml(themeResourcesXaml);
            System.Xml.XmlNamespaceManager manager = new System.Xml.XmlNamespaceManager(new NameTable());
            manager.AddNamespace("d", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
            manager.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
            var root = doc.DocumentElement;
            List <ResourceDictionaryModel> themeModels = new List <ResourceDictionaryModel>();

            foreach (var theme in themeresources.ThemeDictionaries)
            {
                var themeModel = new ResourceDictionaryModel {
                    Key = theme.Key as string
                };
                var     themeName   = theme.Key;
                XmlNode nodeList    = root.SelectSingleNode($"/d:ResourceDictionary/d:ResourceDictionary.ThemeDictionaries/d:ResourceDictionary[@x:Key='{themeName}']", manager);
                var     value       = theme.Value as ResourceDictionary;
                var     themeByType = value.GroupBy(g => g.Value.GetType()).ToArray();
                themeModel.Resources = value.Select(t => new DataModel(t, nodeList.ChildNodes.OfType <XmlNode>().Where(node => node.Attributes["x:Key"].Value == t.Key as string).FirstOrDefault())).OrderBy(t => t.Key).ToList();
                themeModels.Add(themeModel);
            }
            Themes.SelectedIndex = -1;
            resources            = themeresources.Select(t => new DataModel(t, root.ChildNodes.OfType <XmlNode>().Where(node => node.Attributes["x:Key"]?.Value == t.Key as string).FirstOrDefault())).OrderBy(t => t.Key).ToList();

            Themes.ItemsSource = themeModels;
            if (themeModels.Count > 0)
            {
                Themes.SelectedIndex = 0;
            }
            else
            {
                UpdateDataView();
            }
        }
 public static System.Xml.XmlNamespaceManager RegistryNamespace(XmlNameTable NameTable)
 {
     try
     {
         System.Xml.XmlNamespaceManager tmp = new System.Xml.XmlNamespaceManager(NameTable);
         tmp.AddNamespace("message", message);
         tmp.AddNamespace("common", common);
         tmp.AddNamespace("registry", registry);
         tmp.AddNamespace("structure", structure);
         tmp.AddNamespace("xsi", xsi);
         tmp.AddNamespace("schemaLocation", schemaLocation);
         return(tmp);
     }
     catch (Exception ex)
     {
         throw new Exception("Error, [Common.CommonNameSpace.RegistryNamespace] " + ex.Message);
     }
 }
Esempio n. 39
0
        /// <summary>
        /// 对 本结点(xNode) 的 Namespace 注册
        /// </summary>
        /// <param name="xNode">含有或继承有命名空间的结点</param>
        /// <param name="xNameSpaceManager">命名空间管理器</param>
        /// <returns>返回该 Namespace 的 prefix</returns>
        public static string AutoPrefix(System.Xml.XmlNode xNode, System.Xml.XmlNamespaceManager xNameSpaceManager)
        {
            string xPrefix;

            if (xNode.NamespaceURI == string.Empty)
            {
                return(string.Empty);
            }
            else
            {
                xPrefix = xNameSpaceManager.LookupPrefix(xNode.NamespaceURI);
                if (xPrefix == null || xPrefix == string.Empty)
                {
                    xPrefix = "x" + xNode.GetHashCode().ToString();
                    xNameSpaceManager.AddNamespace(xPrefix, xNode.NamespaceURI);
                }
                return(xPrefix + (xPrefix.Length > 0 ? ":" : ""));
            }
        }
Esempio n. 40
0
        /// <summary>
        /// Get a vaule from complet xml document
        /// </summary>
        /// <param name="doc">Loaded xml document</param>
        /// <param name="nodeName">Path of node</param>
        /// <param name="xmlnsManager">namespace manager</param>
        /// <returns>value of path</returns>
        public static string GetFromXML(XmlDocument doc, string nodeName, System.Xml.XmlNamespaceManager xmlnsManager = null, bool text = true)
        {
            string  temp = string.Empty;
            XmlNode node = null;

            if (xmlnsManager != null)
            {
                node = doc.SelectSingleNode(nodeName, xmlnsManager);
            }
            else
            {
                node = doc.SelectSingleNode(nodeName);
            }

            if (node != null)
            {
                temp = text ? node.InnerText : node.InnerXml;
            }

            return(HTMLAgilityUtils.removeNRT(temp));
        }
Esempio n. 41
0
        private void SendNotify(string sid, string url)
        {
            try {
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method      = "NOTIFY";
                webRequest.ContentType = "text/xml; charset=\"utf-8\"";
                webRequest.Headers.Add("NT", "upnp:event");
                webRequest.Headers.Add("NTS", "upnp:propchange");
                webRequest.Headers.Add("SID", "uuid:" + sid);
                webRequest.Headers.Add("SEQ", String.Format("{0}", ++subseq));

                var doc = new XmlDocument();
                doc.LoadXml(Properties.Resources.notify);
                System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("e", "urn:schemas-upnp-org:event-1-0");
                var xProperty = doc.SelectSingleNode("//e:property", nsmgr);

                var xElement = doc.CreateElement("SystemUpdateID");
                xElement.InnerText = systemID.ToString();
                xProperty.AppendChild(xElement);

                byte[] requestBytes = new System.Text.UTF8Encoding().GetBytes(doc.OuterXml);

                using (var reqstream = webRequest.GetRequestStream())
                {
                    reqstream.Write(requestBytes, 0, requestBytes.Length);
                }

                using (var res = webRequest.GetResponse())
                {
                }
            } catch (System.Net.WebException e)
            {
                //subscribers.Remove(sid);
                Error(string.Format("SendNotify failed {0} {1}", sid, url), e);
            } catch (Exception exn)
            {
                Error("SendNotify failed" + exn.Message, exn);
            }
        }
 private string ReadXMLValue(
     System.Xml.XmlNode node,
     string path,
     System.Xml.XmlNamespaceManager nsm)
 {
     System.Xml.XmlNode node2 = node.SelectSingleNode(path, nsm);
     if (node2 == null)
     {
         return(null);
     }
     else
     {
         if (node2 is System.Xml.XmlElement)
         {
             return(((System.Xml.XmlElement)node2).InnerText);
         }
         else
         {
             return(node2.Value);
         }
     }
 }
Esempio n. 43
0
        public static MapInfoDocument Parse(XDocument xmldoc, System.Xml.XmlNamespaceManager NameSpaceManager)
        {
            MapInfoDocument doc = new MapInfoDocument();

            doc.map     = new CT_MapInfo();
            doc.map.Map = new System.Collections.Generic.List <CT_Map>();
            foreach (XElement mapNode in xmldoc.XPathSelectElements("d:MapInfo/d:Map", NameSpaceManager))
            {
                CT_Map ctMap = new CT_Map();
                ctMap.ID          = XmlHelper.ReadUInt(mapNode.GetAttributeNode("ID"));
                ctMap.Name        = XmlHelper.ReadString(mapNode.GetAttributeNode("Name"));
                ctMap.RootElement = XmlHelper.ReadString(mapNode.GetAttributeNode("RootElement"));
                ctMap.SchemaID    = XmlHelper.ReadString(mapNode.GetAttributeNode("SchemaID"));
                ctMap.ShowImportExportValidationErrors = XmlHelper.ReadBool(mapNode.GetAttributeNode("ShowImportExportValidationErrors"));
                ctMap.PreserveFormat       = XmlHelper.ReadBool(mapNode.GetAttributeNode("PreserveFormat"));
                ctMap.PreserveSortAFLayout = XmlHelper.ReadBool(mapNode.GetAttributeNode("PreserveSortAFLayout"));
                ctMap.Append  = XmlHelper.ReadBool(mapNode.GetAttributeNode("Append"));
                ctMap.AutoFit = XmlHelper.ReadBool(mapNode.GetAttributeNode("AutoFit"));
                doc.map.Map.Add(ctMap);
            }
            doc.map.Schema = new System.Collections.Generic.List <CT_Schema>();
            foreach (XElement schemaNode in xmldoc.XPathSelectElements("d:MapInfo/d:Schema", NameSpaceManager))
            {
                CT_Schema ctSchema = new CT_Schema();
                ctSchema.ID = schemaNode.AttributeValue("ID");
                if (schemaNode.Attribute("Namespace") != null)
                {
                    ctSchema.Namespace = schemaNode.AttributeValue("Namespace");
                }
                if (schemaNode.Attribute("SchemaRef") != null)
                {
                    ctSchema.Namespace = schemaNode.AttributeValue("SchemaRef");
                }
                ctSchema.InnerXml = schemaNode.InnerXml();
                doc.map.Schema.Add(ctSchema);
            }
            return(doc);
        }
        protected virtual XmlNamespaceManager GetNamespaceManager(IPDFComponent owner)
        {
            System.Xml.NameTable           nt               = new System.Xml.NameTable();
            System.Xml.XmlNamespaceManager mgr              = new System.Xml.XmlNamespaceManager(nt);
            IPDFRemoteComponent            parsed           = this.GetParsedParent(owner);
            IDictionary <string, string>   parsedNamespaces = null;

            //add the namespaces of the last parsed document so we can infer any declarations
            if (null != parsed)
            {
                parsedNamespaces = parsed.GetDeclaredNamespaces();
                if (null != parsedNamespaces)
                {
                    foreach (string prefix in parsedNamespaces.Keys)
                    {
                        mgr.AddNamespace(prefix, parsedNamespaces[prefix]);
                    }
                }
            }


            return(mgr);
        }
Esempio n. 45
0
        /// <summary>
        /// Load the SSAS namespaces into a XmlNameSpaceManager.  These are used for XPath
        /// queries into a SSAS file
        /// </summary>
        /// <param name="document">XML Document to load namespaces for</param>
        /// <returns>XmlNamespaceManager loaded with SSAS namespaces</returns>
        private static XmlNamespaceManager LoadSsasNamespaces(XmlDocument document)
        {
            XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(document.NameTable);

            //xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlnsManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
            //xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlnsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            //xmlns:ddl2="http://schemas.microsoft.com/analysisservices/2003/engine/2"
            xmlnsManager.AddNamespace("ddl2", "http://schemas.microsoft.com/analysisservices/2003/engine/2");
            //xmlns:ddl2_2="http://schemas.microsoft.com/analysisservices/2003/engine/2/2"
            xmlnsManager.AddNamespace("ddl2_2", "http://schemas.microsoft.com/analysisservices/2003/engine/2/2");
            //xmlns:ddl100_100="http://schemas.microsoft.com/analysisservices/2008/engine/100/100"
            xmlnsManager.AddNamespace("ddl100_100", "http://schemas.microsoft.com/analysisservices/2008/engine/100/100");
            //xmlns:dwd="http://schemas.microsoft.com/DataWarehouse/Designer/1.0"
            xmlnsManager.AddNamespace("dwd", "http://schemas.microsoft.com/DataWarehouse/Designer/1.0");
            //xmlns="http://schemas.microsoft.com/analysisservices/2003/engine"
            xmlnsManager.AddNamespace("AS", "http://schemas.microsoft.com/analysisservices/2003/engine");
            xmlnsManager.AddNamespace("msprop", "urn:schemas-microsoft-com:xml-msprop");
            xmlnsManager.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
            xmlnsManager.AddNamespace("msdata", "urn:schemas-microsoft-com:xml-msdata");

            return(xmlnsManager);
        }
Esempio n. 46
0
        DirectionsStatusCode GetDirectionsUrl(string url, out GDirections direction)
        {
            DirectionsStatusCode ret = DirectionsStatusCode.UNKNOWN_ERROR;

            direction = null;

            try
            {
                string route = GMaps.Instance.UseRouteCache ? Cache.Instance.GetContent(url, CacheType.DirectionsCache) : string.Empty;
                if (string.IsNullOrEmpty(route))
                {
                    route = GetContentUsingHttp(url);
                    if (!string.IsNullOrEmpty(route))
                    {
                        if (GMaps.Instance.UseRouteCache)
                        {
                            Cache.Instance.SaveContent(url, CacheType.DirectionsCache, route);
                        }
                    }
                }

                #region -- gpx response --
                //<?xml version="1.0" encoding="UTF-8"?>
                //<gpx creator="" version="1.1" xmlns="http://www.topografix.com/GPX/1/1"
                //    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                //    xsi:schemaLocation="http://www.topografix.com/GPX/1/1 gpx.xsd ">
                //    <extensions>
                //        <distance>293</distance>
                //        <time>34</time>
                //        <start>Perckhoevelaan</start>
                //        <end>Goudenregenlaan</end>
                //    </extensions>
                //    <wpt lat="51.17702" lon="4.39630" />
                //    <wpt lat="51.17656" lon="4.39655" />
                //    <wpt lat="51.17639" lon="4.39670" />
                //    <wpt lat="51.17612" lon="4.39696" />
                //    <wpt lat="51.17640" lon="4.39767" />
                //    <wpt lat="51.17668" lon="4.39828" />
                //    <wpt lat="51.17628" lon="4.39874" />
                //    <wpt lat="51.17618" lon="4.39888" />
                //    <rte>
                //        <rtept lat="51.17702" lon="4.39630">
                //            <desc>Head south on Perckhoevelaan, 0.1 km</desc>
                //            <extensions>
                //                <distance>111</distance>
                //                <time>13</time>
                //                <offset>0</offset>
                //                <distance-text>0.1 km</distance-text>
                //                <direction>S</direction>
                //                <azimuth>160.6</azimuth>
                //            </extensions>
                //        </rtept>
                //        <rtept lat="51.17612" lon="4.39696">
                //            <desc>Turn left at Laarstraat, 0.1 km</desc>
                //            <extensions>
                //                <distance>112</distance>
                //                <time>13</time>
                //                <offset>3</offset>
                //                <distance-text>0.1 km</distance-text>
                //                <direction>NE</direction>
                //                <azimuth>58.1</azimuth>
                //                <turn>TL</turn>
                //                <turn-angle>269.0</turn-angle>
                //            </extensions>
                //        </rtept>
                //        <rtept lat="51.17668" lon="4.39828">
                //            <desc>Turn right at Goudenregenlaan, 70 m</desc>
                //            <extensions>
                //                <distance>70</distance>
                //                <time>8</time>
                //                <offset>5</offset>
                //                <distance-text>70 m</distance-text>
                //                <direction>SE</direction>
                //                <azimuth>143.4</azimuth>
                //                <turn>TR</turn>
                //                <turn-angle>89.8</turn-angle>
                //            </extensions>
                //        </rtept>
                //    </rte>
                //</gpx>
                #endregion

                if (!string.IsNullOrEmpty(route))
                {
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.LoadXml(route);
                    System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmldoc.NameTable);
                    xmlnsManager.AddNamespace("sm", "http://www.topografix.com/GPX/1/1");

                    XmlNodeList wpts = xmldoc.SelectNodes("/sm:gpx/sm:wpt", xmlnsManager);
                    if (wpts != null && wpts.Count > 0)
                    {
                        ret = DirectionsStatusCode.OK;

                        direction       = new GDirections();
                        direction.Route = new List <PointLatLng>();

                        foreach (XmlNode w in wpts)
                        {
                            double lat = double.Parse(w.Attributes["lat"].InnerText, CultureInfo.InvariantCulture);
                            double lng = double.Parse(w.Attributes["lon"].InnerText, CultureInfo.InvariantCulture);
                            direction.Route.Add(new PointLatLng(lat, lng));
                        }

                        if (direction.Route.Count > 0)
                        {
                            direction.StartLocation = direction.Route[0];
                            direction.EndLocation   = direction.Route[direction.Route.Count - 1];
                        }

                        XmlNode n = xmldoc.SelectSingleNode("/sm:gpx/sm:metadata/sm:copyright/sm:license", xmlnsManager);
                        if (n != null)
                        {
                            direction.Copyrights = n.InnerText;
                        }

                        n = xmldoc.SelectSingleNode("/sm:gpx/sm:extensions/sm:distance", xmlnsManager);
                        if (n != null)
                        {
                            direction.Distance = n.InnerText + "m";
                        }

                        n = xmldoc.SelectSingleNode("/sm:gpx/sm:extensions/sm:time", xmlnsManager);
                        if (n != null)
                        {
                            direction.Duration = n.InnerText + "s";
                        }

                        n = xmldoc.SelectSingleNode("/sm:gpx/sm:extensions/sm:start", xmlnsManager);
                        if (n != null)
                        {
                            direction.StartAddress = n.InnerText;
                        }

                        n = xmldoc.SelectSingleNode("/sm:gpx/sm:extensions/sm:end", xmlnsManager);
                        if (n != null)
                        {
                            direction.EndAddress = n.InnerText;
                        }

                        wpts = xmldoc.SelectNodes("/sm:gpx/sm:rte/sm:rtept", xmlnsManager);
                        if (wpts != null && wpts.Count > 0)
                        {
                            direction.Steps = new List <GDirectionStep>();

                            foreach (XmlNode w in wpts)
                            {
                                GDirectionStep step = new GDirectionStep();

                                double lat = double.Parse(w.Attributes["lat"].InnerText, CultureInfo.InvariantCulture);
                                double lng = double.Parse(w.Attributes["lon"].InnerText, CultureInfo.InvariantCulture);

                                step.StartLocation = new PointLatLng(lat, lng);

                                XmlNode nn = w.SelectSingleNode("sm:desc", xmlnsManager);
                                if (nn != null)
                                {
                                    step.HtmlInstructions = nn.InnerText;
                                }

                                nn = w.SelectSingleNode("sm:extensions/sm:distance-text", xmlnsManager);
                                if (nn != null)
                                {
                                    step.Distance = nn.InnerText;
                                }

                                nn = w.SelectSingleNode("sm:extensions/sm:time", xmlnsManager);
                                if (nn != null)
                                {
                                    step.Duration = nn.InnerText + "s";
                                }

                                direction.Steps.Add(step);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ret       = DirectionsStatusCode.ExceptionInCode;
                direction = null;
                Debug.WriteLine("GetDirectionsUrl: " + ex);
            }

            return(ret);
        }