AddNamespace() public method

public AddNamespace ( string prefix, string uri ) : void
prefix string
uri string
return void
Exemplo n.º 1
1
        /// <summary>
        /// Metodo para carregar os dados.
        /// </summary>
        /// <returns></returns>
        public List<YoutubeFeedItem> Listar()
        {
            string url = String.Format("https://gdata.youtube.com/feeds/api/videos?author={0}&orderby=published&start-index=11&max-results={1}&v=2&fields=entry(title,published,link,media:group(media:thumbnail, media:description))", this.Username, this.Lines);
            XmlDocument xmlDoc = this.GetXmlDocument(url);

            /// Uma peculiaridade deste codico é que o retorno do XML traz a definição
            /// de uma namespace implicita, assim como outras. Ou seja, se não regitrarmos
            /// as namespaces e depois as referenciarmos, a engine não irá encontrar
            /// os lementos especificados nos xpath.
            XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
            nsManager.AddNamespace("atom", "http://www.w3.org/2005/Atom");
            nsManager.AddNamespace("media", "http://search.yahoo.com/mrss/");
            nsManager.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007");

            List<YoutubeFeedItem> resultados = new List<YoutubeFeedItem>();

            foreach (XmlNode node in xmlDoc.SelectNodes("//atom:entry", nsManager))
            {
                resultados.Add(new YoutubeFeedItem()
                {
                    Text = node.SelectSingleNode("atom:title", nsManager).InnerText,
                    Link = node.SelectSingleNode("atom:link[@type='text/html']", nsManager).Attributes["href"].Value,
                    Description = node.SelectSingleNode("media:group/media:description", nsManager).InnerText,
                    Thumbnail = node.SelectSingleNode("media:group/media:thumbnail", nsManager).Attributes["url"].Value,
                    Published = DateTime.Parse(node.SelectSingleNode("atom:published", nsManager).InnerText)
                });
            }

            return resultados;
        }
Exemplo n.º 2
0
 static NugetXmlFeed()
 {
     _manager = new XmlNamespaceManager(new NameTable());
     _manager.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
     _manager.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
     _manager.AddNamespace("atom", "http://www.w3.org/2005/Atom");
 }
        public override bool OnActivate()
        {
            base.OnActivate();
            AddBrandingPanel();
            HasBeenActivated = true;
            this.Cancellable = false;
            this.ShowInfoPanel = false;

            //get title, description and version
            string path = Path.Combine(GetBasePath(), "SPALM.SPSF.xml");
            if (File.Exists(path))
            {
                XmlDocument guidanceDoc = new XmlDocument();
                guidanceDoc.Load(path);

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(guidanceDoc.NameTable);
                nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/pag/gax-core");
                nsmgr.AddNamespace("spsf", "http://spsf.codeplex.com");
                nsmgr.AddNamespace("wiz", "http://schemas.microsoft.com/pag/gax-wizards");

                XmlNode rootNode = guidanceDoc.SelectSingleNode("/ns:GuidancePackage", nsmgr);
                if (rootNode != null)
                {
                    label_title.Text = rootNode.Attributes["Caption"].Value.ToString();
                    label_description.Text = rootNode.Attributes["Description"].Value.ToString();
                    label_version.Text = rootNode.Attributes["Version"].Value.ToString();
                }
            }

            //get fileversion of assembly
            label_fileversion.Text = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;

            //TODO: get contributors from Authors.xml
            return true;
        }
Exemplo n.º 4
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";
            }
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            // Massive mem use here somewhere - about 1 GB
            var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var gmlDoc = new XmlDocument();
            gmlDoc.Load(Path.Combine(userProfile, ConfigurationManager.AppSettings["GeographyFile"]));
            var ns = new XmlNamespaceManager(gmlDoc.NameTable);
            ns.AddNamespace("gml", "http://www.opengis.net/gml");
            ns.AddNamespace("fme", "http://www.safe.com/gml/fme");
            var nodes = gmlDoc.SelectNodes("/gml:FeatureCollection/gml:featureMember", ns);

            var boundaries = new List<BoundaryItem>();
            foreach (XmlNode node in nodes)
            {
                boundaries.Add(new BoundaryItem(ns, node));
            }

            var collection = new BoundaryItemCollection();
            collection.SetItems(boundaries);
            var importer = new NpgsqlBulkImporter(ConfigurationManager.ConnectionStrings["spurious"].ConnectionString);
            importer.BulkImport("subdivisions", collection);
            Console.WriteLine("Bulk update complete");

            using (var wrapper = new NpgsqlConnectionWrapper(ConfigurationManager.ConnectionStrings["spurious"].ConnectionString))
            {
                wrapper.Connection.Open();
                var rowsGeoUpdated = wrapper.ExecuteNonQuery("update subdivisions s set (boundry) = ((select ST_FlipCoordinates(ST_GeomFromGML(boundary_gml, 4269)) from subdivisions ss where s.id = ss.id))");
                Console.WriteLine($"Updated {rowsGeoUpdated} rows geo data from GML data");
            }

            Console.WriteLine("Node count {0}", nodes.Count);
        }
Exemplo n.º 6
0
        public bool ApplyToContent(string rootFolder)
        {
            var fullPath = rootFolder + @"\" + AppxRelativePath;

            if (!File.Exists(fullPath))
            {
                return(false);
            }

            var document = new XmlDocument();

            document.XmlResolver = null;

            using (var textReader = new XmlTextReader(fullPath))
            {
                textReader.DtdProcessing = DtdProcessing.Ignore;
                document.Load(textReader);
            }

            var navigator    = document.CreateNavigator();
            var xmlnsManager = new System.Xml.XmlNamespaceManager(document.NameTable);

            xmlnsManager.AddNamespace("std", "http://schemas.microsoft.com/appx/manifest/foundation/windows10");
            xmlnsManager.AddNamespace("mp", "http://schemas.microsoft.com/appx/2014/phone/manifest");
            xmlnsManager.AddNamespace("uap", "http://schemas.microsoft.com/appx/manifest/uap/windows10");
            xmlnsManager.AddNamespace("iot", "http://schemas.microsoft.com/appx/manifest/iot/windows10");
            xmlnsManager.AddNamespace("build", "http://schemas.microsoft.com/developer/appx/2015/build");

            var node = navigator.SelectSingleNode(XPath, xmlnsManager);

            node.SetValue(Value);

            document.Save(fullPath);
            return(true);
        }
Exemplo n.º 7
0
 static Router()
 {
     namespaceManager = new XmlNamespaceManager(new NameTable());
     namespaceManager.AddNamespace("cnf", "http://cnf/Integration");
     namespaceManager.AddNamespace("cnfMgr", "http://cnf/ConfirmationsManager");
     namespaceManager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
 }
Exemplo n.º 8
0
        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;
        }
Exemplo n.º 9
0
        private static string PrepareComponentUpdateXml(string xmlpath, IDictionary<string, string> paths)
        {
            string xml = File.ReadAllText(xmlpath);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
            manager.AddNamespace("avm", "avm");
            manager.AddNamespace("cad", "cad");

            XPathNavigator navigator = doc.CreateNavigator();
            var resourceDependencies = navigator.Select("/avm:Component/avm:ResourceDependency", manager).Cast<XPathNavigator>()
                .Concat(navigator.Select("/avm:Component/ResourceDependency", manager).Cast<XPathNavigator>());
            
            foreach (XPathNavigator node in resourceDependencies)
            {
                string path = node.GetAttribute("Path", "avm");
                if (String.IsNullOrWhiteSpace(path))
                {
                    path = node.GetAttribute("Path", "");
                }
                string newpath;
                if (paths.TryGetValue(node.GetAttribute("Name", ""), out newpath))
                {
                    node.MoveToAttribute("Path", "");
                    node.SetValue(newpath);
                }
            }
            StringBuilder sb = new StringBuilder();
            XmlTextWriter w = new XmlTextWriter(new StringWriter(sb));
            doc.WriteContentTo(w);
            w.Flush();
            return sb.ToString();
        }
Exemplo n.º 10
0
        public CASClient(
            ShellSettings settings, 
            ITicketValidatorFactory ticketValidatorFactory,
            IRequestEvaluator requestEvaluator,
            IClock clock,
            IUrlUtil urlUtil,
            IAuthenticationService authenticationService,
            ICasServices casServices) {
            _settings = settings;
            _ticketValidatorFactory = ticketValidatorFactory;
            _requestEvaluator = requestEvaluator;
            _clock = clock;
            _urlUtil = urlUtil;
            _authenticationService = authenticationService;
            _casServices = casServices;

            _xmlNamespaceManager = new XmlNamespaceManager(_xmlNameTable);
            _xmlNamespaceManager.AddNamespace("cas", "http://www.yale.edu/tp/cas");
            _xmlNamespaceManager.AddNamespace("saml", "urn: oasis:names:tc:SAML:1.0:assertion");
            _xmlNamespaceManager.AddNamespace("saml2", "urn: oasis:names:tc:SAML:1.0:assertion");
            _xmlNamespaceManager.AddNamespace("samlp", "urn: oasis:names:tc:SAML:1.0:protocol");

            Logger = NullLogger.Instance;
            T = NullLocalizer.Instance;
        }
        /*-------------------------------------------------------------------------------------------------------
        ** Constructors
        **-----------------------------------------------------------------------------------------------------*/
        
        public CheckBoxContentControl(ApplicationField ApplicationField)
            : base(ApplicationField)
        {
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(ApplicationField.Parameters[0]);

            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xml.NameTable);
            namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            namespaceManager.AddNamespace("w14", "http://schemas.microsoft.com/office/word/2010/wordml");

            XmlNodeList xnList = xml.SelectNodes("/w:sdt/w:sdtPr/w14:checkbox", namespaceManager);

            foreach (XmlNode xn in xnList)
            {
                foreach (XmlNode subnode in xn.ChildNodes)
                {
                    switch (subnode.LocalName)
                    {
                        case "checked":
                            if (subnode.Attributes["w14:val"] != null)
                                _bChecked = ((Convert.ToInt32(subnode.Attributes["w14:val"].Value) != 0));
                            break;
                    }
                }
            }
        }
Exemplo n.º 12
0
        public void LoadFromXml(XmlNode node)
        {
            this.DocInfo = new MmlDocumentInfo(node.SelectSingleNode("docInfo"));
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(node.OwnerDocument.NameTable);

            XmlNode content = node.SelectSingleNode("content");
            if (this.DocInfo.ContentModuleType == "patientInfo") {
                nsmgr.AddNamespace(MmlPi.PatientModule.NameSpacePrefix, MmlPi.PatientModule.NameSpaceURI);
                this.Content = new MmlPi.PatientModule(content.SelectSingleNode("mmlPi:PatientModule",nsmgr));
            } else if (this.DocInfo.ContentModuleType == "healthInsurance") {
                nsmgr.AddNamespace(MmlHi.HealthInsurance.NameSpacePrefix, MmlHi.HealthInsurance.NameSpaceURI);
                this.Content = new MmlHi.HealthInsurance(content.SelectSingleNode("mmlHi:HealthInsuranceModule", nsmgr));
            } else if (this.DocInfo.ContentModuleType == "registeredDiagnosis") {
                nsmgr.AddNamespace(MmlRd.RegisteredDiagnosisModule.NameSpacePrefix, MmlRd.RegisteredDiagnosisModule.NameSpaceURI);
                this.Content = new MmlRd.RegisteredDiagnosisModule(content.SelectSingleNode("mmlRd:RegisteredDiagnosisModule", nsmgr));
            } else if (this.DocInfo.ContentModuleType == "lifestyle") {
            } else if (this.DocInfo.ContentModuleType == "baseClinic") {
            } else if (this.DocInfo.ContentModuleType == "firstClinic") {
            } else if (this.DocInfo.ContentModuleType == "progressCourse") {
            } else if (this.DocInfo.ContentModuleType == "surgery") {
            } else if (this.DocInfo.ContentModuleType == "summary") {
            } else if (this.DocInfo.ContentModuleType == "claim") {
                nsmgr.AddNamespace(Claim.ClaimModule.NameSpacePrefix, Claim.ClaimModule.NameSpaceURI);
                this.Content = new Claim.ClaimModule(content.SelectSingleNode("claim:ClaimModule", nsmgr));
            } else if (this.DocInfo.ContentModuleType == "claimAmount") {
            } else if (this.DocInfo.ContentModuleType == "referral") {
            } else if (this.DocInfo.ContentModuleType == "test") {
            } else if (this.DocInfo.ContentModuleType == "report") {
            } else {
                throw new XmlException("ContentModuleTypeが対象外です。:" + this.DocInfo.ContentModuleType);
            }
        }
Exemplo n.º 13
0
        private List<Entities.Models.BlogItemModel> GetItens(string urlFeed)
        {
            var retorno = new List<Entities.Models.BlogItemModel>();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(Library.Feed.Get(urlFeed));

            XmlNode channelNode = doc.SelectSingleNode("rss/channel");
            if (channelNode != null)
            {
                XmlNamespaceManager nameSpace = new XmlNamespaceManager(doc.NameTable);
                nameSpace.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
                nameSpace.AddNamespace("slash", "http://purl.org/rss/1.0/modules/slash/");
                nameSpace.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");

                foreach (XmlNode item in channelNode.SelectNodes("item"))
                {
                    var newItem = new Entities.Models.BlogItemModel();
                    newItem.title = item.SelectSingleNode("title").InnerText;
                    newItem.slash = item.SelectSingleNode("slash:comments", nameSpace).InnerText;
                    newItem.pubDate = item.SelectSingleNode("pubDate").InnerText;
                    newItem.link = item.SelectSingleNode("link").InnerText;
                    newItem.guid = item.SelectSingleNode("guid").InnerText;
                    newItem.description = item.SelectSingleNode("description").InnerText;
                    newItem.creator = item.SelectSingleNode("dc:creator", nameSpace).InnerText;
                    newItem.content = item.SelectSingleNode("content:encoded", nameSpace).InnerText;
                    newItem.comments = item.SelectSingleNode("comments").InnerText;
                    newItem.category = item.SelectSingleNode("category").InnerText;
                    retorno.Add(newItem);
                }
            }
            return retorno;
        }
Exemplo n.º 14
0
		void AssertDecryption1 (string filename)
		{
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;
			doc.Load (filename);
			EncryptedXml encxml = new EncryptedXml (doc);
			RSACryptoServiceProvider rsa = new X509Certificate2 ("Test/System.Security.Cryptography.Xml/sample.pfx", "mono").PrivateKey as RSACryptoServiceProvider;
			XmlNamespaceManager nm = new XmlNamespaceManager (doc.NameTable);
			nm.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope");
			nm.AddNamespace ("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			nm.AddNamespace ("e", EncryptedXml.XmlEncNamespaceUrl);
			XmlElement el = doc.SelectSingleNode ("/s:Envelope/s:Header/o:Security/e:EncryptedKey", nm) as XmlElement;
			EncryptedKey ekey = new EncryptedKey ();
			ekey.LoadXml (el);
			byte [] key = rsa.Decrypt (ekey.CipherData.CipherValue, true);
			Rijndael aes = new RijndaelManaged ();
			aes.Key = key;
			aes.Mode = CipherMode.CBC;
			ArrayList al = new ArrayList ();
			foreach (XmlElement ed in doc.SelectNodes ("//e:EncryptedData", nm))
				al.Add (ed);
			foreach (XmlElement ed in al) {
				EncryptedData edata = new EncryptedData ();
				edata.LoadXml (ed);
				encxml.ReplaceData (ed, encxml.DecryptData (edata, aes));
			}
		}
Exemplo n.º 15
0
 public static XmlNamespaceManager CreateManager(XmlNameTable table)
 {
     XmlNamespaceManager mgr = new XmlNamespaceManager(table);
     mgr.AddNamespace(Options_Prefix, Options);
     mgr.AddNamespace(SongBook_Prefix, SongBook);
     return mgr;
 }
Exemplo n.º 16
0
        /// <summary>
        /// Tries to extract the BluRay title.
        /// </summary>
        /// <returns></returns>
        public string GetTitle()
        {
            string metaFilePath = Path.Combine(DirectoryBDMV.FullName, @"META\DL\bdmt_eng.xml");
              if (!File.Exists(metaFilePath))
            return null;

              try
              {
            XPathDocument metaXML = new XPathDocument(metaFilePath);
            XPathNavigator navigator = metaXML.CreateNavigator();
            if (navigator.NameTable != null)
            {
              XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
              ns.AddNamespace("", "urn:BDA:bdmv;disclib");
              ns.AddNamespace("di", "urn:BDA:bdmv;discinfo");
              navigator.MoveToFirst();
              XPathNavigator node = navigator.SelectSingleNode("//di:discinfo/di:title/di:name", ns);
              if (node != null)
            return node.ToString().Trim();
            }
              }
              catch (Exception e)
              {
            ServiceRegistration.Get<ILogger>().Error("BDMEx: Meta File Error: ", e);
              }
              return null;
        }
Exemplo n.º 17
0
        public static MapsLookupResult GeocodeAddress(IAddress addr)
        {
            MapsLookupResult result = new MapsLookupResult { Result = LookupResult.Error };
            if (addr.Street.ToLower().StartsWith("po box"))
            {
                result.Result = LookupResult.NotFound;
                return result;
            }

            WebClient client = new WebClient();
            XmlDocument xml = new System.Xml.XmlDocument();
            string url = string.Format("http://maps.google.com/maps/geo?q={0}&key={1}&output=xml",
                System.Web.HttpUtility.UrlEncode(string.Format("{0}, {1} {2} {3}", addr.Street, addr.City, addr.State, addr.Zip)),
                System.Configuration.ConfigurationManager.AppSettings["MapsKey"]
                );

            xml.LoadXml(client.DownloadString(url));

            XmlElement root = xml.DocumentElement;
            XmlNamespaceManager nsmgr = new
            XmlNamespaceManager(xml.NameTable);
            nsmgr.AddNamespace("k", root.NamespaceURI);
            nsmgr.AddNamespace("d", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0");

            string status = xml.SelectSingleNode("//k:Response/k:Status/k:code", nsmgr).InnerText;
            if (status != "200")
            {
                // Error
            }
            else
            {
                XmlNode details = xml.SelectSingleNode("//d:AddressDetails", nsmgr);

                string accuracyString = ((XmlElement)details).GetAttribute("Accuracy");
                result.Quality = int.Parse(accuracyString);

                result.Result = LookupResult.Range;
                if (result.Quality > 5)
                {
                    result.Result = LookupResult.Success;
                    result.Street = details.SelectSingleNode("//d:ThoroughfareName", nsmgr).InnerText;
                }
                if (result.Quality > 4)
                {
                    result.Zip = details.SelectSingleNode("//d:PostalCodeNumber", nsmgr).InnerText;
                }
                result.City = details.SelectSingleNode("//d:LocalityName", nsmgr).InnerText;
                result.State = details.SelectSingleNode("//d:AdministrativeAreaName", nsmgr).InnerText;

                string[] coords = details.SelectSingleNode("//k:Response/k:Placemark/k:Point", nsmgr).InnerText.Split(',');
                double lat = double.Parse(coords[1]);
                double lng = double.Parse(coords[0]);
                double z = GeographyServices.GetElevation(lat, lng);

                string point = (z > 0) ? string.Format("POINT({0} {1} {2} NULL)", lng, lat, z) : string.Format("POINT({0} {1})", lng, lat);

                result.Geography = SqlGeography.STGeomFromText(new SqlChars(point.ToCharArray()), GeographyServices.SRID);
            }
            return result;
        }
Exemplo n.º 18
0
        public bool ApplyToContent(string rootFolder)
        {
            var fullPath = rootFolder + @"\" + AppxRelativePath;
            if (!File.Exists(fullPath))
            {
                return false;
            }

            var document = new XmlDocument();
            document.XmlResolver = null;

            using (var textReader = new XmlTextReader(fullPath))
            {
                textReader.DtdProcessing = DtdProcessing.Ignore;
                document.Load(textReader);
            }

            var navigator = document.CreateNavigator();
            var xmlnsManager = new System.Xml.XmlNamespaceManager(document.NameTable);
            xmlnsManager.AddNamespace("std", "http://schemas.microsoft.com/appx/manifest/foundation/windows10");
            xmlnsManager.AddNamespace("mp", "http://schemas.microsoft.com/appx/2014/phone/manifest");
            xmlnsManager.AddNamespace("uap", "http://schemas.microsoft.com/appx/manifest/uap/windows10");
            xmlnsManager.AddNamespace("iot", "http://schemas.microsoft.com/appx/manifest/iot/windows10");
            xmlnsManager.AddNamespace("build", "http://schemas.microsoft.com/developer/appx/2015/build");

            var node = navigator.SelectSingleNode(XPath, xmlnsManager);
            node.SetValue(Value);

            document.Save(fullPath);
            return true;
        }
Exemplo n.º 19
0
        /// <summary>
        /// Initializes a new instance of the ArtifactResponse class.
        /// </summary>
        /// <param name="artifactResponse">
        /// String representation of the ArtifactResponse xml.
        /// </param>
        public ArtifactResponse(string artifactResponse)
        {
            try
            {
                xml = new XmlDocument();
                xml.PreserveWhitespace = true;
                xml.LoadXml(artifactResponse);
                nsMgr = new XmlNamespaceManager(xml.NameTable);
                nsMgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
                nsMgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
                nsMgr.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");

                string xpath = "/samlp:ArtifactResponse/samlp:Response";
                XmlNode response = xml.DocumentElement.SelectSingleNode(xpath, nsMgr);
                if (response == null)
                {
                    throw new Saml2Exception(Resources.ArtifactResponseMissingResponse);
                }

                authnResponse = new AuthnResponse(response.OuterXml);
            }
            catch (ArgumentNullException ane)
            {
                throw new Saml2Exception(Resources.ArtifactResponseNullArgument, ane);
            }
            catch (XmlException xe)
            {
                throw new Saml2Exception(Resources.ArtifactResponseXmlException, xe);
            }
        }
Exemplo n.º 20
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");
 }
Exemplo n.º 21
0
 internal static string[] GetClickOnceInfo(ref string manifestPath, bool scanRemote, ref bool isUncPath, ref bool isHttpPath)
 {
     string[] strArray = new string[2];
       string str1 = string.Empty;
       string baseDir = string.Empty;
       string str2 = string.Empty;
       XmlDocument deployDoc = new XmlDocument();
       if (manifestPath == null || manifestPath.Length == 0)
     throw new ArgumentException(Resources.EMPTY_MANIFESTPATH);
       try
       {
     Uri uri = new Uri(manifestPath);
     bool flag;
     if (uri.IsLoopback)
       flag = ManifestReader.GetManifestFromLocalPath(deployDoc, ref manifestPath, out baseDir);
     else if (uri.IsUnc)
     {
       isUncPath = true;
       flag = scanRemote && ManifestReader.GetManifestFromUncPath(deployDoc, ref manifestPath, out baseDir);
     }
     else if (uri.Host != null && uri.Host.Length > 0)
     {
       isHttpPath = true;
       flag = scanRemote && ManifestReader.GetManifestFromHttpUrlPath(manifestPath, deployDoc, out baseDir);
     }
     else
       flag = false;
     if (flag)
     {
       XmlNamespaceManager nsmgr = new XmlNamespaceManager(deployDoc.NameTable);
       nsmgr.AddNamespace("asmv1", "urn:schemas-microsoft-com:asm.v1");
       nsmgr.AddNamespace("def", "urn:schemas-microsoft-com:asm.v2");
       XmlNode xmlNode1 = (XmlNode) deployDoc.DocumentElement;
       XmlNode xmlNode2 = xmlNode1.SelectSingleNode("/asmv1:assembly/def:dependency/def:dependentAssembly", nsmgr);
       XmlNode xmlNode3 = xmlNode1.SelectSingleNode("/asmv1:assembly/def:dependency/def:dependentAssembly/def:assemblyIdentity", nsmgr);
       string path2_1 = xmlNode2.Attributes["codebase"].Value;
       string path2_2 = xmlNode3.Attributes["name"].Value;
       str2 = xmlNode3.Attributes["version"].Value;
       if (isHttpPath)
       {
     string str3 = (baseDir + path2_1).Replace("\\", "/");
     str1 = str3.Substring(0, str3.LastIndexOf(".manifest")) + ".deploy";
       }
       else
     str1 = Path.Combine(Path.GetDirectoryName(Path.Combine(baseDir, path2_1)), path2_2) + ".deploy";
     }
     else
     {
       str1 = (string) null;
       str2 = (string) null;
     }
       }
       catch (Exception ex)
       {
     Globals.AddException(ex);
       }
       strArray[0] = str1;
       strArray[1] = str2;
       return strArray;
 }
Exemplo n.º 22
0
        internal void SetReferences(Schema schema, BizTalkArtifacts artifacts, Microsoft.BizTalk.ExplorerOM.Schema omSchema)
        {
            schema.Application = artifacts.Applications[omSchema.Application.Id()];
            schema.ParentAssembly = artifacts.Assemblies[omSchema.BtsAssembly.Id()];

            if (_schema == null || _schema.Name == null || !_schema.Name.Equals(schema.Name, StringComparison.Ordinal))
            {
                var source = new XmlDocument();
                source.LoadXml(omSchema.GetXmlContent());

                var mgr = new XmlNamespaceManager(source.NameTable);
                mgr.AddNamespace("b", "http://schemas.microsoft.com/BizTalk/2003");
                mgr.AddNamespace("x", "http://www.w3.org/2001/XMLSchema");

                SetSchemaType(schema, source, mgr);
                SetSchemaImports(schema, source, mgr, artifacts);

                if (omSchema.Properties != null)
                {
                    foreach (DictionaryEntry property in omSchema.Properties)
                    {
                        schema.Properties.Add(new KeyValuePair<string, string>(property.Key.ToString(),
                                                                               property.Value.ToString()));
                    }
                }

                _schema = schema;
            }
            else
            {
                schema.Properties = _schema.Properties;
                schema.SchemaType = _schema.SchemaType;
                schema.ReferencedSchemas = _schema.ReferencedSchemas;
            }
        }
Exemplo n.º 23
0
 /// <summary>
 /// Prepare namespace manager for usage (add standard namespaces)
 /// </summary>
 /// <param name="wsdl"></param>
 /// <returns></returns>
 private static XmlNamespaceManager PrepareNamespaceManager ( XmlDocument wsdl )
 {
     XmlNamespaceManager manager = new XmlNamespaceManager ( wsdl.NameTable );
     manager.AddNamespace ( "wsdl", WSDLNamespace );
     manager.AddNamespace ( "xsd", XSDNamespace );
     return manager;
 }
        public void ActivityNameForXmlListenersStrangeCharacters()
        {
            TraceSource source = new TraceSource("testScopeSource");
            var listener = source.Listeners.OfType<TestTraceListener>().First();
            listener.MethodCallInformation.Clear();
            string transferIn = "TransferIn";
            string start = "<";
            string transferOut = "TransferOut";
            string stop = "Stopping...";
            var activityName = "<";

            using (var scope = new ActivityScope(source, 11, 12, 13, 14, transferIn, start, transferOut, stop, activityName))
            {
                source.TraceEvent(TraceEventType.Warning, 2, "B");
            }

            var events = listener.MethodCallInformation;
            StringAssert.StartsWith(events[0].Message, transferIn);

            Console.WriteLine(string.Join(",", events[1].Data));
            Assert.AreEqual(1, events[1].Data.Length);
            Assert.IsInstanceOfType(events[1].Data[0], typeof(XPathNavigator));
            var navigator = (XPathNavigator)events[1].Data[0];
            var resolver = new XmlNamespaceManager(navigator.NameTable);
            resolver.AddNamespace("ns1", "http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord");
            resolver.AddNamespace("ns2", "http://schemas.microsoft.com/2006/08/ServiceModel/DictionaryTraceRecord");
            Assert.AreEqual(start, navigator.SelectSingleNode("/ns1:TraceRecord/ns1:Description", resolver).Value);
            Assert.AreEqual(activityName, navigator.SelectSingleNode("/ns1:TraceRecord/ns2:ExtendedData/ns2:ActivityName", resolver).Value);
            //StringAssert.Contains(events[1].Data[0].ToString(), activityName);
            //StringAssert.Contains(events[1].Data[0].ToString(), start);

            StringAssert.StartsWith(events[3].Message, transferOut);
            Assert.AreEqual(stop, events[4].Message);
        }
Exemplo n.º 25
0
        private static Tuple <XmlDocument, XmlNamespaceManager> GetResourceXmlDocument(Uri resourceDictionaryUri)
        {
            return(_resourceDictionaryCache.GetFromCacheOrFetch(resourceDictionaryUri, () =>
            {
                var streamResourceInfo = Application.GetResourceStream(resourceDictionaryUri);
                var reader = new XmlBamlReader(streamResourceInfo.Stream);

                var doc = new XmlDocument();
                doc.Load(reader);

                // Create namespace manager (all namespaces are required)
                var xmlNamespaceManager = new XmlNamespaceManager(doc.NameTable);
                foreach (XmlAttribute namespaceAttribute in doc.DocumentElement.Attributes)
                {
                    // Clean up namespace (remove xmlns prefix)
                    var xmlNamespace = namespaceAttribute.Name.Replace("xmlns", string.Empty).TrimStart(':');
                    xmlNamespaceManager.AddNamespace(xmlNamespace, namespaceAttribute.Value);
                }

                // Add a dummy node
                xmlNamespaceManager.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
                xmlNamespaceManager.AddNamespace("ctl", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");

                return new Tuple <XmlDocument, XmlNamespaceManager>(doc, xmlNamespaceManager);
            }));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Creates a <see cref="XmlNamespaceManager"/> for <paramref name="document"/>.
        /// Namespaces declared in the document node are automatically added.
        /// The default namespace is given the prefix 'ns'.
        /// </summary>
        public static XmlNamespaceManager CreateNamespaceManager(this XmlDocument document)
        {
            var manager = new XmlNamespaceManager(document.NameTable);

            foreach (XmlNode node in document.SelectNodes("//node()"))
            {
                if (node is XmlElement)
                {
                    var element = node as XmlElement;

                    foreach (XmlAttribute attribute in element.Attributes)
                    {
                        if (attribute.Name == "xmlns")
                        {
                            // The first default namespace wins
                            // (since using multiple default namespaces in a single file is not considered a good practice)
                            if (!manager.HasNamespace("ns"))
                            {
                                manager.AddNamespace("ns", attribute.Value);
                            }
                        }

                        if (attribute.Prefix == "xmlns")
                        {
                            manager.AddNamespace(attribute.LocalName, attribute.Value);
                        }
                    }
                }
            }

            return manager;
        }
            public void HoveddokumentStarterMedEtTallXsdValidererIkke()
            {
                var arkiv = DomeneUtility.GetAsicEArkivEnkel();

                var signaturXml = arkiv.Signatur.Xml();
                var signaturvalidator = new Signaturvalidator();

                //Endre id på hoveddokument til å starte på et tall
                var namespaceManager = new XmlNamespaceManager(signaturXml.NameTable);
                namespaceManager.AddNamespace("ds", NavneromUtility.XmlDsig);
                namespaceManager.AddNamespace("ns10", NavneromUtility.UriEtsi121);
                namespaceManager.AddNamespace("ns11", NavneromUtility.UriEtsi132);

                var hoveddokumentReferanseNode = signaturXml.DocumentElement
                    .SelectSingleNode("//ds:Reference[@Id = '" + DomeneUtility.GetHoveddokumentEnkel().Id + "']",
                        namespaceManager);

                var gammelVerdi = hoveddokumentReferanseNode.Attributes["Id"].Value;
                hoveddokumentReferanseNode.Attributes["Id"].Value = "0_Id_Som_Skal_Feile";

                var validerer = signaturvalidator.ValiderDokumentMotXsd(signaturXml.OuterXml);
                Assert.IsFalse(validerer, signaturvalidator.ValideringsVarsler);

                hoveddokumentReferanseNode.Attributes["Id"].Value = gammelVerdi;
            }
Exemplo n.º 28
0
        public void ModifyStylesXML(string projectPath, Dictionary<string, Dictionary<string, string>> childStyle, List<string> usedStyleName, Dictionary<string, string> languageStyleName, string baseStyle, bool isHeadword, Dictionary<string, string> parentClass, string odmMTFont)
        {
            LoadAllProperty();
            LoadSpellCheck();
            CreateFontLanguageMap();
            
            _childStyle = childStyle;
            _projectPath = projectPath;
            _isHeadword = isHeadword;
            _languageStyleName = languageStyleName;
            _parentClass = parentClass;
            string styleFilePath = OpenIDStyles(); //todo change name
            SetHeaderFontName(styleFilePath, odmMTFont);
            nsmgr = new XmlNamespaceManager(_styleXMLdoc.NameTable);
            nsmgr.AddNamespace("style", "urn:oasis:names:tc:opendocument:xmlns:style:1.0");
            nsmgr.AddNamespace("fo", "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0");
            nsmgr.AddNamespace("text", "urn:oasis:names:tc:opendocument:xmlns:text:1.0");

            _root = _styleXMLdoc.DocumentElement;
            if (_root == null)
            {
                return;
            }

            const string paraStyle = "Empty";
            const string charStyle = "Empty";

            CreateStyle(paraStyle, charStyle, usedStyleName);
            _styleXMLdoc.Save(styleFilePath);

            AddFontDeclarative(styleFilePath, _languageFont);
        }
Exemplo n.º 29
0
 private static XmlNamespaceManager LoadNamespaceManager(XmlDocument docOrig)
 {
     XmlNamespaceManager nsm = new XmlNamespaceManager(docOrig.NameTable);
     nsm.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
     nsm.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
     return nsm;
 }
Exemplo n.º 30
0
        /// <summary>
        /// Initializes a new instance of the ArtifactResolve class.
        /// </summary>
        /// <param name="serviceProvider">Service Provider to issue this request</param>
        /// <param name="artifact">SAMLv2 Artifact</param>
        public ArtifactResolve(IServiceProvider serviceProvider, Artifact artifact, Saml2Utils saml2Utils)
        {
            xml = new XmlDocument();
            xml.PreserveWhitespace = true;

            nsMgr = new XmlNamespaceManager(xml.NameTable);
            nsMgr.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
            nsMgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");

            Id = saml2Utils.GenerateId();
            IssueInstant = saml2Utils.GenerateIssueInstant();
            Issuer = serviceProvider.EntityId;
            Artifact = artifact;

            var rawXml = new StringBuilder();
            rawXml.Append("<samlp:ArtifactResolve");
            rawXml.Append(" xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\"");
            rawXml.Append(" xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\"");
            rawXml.Append(" ID=\"" + Id + "\"");
            rawXml.Append(" Version=\"2.0\"");
            rawXml.Append(" IssueInstant=\"" + IssueInstant + "\"");
            rawXml.Append(">");
            rawXml.Append(" <saml:Issuer>" + Issuer + "</saml:Issuer>");
            rawXml.Append(" <samlp:Artifact>" + Artifact + "</samlp:Artifact>");
            rawXml.Append("</samlp:ArtifactResolve>");

            xml.LoadXml(rawXml.ToString());
        }
Exemplo n.º 31
0
        public AtomParser(string uri, string xml)
        {
            Uri = uri;
            document = new XmlDocument();
            xml = xml.TrimStart();

            document.LoadXml(xml);

            mgr = new XmlNamespaceManager(document.NameTable);
            if ( xml.Contains("xmlns=\"http://purl.org/atom/ns#\"") ) {
                mgr.AddNamespace("atom", "http://purl.org/atom/ns#");
            } else {
                mgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
            }

            Name = GetXmlNodeText(document, "/atom:feed/atom:title");
            Subtitle = GetXmlNodeText(document, "/atom:feed/atom:subtitle");
            License = GetXmlNodeText(document, "/atom:feed/atom:license");
            Image = GetXmlNodeText(document, "/atom:feed/atom:banner");
            Author = GetXmlNodeText(document, "/atom:feed/atom:author/atom:name");

            XmlNodeList nodes = document.SelectNodes("//atom:entry", mgr);

            Items = new ArrayList();
            foreach (XmlNode node in nodes) {
                items.Add(ParseItem(node));
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FeatureSourceDescription"/> class.
        /// </summary>
        /// <param name="stream">The stream.</param>
        public FeatureSourceDescription(System.IO.Stream stream)
        {
            List<FeatureSchema> schemas = new List<FeatureSchema>();

            XmlDocument doc = new XmlDocument();
            doc.Load(stream);

            XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
            mgr.AddNamespace("xs", XmlNamespaces.XS); //NOXLATE
            mgr.AddNamespace("gml", XmlNamespaces.GML); //NOXLATE
            mgr.AddNamespace("fdo", XmlNamespaces.FDO); //NOXLATE

            //Assume XML configuration document
            XmlNodeList schemaNodes = doc.SelectNodes("fdo:DataStore/xs:schema", mgr); //NOXLATE
            if (schemaNodes.Count == 0) //Then assume FDO schema
                schemaNodes = doc.SelectNodes("xs:schema", mgr); //NOXLATE

            foreach (XmlNode sn in schemaNodes)
            {
                FeatureSchema fs = new FeatureSchema();
                fs.ReadXml(sn, mgr);
                schemas.Add(fs);
            }
            this.Schemas = schemas.ToArray();
        }
Exemplo n.º 33
0
        /*
         *
         * public bool SaveStream(string StreamName, string FileName)
         * {
         *  gStream f = null;
         *  foreach (gStream s in streams) if (s.zfe.FilenameInZip == StreamName) f = s;
         *  if (f == null) return false;
         *  f.SaveToFile(FileName);
         *  return true;
         * }
         * */

        private void SetStructure()                                                                                             // Initializes all the elements of a valid XLSX file
        {
            XmlDocument rd = null, sd = null, st = null;

            foreach (gStream s in streams)                                                                                      // Loop all the streams and get
            {
                if (s.zfe.FilenameInZip == "xl/_rels/workbook.xml.rels")
                {
                    rd = s.ReadAsXml();                                                                                         //      Stream for Relations
                }
                if (s.zfe.FilenameInZip == "xl/workbook.xml")
                {
                    sd = s.ReadAsXml();                                                                                         //      Stream for structure
                }
                if (s.zfe.FilenameInZip == "xl/sharedStrings.xml")
                {
                    st = s.ReadAsXml();                                                                                         //      Stream for strings
                }
            }
            if ((rd == null) || (sd == null) || (st == null))
            {
                throw new Exception("Bad WorkBook");                                                                            // If ay of them could not be found, then raise an error
            }
            XmlNode tn = st.FirstChild.NextSibling.FirstChild;                                                                  // This is the first node with strings

            while (tn != null)
            {
                words.Add(tn.FirstChild.InnerText); tn = tn.NextSibling;
            }                                                                                                                   // Add all strings to dictionary

            XmlNamespaceManager nsmgr0 = new System.Xml.XmlNamespaceManager(sd.NameTable);                                      // Add namespaces

            nsmgr0.AddNamespace("main", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
            nsmgr0.AddNamespace("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            XmlNamespaceManager nsmgr1 = new System.Xml.XmlNamespaceManager(rd.NameTable);

            nsmgr1.AddNamespace("rels", "http://schemas.openxmlformats.org/package/2006/relationships");

            foreach (XmlNode n in sd.SelectNodes("main:workbook/main:sheets/main:sheet", nsmgr0))                               // For each sheet
            {
                string  rId = n.Attributes["r:id"].Value;                                                                       // Get its RelationID
                XmlNode r   = rd.SelectSingleNode("rels:Relationships/rels:Relationship[@Id='" + rId + "']", nsmgr1);           // Use RelationID to find it in Relations
                if (r != null)                                                                                                  // If found,
                {
                    gStream sr = streams.Find(element => element.zfe.FilenameInZip == "xl/" + r.Attributes["Target"].Value);    // Use Target to find the stream implementing the relation
                    if (sr == null)
                    {
                        throw new Exception("Could not find [" + r.Attributes["Target"].Value + "] in streams");                // Raise and error if fail
                    }
                    sr.Sheet = new gSheet(this, Int32.Parse(n.Attributes["sheetId"].Value), n.Attributes["name"].Value, sr);    // Create the stream structure
                    sheets[sr.Sheet.Name] = sr.Sheet;                                                                           // Add it
                }
            }
        }
 public static System.Xml.XmlNamespaceManager StructureNamespace(XmlNameTable NameTable)
 {
     try
     {
         System.Xml.XmlNamespaceManager tmp = new System.Xml.XmlNamespaceManager(NameTable);
         tmp.AddNamespace("s", soap);
         tmp.AddNamespace("web", web);
         return(tmp);
     }
     catch (Exception ex)
     {
         throw new Exception("Error, [Common.CommonNameSpace.RegistryNamespace] " + ex.Message);
     }
 }
        protected override void ProcessDataNode(System.Xml.XmlDocument doc, System.Xml.XmlNamespaceManager namespaces)
        {
            namespaces.AddNamespace("contact", "urn:ietf:params:xml:ns:contact-1.0");

            var children = doc.SelectSingleNode("//contact:creData", namespaces);

            if (children != null)
            {
                XmlNode node;

                // ContactId
                node = children.SelectSingleNode("contact:id", namespaces);
                if (node != null)
                {
                    ContactId = node.InnerText;
                }

                // DateCreated
                node = children.SelectSingleNode("contact:crDate", namespaces);
                if (node != null)
                {
                    DateCreated = node.InnerText;
                }
            }
        }
 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);
     }
 }
Exemplo n.º 37
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);
        }
Exemplo n.º 38
0
        private IValueSet buildScalarSetFromFolder(string folder, DateTime datetime)
        {
            string[] files = Directory.GetFiles(folder);

            //create array list to store location values
            List <double> locationValues = new List <double>();

            //loop through all files in directory to create element set
            foreach (string fileName in files)
            {
                StreamReader sr = new StreamReader(fileName);

                //deserialize
                XmlSerializer          xml_reader = new XmlSerializer(typeof(TimeSeriesResponseType));
                TimeSeriesResponseType tsr        = (TimeSeriesResponseType)xml_reader.Deserialize(sr);

                //load the first file in the directory as an XML document
                DateTime dt;
                double   value;
                for (int i = 0; i < Convert.ToInt32(tsr.timeSeries.values.count); ++i)
                {
                    dt = tsr.timeSeries.values.value[i].dateTime;
                    if (dt == datetime)
                    {
                        dt    = tsr.timeSeries.values.value[i].dateTime;
                        value = Convert.ToDouble(tsr.timeSeries.values.value[i].Value);
                    }
                }
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(fileName);
                System.Xml.XmlNamespaceManager xmlnsManager
                    = new System.Xml.XmlNamespaceManager(xmldoc.NameTable);
                xmlnsManager.AddNamespace("wtr", "http://www.cuahsi.org/waterML/1.0/");

                //lookup the values from the waterml file
                XmlNode xml_value = xmldoc.SelectSingleNode(
                    "//wtr:values//wtr:value[@dateTime='" + datetime.ToString("s") + "']",
                    xmlnsManager);

                if (xml_value != null && xml_value.InnerText != null)
                {
                    //convert to a double.  use -999 for missing values.
                    double num;
                    if (xml_value != null)
                    {
                        num = Convert.ToDouble(xml_value.InnerText);
                    }
                    else
                    {
                        num = -999;
                    }

                    locationValues.Add(num);
                }
            }

            return(new ScalarSet(locationValues.ToArray()));
        }
Exemplo n.º 39
0
        List <PointLatLng> GetRoutePoints(string url)
        {
            List <PointLatLng> points = null;

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

                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);
        }
Exemplo n.º 40
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();
            }
        }
Exemplo n.º 41
0
        private void ParseOPF()
        {
            var opfFile = epubFolderLocation + "/" + opfFileString;

            XmlDocument doc = new XmlDocument();

            doc.Load(opfFile);

            var xmlnsManager = new System.Xml.XmlNamespaceManager(doc.NameTable);

            xmlnsManager.AddNamespace("ns", "http://www.idpf.org/2007/opf");
            xmlnsManager.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
            xmlnsManager.AddNamespace("dcterms", "http://purl.org/dc/terms/");

            ReadMetadata(doc, xmlnsManager);

            ReadChapters(opfFile, doc, xmlnsManager);
        }
Exemplo n.º 42
0
        public NPandayImportProjectForm(DTE2 applicationObject, Logger logger)
        {
            this.applicationObject = applicationObject;
            this.logger            = logger;
            InitializeComponent();

            if (applicationObject != null && applicationObject.Solution != null && applicationObject.Solution.FileName != null)
            {
                txtBrowseDotNetSolutionFile.Text = applicationObject.Solution.FileName;
                try
                {
                    string companyId = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion").GetValue("RegisteredOrganization", "mycompany").ToString();
                    string groupId   = string.Empty;

                    if (companyId != string.Empty)
                    {
                        groupId = FilterID(ConvertToPascalCase(companyId)) + ".";
                    }

                    groupId         = groupId + FilterID(ConvertToPascalCase(new FileInfo(applicationObject.Solution.FileName).Name.Replace(".sln", "")));
                    txtGroupId.Text = groupId;
                    string scmTag      = string.Empty; //getSCMTag(applicationObject.Solution.FileName);
                    string version     = "1.0-SNAPSHOT";
                    string pomFilePath = applicationObject.Solution.FileName.Substring(0, applicationObject.Solution.FileName.LastIndexOf("\\"));
                    pomFilePath += "\\pom.xml";
                    if (File.Exists(pomFilePath))
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(pomFilePath);
                        System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(doc.NameTable);
                        xmlnsManager.AddNamespace("pom", "http://maven.apache.org/POM/4.0.0");
                        XmlNode node = doc.SelectSingleNode("/pom:project/pom:scm/pom:developerConnection", xmlnsManager);
                        if (node != null)
                        {
                            scmTag = node.InnerText;
                        }
                        node = doc.SelectSingleNode("/pom:project/pom:version", xmlnsManager);
                        if (node != null)
                        {
                            version = node.InnerText;
                        }
                    }

                    if (!string.IsNullOrEmpty(scmTag))
                    {
                        txtSCMTag.Text = scmTag;
                    }

                    txtVersion.Text = version;

                    // TODO: remember this, or have a default
                    useMsDeployCheckBox.Checked = true;
                }
                catch { /*do nothing*/ }
            }
        }
Exemplo n.º 43
0
        private static XmlElement getSignatureNode(XmlDocument doc)
        {
            XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(doc.NameTable);

            xmlnsManager.AddNamespace("bk", "http://www.w3.org/2000/09/xmldsig#");

            var node = doc.SelectSingleNode("/*/bk:Signature", xmlnsManager);

            return((XmlElement)node);
        }
 public static void AddSpecificGenericNamespace(string prefix, System.Xml.XmlNamespaceManager nmsMng)
 {
     try
     {
         nmsMng.AddNamespace(prefix, "http://www.SDMX.org/resources/SDMXML/schemas/v2_0/generic");
     }
     catch (Exception ex)
     {
         throw new Exception("Error, [Common.CommonNameSpace.AddSpecificGenericNamespace] " + ex.Message);
     }
 }
        private static XmlNamespaceManager ConstructEnterpriseLibraryNamespaceManager()
        {
            System.Xml.NameTable nameTable = new System.Xml.NameTable();

            System.Xml.XmlNamespaceManager namespaceManager = new System.Xml.XmlNamespaceManager(nameTable);
            string enterpriseLibraryNamespace = "http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/configuration";

            namespaceManager.AddNamespace("el", enterpriseLibraryNamespace);

            return(namespaceManager);
        }
Exemplo n.º 46
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);
        }
Exemplo n.º 47
0
        private void ParseContainer()
        {
            var containerFile = epubFolderLocation + "/META-INF/container.xml";

            XmlDocument doc = new XmlDocument();

            doc.Load(containerFile);

            var xmlnsManager = new System.Xml.XmlNamespaceManager(doc.NameTable);

            xmlnsManager.AddNamespace("ns", "urn:oasis:names:tc:opendocument:xmlns:container");

            XmlNodeList rootFiles = doc.SelectNodes("/ns:container/ns:rootfiles/ns:rootfile", xmlnsManager);

            opfFileString = rootFiles[0].Attributes ["full-path"].InnerText;
        }
Exemplo n.º 48
0
        static public System.Xml.XmlDocument set_todoc(System.Data.DataTable dt)
        {
            // salvo xml
            System.Xml.XmlDocument docSet       = new System.Xml.XmlDocument();
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            DataSet ds = new DataSet(); ds.Tables.Add(dt);

            ds.WriteXml(new System.Xml.XmlTextWriter(stringWriter), System.Data.XmlWriteMode.WriteSchema);
            docSet.LoadXml(stringWriter.ToString());

            System.Xml.XmlNamespaceManager nm = new System.Xml.XmlNamespaceManager(docSet.NameTable);
            nm.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
            System.Xml.XmlNodeList fields = docSet.SelectNodes("/" + ds.DataSetName + "/xs:schema//xs:element[@name='" + ds.Tables[0].TableName
                                                               + "']/xs:complexType/xs:sequence/xs:element", nm);
            if (fields == null || fields.Count == 0)
            {
                return(null);
            }

            // costruzione xsl
            System.Xml.Xsl.XslCompiledTransform xslDoc = new System.Xml.Xsl.XslCompiledTransform();
            string strXsl = "<?xml version='1.0'?>"
                            + "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"
                            + "<xsl:template match=\"/\">"
                            + " <rows schema='xmlschema.datatable'>"
                            + "  <xsl:for-each select=\"/" + ds.DataSetName + "/" + ds.Tables[0].TableName + "\"><row>"
                            + string.Concat(fields.Cast <XmlNode>().Select(x =>
                                                                           string.Format("  <{0}><xsl:value-of select=\"{0}\"/></{0}>", x.Attributes["name"].Value)))
                            + "  </row></xsl:for-each>"
                            + " </rows></xsl:template></xsl:stylesheet>";

            System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new System.IO.StringReader(strXsl));
            xslDoc.Load(reader);

            // trasformazione xml
            System.Xml.XmlDocument docResult = new System.Xml.XmlDocument();
            System.IO.StringWriter xmlText   = new System.IO.StringWriter();
            xslDoc.Transform(docSet, System.Xml.XmlWriter.Create(xmlText));
            //System.Text.Encoding e = xslDoc.OutputSettings.Encoding;

            docResult.LoadXml(xmlText.ToString());

            return(docResult);
        }
Exemplo n.º 49
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 ? ":" : ""));
            }
        }
Exemplo n.º 50
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);
            }
        }
        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);
        }
 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);
     }
 }
Exemplo n.º 53
0
        public string GetListData(object count)
        {
            /*Declare and initialize a variable for the Lists Web service.*/
            Web_Reference.Lists listService = new Web_Reference.Lists();

            /*Authenticate the current user by passing their default
             * credentials to the Web service from the system credential cache.*/
            listService.Credentials =
                System.Net.CredentialCache.DefaultCredentials;

            /*Set the Url property of the service for the path to a subsite.*/
            listService.Url =
                "http://spwfedevv002:6907/sites/Importad/_vti_bin/lists.asmx";

            // Instantiate an XmlDocument object
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

            /* Assign values to the string parameters of the GetListItems method, using GUIDs for the listName and viewName variables. For listName, using the list display name will also work, but using the list GUID is recommended. For viewName, only the view GUID can be used. Using an empty string for viewName causes the default view
             * to be used.*/
            string listName = "{6C3EEF09-72D7-4BBD-857E-3E368DCB5859}";
            string viewName = "{062B24E9-C4BD-4B2D-8550-3529394970D2}";
            string rowLimit = "150";

            /*Use the CreateElement method of the document object to create elements for the parameters that use XML.*/
            System.Xml.XmlElement query      = xmlDoc.CreateElement("Query");
            System.Xml.XmlElement viewFields =
                xmlDoc.CreateElement("ViewFields");
            System.Xml.XmlElement queryOptions =
                xmlDoc.CreateElement("QueryOptions");

            /*To specify values for the parameter elements (optional), assign CAML fragments to the InnerXml property of each element.*/
            query.InnerXml        = "<Where></Where>";
            viewFields.InnerXml   = "<FieldRef Name=\"Title\" />";
            queryOptions.InnerXml = "";

            /* Declare an XmlNode object and initialize it with the XML response from the GetListItems method. The last parameter specifies the GUID of the Web site containing the list. Setting it to null causes the Web site specified by the Url property to be used.*/
            System.Xml.XmlNode Result =
                listService.GetListItems
                    (listName, viewName, query, viewFields, rowLimit, queryOptions, null);

            /*Loop through each node in the XML response and display each item.*/


            XmlDocument NewxmlDoc = new XmlDocument();

            string ListItemsNamespacePrefix = "z";
            string ListItemsNamespaceURI    = "#RowsetSchema";

            string PictureLibrariesNamespacePrefix = "s";
            string PictureLibrariesNamespaceURI    = "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882";

            string WebPartsNamespacePrefix = "dt";
            string WebPartsNamespaceURI    = "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882";

            string DirectoryNamespacePrefix = "rs";
            string DirectoryNamespaceURI    = "urn:schemas-microsoft-com:rowset";

            //now associate with the xmlns namespaces (part of all XML nodes returned
            //from SharePoint) a namespace prefix which we can then use in the queries
            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(NewxmlDoc.NameTable);

            nsmgr.AddNamespace(ListItemsNamespacePrefix, ListItemsNamespaceURI);
            nsmgr.AddNamespace(PictureLibrariesNamespacePrefix, PictureLibrariesNamespaceURI);
            nsmgr.AddNamespace(WebPartsNamespacePrefix, WebPartsNamespaceURI);
            nsmgr.AddNamespace(DirectoryNamespacePrefix, DirectoryNamespaceURI);


            XmlNodeList nodeList = Result.SelectNodes("//z:row", nsmgr);


            int test = 1;

            foreach (XmlNode node in nodeList)
            {
                StatusValue += test.ToString() + '-' + node.Attributes["ows_Title"].InnerText;
                test++;
            }

            return(StatusValue);
        }
Exemplo n.º 54
0
        public static void MyXml1(string fileName, string ansStr)
        {
            string[] myPathArr = fileName.Split('\\');
            string   myPath    = string.Join("\\", myPathArr, 0, myPathArr.Length - 1);
            //将docx转为zip
            string dfileName = System.IO.Path.ChangeExtension(fileName, ".zip");

            if (File.Exists(dfileName))
            {
                File.Delete(dfileName);
            }
            File.Move(fileName, dfileName);
            //解压
            string err = "error";

            UPZipFile(dfileName, myPath + "\\aa", ref err);

            XmlDocument xmldoc = new XmlDocument();

            xmldoc.Load(myPath + "\\aa\\word\\document.xml");

            System.Xml.XmlNamespaceManager m = new System.Xml.XmlNamespaceManager(xmldoc.NameTable);
            XmlNode rootDoc = xmldoc.ChildNodes[1];//获取根节点

            //添加命名空间
            for (int i = 0; i < rootDoc.Attributes.Count; i++)
            {
                m.AddNamespace(rootDoc.Attributes[i].LocalName, rootDoc.Attributes[i].Value);
            }

            string         myXmlStr  = "";
            string         myHtmlStr = "";
            IList <string> list      = new List <string>();
            List <string>  list1     = new List <string>();

            foreach (XmlNode xml in xmldoc.SelectNodes("/w:document/w:body/w:p", m))
            {
                string text = xml.InnerText;

                myHtmlStr += ParagraphsHandler(xml, m, myPath);


                XmlNode xmlSibling = xml.NextSibling;

                myXmlStr += "<w:p>" + xml.InnerXml + "</w:p>";
                if (xmlSibling != null && xmlSibling.Name == "w:tbl")
                {
                    //处理表格
                    string tabStr = "<table  border=\"1\" cellspacing=\"0\" cellpadding=\"0\" style=\"text-align:center\"> ";
                    foreach (XmlNode tr in xmlSibling.SelectNodes("./w:tr", m))
                    {
                        tabStr += "<tr>";
                        foreach (XmlNode td in tr.SelectNodes("./w:tc", m))
                        {
                            tabStr += "<td>";
                            foreach (XmlNode tdStr in td.SelectNodes("./w:p", m))
                            {
                                tabStr += ParagraphsHandler(tdStr, m, myPath);
                            }
                            tabStr += "</td>";
                        }
                        tabStr += "</tr>";
                    }
                    tabStr    += "</table>";
                    myHtmlStr += tabStr;
                    myXmlStr  += "<w:tbl>" + xmlSibling.InnerXml + "</w:tbl>";
                }
                if (text.IndexOf("【类型】") != -1)
                {
                    list.Add(myXmlStr);
                    list1.Add(myHtmlStr);
                    myXmlStr  = "";
                    myHtmlStr = "";
                }
            }
            string[] aaaa = list1.ToArray();
            string   bbb  = String.Join("", aaaa);
            //Directory.Delete(myPath + "\\aa", true);
            int count = list.Count;
        }
Exemplo n.º 55
0
        List <PointLatLng> GetRoutePoints(string url)
        {
            List <PointLatLng> points = null;

            try
            {
                string route = GMaps.Instance.UseRouteCache ? Cache.Instance.GetContent(url, CacheType.RouteCache) : string.Empty;
                if (string.IsNullOrEmpty(route))
                {
                    route = GetContentUsingHttp(url);
                    if (!string.IsNullOrEmpty(route))
                    {
                        if (GMaps.Instance.UseRouteCache)
                        {
                            Cache.Instance.SaveContent(url, CacheType.RouteCache, 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)
                    {
                        points = 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);
                            points.Add(new PointLatLng(lat, lng));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetRoutePoints: " + ex);
            }

            return(points);
        }
Exemplo n.º 56
0
        /**
         * Save relationships into the part.
         *
         * @param rels
         *            The relationships collection to marshall.
         * @param relPartName
         *            Part name of the relationship part to marshall.
         * @param zos
         *            Zip output stream in which to save the XML content of the
         *            relationships serialization.
         */
        public static bool MarshallRelationshipPart(
            PackageRelationshipCollection rels, PackagePartName relPartName,
            ZipOutputStream zos)
        {
            // Building xml
            XmlDocument xmlOutDoc = new XmlDocument();

            // make something like <Relationships
            // xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
            System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmlOutDoc.NameTable);
            xmlnsManager.AddNamespace("x", PackageNamespaces.RELATIONSHIPS);

            XmlNode root = xmlOutDoc.AppendChild(xmlOutDoc.CreateElement(PackageRelationship.RELATIONSHIPS_TAG_NAME, PackageNamespaces.RELATIONSHIPS));

            // <Relationship
            // TargetMode="External"
            // Id="rIdx"
            // Target="http://www.custom.com/images/pic1.jpg"
            // Type="http://www.custom.com/external-resource"/>

            Uri sourcePartURI = PackagingUriHelper
                                .GetSourcePartUriFromRelationshipPartUri(relPartName.URI);

            foreach (PackageRelationship rel in rels)
            {
                // the relationship element
                XmlElement relElem = xmlOutDoc.CreateElement(PackageRelationship.RELATIONSHIP_TAG_NAME, PackageNamespaces.RELATIONSHIPS);

                // the relationship ID
                relElem.SetAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel.Id);

                // the relationship Type
                relElem.SetAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel
                                     .RelationshipType);

                // the relationship Target
                String targetValue;
                Uri    uri = rel.TargetUri;
                if (rel.TargetMode == TargetMode.External)
                {
                    // Save the target as-is - we don't need to validate it,
                    //  alter it etc
                    targetValue = uri.OriginalString;

                    // add TargetMode attribute (as it is external link external)
                    relElem.SetAttribute(
                        PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME,
                        "External");
                }
                else
                {
                    targetValue = PackagingUriHelper.RelativizeUri(
                        sourcePartURI, rel.TargetUri, true).ToString();
                }
                relElem.SetAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME,
                                     targetValue);
                xmlOutDoc.DocumentElement.AppendChild(relElem);
            }

            xmlOutDoc.Normalize();

            // String schemaFilename = Configuration.getPathForXmlSchema()+
            // File.separator + "opc-relationships.xsd";

            // Save part in zip
            ZipEntry ctEntry = new ZipEntry(ZipHelper.GetZipURIFromOPCName(
                                                relPartName.URI.ToString()).OriginalString);

            try
            {
                zos.PutNextEntry(ctEntry);

                StreamHelper.SaveXmlInStream(xmlOutDoc, zos);
                zos.CloseEntry();
            }
            catch (IOException e)
            {
                logger.Log(POILogger.ERROR, "Cannot create zip entry " + relPartName, e);
                return(false);
            }
            return(true); // success
        }
Exemplo n.º 57
0
        public static void MyXml(string fileName, string ansStr)
        {
            string[] myPathArr = fileName.Split('\\');
            string   myPath    = string.Join("\\", myPathArr, 0, myPathArr.Length - 1);
            //将docx转为zip
            string dfileName = System.IO.Path.ChangeExtension(fileName, ".zip");

            if (File.Exists(dfileName))
            {
                File.Delete(dfileName);
            }
            File.Move(fileName, dfileName);
            //解压
            string err = "error";

            UPZipFile(dfileName, myPath + "\\aa", ref err);

            XmlDocument xmldoc = new XmlDocument();

            xmldoc.Load(myPath + "\\aa\\word\\document.xml");

            System.Xml.XmlNamespaceManager m = new System.Xml.XmlNamespaceManager(xmldoc.NameTable);
            m.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            m.AddNamespace("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
            m.AddNamespace("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            m.AddNamespace("o", "urn:schemas-microsoft-com:office:office");
            m.AddNamespace("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            m.AddNamespace("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            m.AddNamespace("v", "urn:schemas-microsoft-com:vml");
            m.AddNamespace("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
            m.AddNamespace("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            m.AddNamespace("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
            m.AddNamespace("w10", "urn:schemas-microsoft-com:office:word");
            m.AddNamespace("w15", "http://schemas.microsoft.com/office/word/2012/wordml");
            m.AddNamespace("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
            m.AddNamespace("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
            m.AddNamespace("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
            m.AddNamespace("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
            m.AddNamespace("wpsCustomData", "http://www.wps.cn/officeDocument/2013/wpsCustomData");

            string         myXmlStr = "";
            IList <string> list     = new List <string>();
            //XmlNode xn = xmldoc.SelectSingleNode("/w:document", m);
            //string attribute = xn.Attributes["xmlns"].Value;
            string TH    = "";
            int    count = 0;

            foreach (XmlNode xml in xmldoc.SelectNodes("/w:document/w:body/w:p", m))
            {
                string  text       = xml.InnerText;
                XmlNode xmlSibling = xml.NextSibling;
                if (text.IndexOf("【题号】") != -1)
                {
                    string th = text.Substring(4).Trim();
                    TH = th;
                    if (th.IndexOf("-") != -1)
                    {
                        string[] ths = th.Split('-');
                        count = int.Parse(ths[1]);
                        if (int.Parse(ths[1]) <= ansStr.Length)
                        {
                            myXmlStr += "<w:p><w:r xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:t>【答案】</w:t></w:r></w:p>";
                            for (var i = int.Parse(ths[0]); i <= int.Parse(ths[1]); i++)
                            {
                                myXmlStr += "<w:p><w:r xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:t>(" + i + ")</w:t></w:r><w:r xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:rPr><w:rFonts w:hint=\"eastAsia\" /><w:lang w:val=\"en-US\" w:eastAsia=\"zh-CN\" /></w:rPr><w:t>" + ansStr[i - 1] + "</w:t></w:r></w:p>";
                            }
                        }
                    }
                    else
                    {
                        count = int.Parse(th);
                        if (int.Parse(th) <= ansStr.Length)
                        {
                            myXmlStr += "<w:p><w:pPr></w:pPr><w:r><w:t xml:space=\"preserve\">【答案】" + ansStr[int.Parse(th) - 1] + "</w:t></w:r></w:p>";
                        }
                    }
                    continue;
                }
                myXmlStr += "<w:p>" + xml.InnerXml + "</w:p>";
                if (xmlSibling.Name == "w:tbl")
                {
                    myXmlStr += "<w:tbl>" + xmlSibling.InnerXml + "</w:tbl>";
                }
                if (text.IndexOf("【类型】") != -1)
                {
                    if (TH.Length == 0)
                    {
                        count++;
                        TH = count + "";
                    }
                    myXmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?><w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:wpc=\"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:wp14=\"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" xmlns:w10=\"urn:schemas-microsoft-com:office:word\" xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\" xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\" xmlns:wpi=\"http://schemas.microsoft.com/office/word/2010/wordprocessingInk\" xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\" xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\" xmlns:wpsCustomData=\"http://www.wps.cn/officeDocument/2013/wpsCustomData\" mc:Ignorable=\"w14 w15 wp14\"><w:body> " + myXmlStr + " </w:body></w:document> ";

                    //拷贝一份解压后的源文件
                    string docxPath = myPath + "\\" + TH;
                    CopyDirectory(myPath + "\\aa", docxPath);
                    //File.Copy(myPath + "\\aa", docxPath, false);
                    //将xml字符串写进xml文档里
                    StringReader Reader  = new StringReader(myXmlStr);
                    XmlDocument  xmlDoc1 = new XmlDocument();
                    xmlDoc1.Load(Reader);
                    xmlDoc1.Save(docxPath + "\\word\\document.xml");
                    //压缩文件
                    string docxZip = myPath + "\\" + TH + ".zip";
                    Zip(docxPath, docxZip, ref err);
                    Directory.Delete(docxPath, true);
                    //zip --docx
                    string docxName = System.IO.Path.ChangeExtension(docxZip, ".docx");
                    if (File.Exists(docxName))
                    {
                        File.Delete(docxName);
                    }
                    File.Move(docxZip, docxName);
                    //File.Delete(dfileName);



                    list.Add(myXmlStr);
                    myXmlStr = "";
                    TH       = "";
                }
            }
            Directory.Delete(myPath + "\\aa", true);
        }
Exemplo n.º 58
0
        /// <summary>
        /// 处理段落
        /// </summary>
        /// <param name="xml">w:p节点</param>
        /// <param name="m">命名空间</param>
        /// <param name="myPath">源文件路径</param>
        /// <returns></returns>
        public static string ParagraphsHandler(XmlNode xml, System.Xml.XmlNamespaceManager m, string myPath)
        {
            string myHtmlStr = "<p>";

            foreach (XmlNode r in xml.SelectNodes("./w:r", m))
            {
                XmlNodeList rt       = r.SelectNodes("./w:t", m);      //取当前节点下的w:t
                XmlNodeList robject  = r.SelectNodes("./w:object", m); //取当前节点下的w:object
                XmlNodeList rdrawing = r.SelectNodes("./w:drawing", m);
                XmlNodeList rmc      = r.SelectNodes("./mc:AlternateContent", m);

                if (rt.Count > 0)
                {
                    myHtmlStr += rt[0].InnerText.Replace(" ", "&nbsp;");
                }
                //v:imagedata
                if (robject.Count > 0)
                {
                    foreach (XmlNode o in robject)
                    {
                        XmlNode     img       = o.SelectSingleNode(".//v:imagedata", m); //获取imagedata节点
                        var         rid       = img.Attributes["r:id"].Value;            //图片id
                        XmlDocument xmldocRel = new XmlDocument();
                        xmldocRel.Load(myPath + "\\aa\\word\\_rels\\document.xml.rels"); //加载关系文档
                        System.Xml.XmlNamespaceManager m1 = new System.Xml.XmlNamespaceManager(xmldocRel.NameTable);
                        m1.AddNamespace("ns", "http://schemas.openxmlformats.org/package/2006/relationships");
                        XmlNode imgxml  = xmldocRel.SelectSingleNode("/ns:Relationships/ns:Relationship[@Id='" + rid + "']", m1);
                        string  imgPath = imgxml.Attributes["Target"].Value;                    //相对路径
                        string  path    = myPath + "\\aa\\word\\" + imgPath.Replace("/", "\\"); //图片绝对路径
                        string  newPath = "";
                        if (imgPath.IndexOf(".wmf") != -1)
                        {
                            var im = Bitmap.FromFile(path);
                            newPath = path.Split('.')[0] + ".png";
                            im.Save(newPath, ImageFormat.Png);
                        }
                        else
                        {
                            newPath = path;
                        }

                        string strBase64 = GetBase64FromImage(newPath);
                        myHtmlStr += "<img src=\"data:image/png;base64," + strBase64 + "\">";
                    }
                }
                //a:blip
                if (rdrawing.Count > 0)
                {
                    foreach (XmlNode o in rdrawing)
                    {
                        XmlNode     img       = o.SelectSingleNode(".//a:blip", m);      //获取imagedata节点
                        var         rid       = img.Attributes["r:embed"].Value;         //图片id
                        XmlDocument xmldocRel = new XmlDocument();
                        xmldocRel.Load(myPath + "\\aa\\word\\_rels\\document.xml.rels"); //加载关系文档
                        System.Xml.XmlNamespaceManager m1 = new System.Xml.XmlNamespaceManager(xmldocRel.NameTable);
                        m1.AddNamespace("ns", "http://schemas.openxmlformats.org/package/2006/relationships");
                        XmlNode imgxml  = xmldocRel.SelectSingleNode("/ns:Relationships/ns:Relationship[@Id='" + rid + "']", m1);
                        string  imgPath = imgxml.Attributes["Target"].Value;                    //相对路径
                        string  path    = myPath + "\\aa\\word\\" + imgPath.Replace("/", "\\"); //图片绝对路径
                        string  newPath = "";
                        if (imgPath.IndexOf(".wmf") != -1)
                        {
                            var im = Bitmap.FromFile(path);
                            newPath = path.Split('.')[0] + ".png";
                            im.Save(newPath, ImageFormat.Png);
                        }
                        else
                        {
                            newPath = path;
                        }

                        string strBase64 = GetBase64FromImage(newPath);
                        myHtmlStr += "<img src=\"data:image/png;base64," + strBase64 + "\">";
                    }
                }
                if (rmc.Count > 0)
                {
                    foreach (XmlNode o in rmc)
                    {
                        XmlNodeList   imgs = o.SelectNodes(".//v:imagedata[@r:id]", m);
                        List <string> temp = new List <string>();
                        foreach (XmlNode img in imgs)
                        {
                            //XmlNode img = o.SelectSingleNode(".//v:imagedata[@r:id]", m);//获取imagedata节点
                            bool flag = false;

                            var rid = img.Attributes["r:id"].Value;//图片id
                            if (temp.Count > 0)
                            {
                                foreach (var t in temp)
                                {
                                    if (t == rid)
                                    {
                                        flag = true;
                                    }
                                }
                            }
                            if (flag)
                            {
                                continue;
                            }
                            temp.Add(rid);
                            XmlDocument xmldocRel = new XmlDocument();
                            xmldocRel.Load(myPath + "\\aa\\word\\_rels\\document.xml.rels");//加载关系文档
                            System.Xml.XmlNamespaceManager m1 = new System.Xml.XmlNamespaceManager(xmldocRel.NameTable);
                            m1.AddNamespace("ns", "http://schemas.openxmlformats.org/package/2006/relationships");
                            XmlNode imgxml  = xmldocRel.SelectSingleNode("/ns:Relationships/ns:Relationship[@Id='" + rid + "']", m1);
                            string  imgPath = imgxml.Attributes["Target"].Value;                    //相对路径
                            string  path    = myPath + "\\aa\\word\\" + imgPath.Replace("/", "\\"); //图片绝对路径
                            string  newPath = "";
                            if (imgPath.IndexOf(".wmf") != -1)
                            {
                                var im = Bitmap.FromFile(path);
                                newPath = path.Split('.')[0] + ".png";
                                im.Save(newPath, ImageFormat.Png);
                            }
                            else
                            {
                                newPath = path;
                            }

                            string strBase64 = GetBase64FromImage(newPath);
                            myHtmlStr += "<img src=\"data:image/png;base64," + strBase64 + "\">";
                        }
                    }
                }
            }

            myHtmlStr += "</p>";
            return(myHtmlStr);
        }
Exemplo n.º 59
0
 /// <summary>
 /// Create a new XmlNamespaceManager and fill it with all necessary namespaces and prefixes.
 /// </summary>
 /// <param name="nametable">The XmlNameTable of the TextDocument object XmlDocument.</param>
 /// <returns>The XmlNamespaceManager object.</returns>
 public static XmlNamespaceManager NameSpace(XmlNameTable nametable)
 {
     System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(nametable);
     xmlnsManager.AddNamespace("office", "urn:oasis:names:tc:opendocument:xmlns:office:1.0");
     xmlnsManager.AddNamespace("style", "urn:oasis:names:tc:opendocument:xmlns:style:1.0");
     xmlnsManager.AddNamespace("text", "urn:oasis:names:tc:opendocument:xmlns:text:1.0");
     xmlnsManager.AddNamespace("table", "urn:oasis:names:tc:opendocument:xmlns:table:1.0");
     xmlnsManager.AddNamespace("draw", "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0");
     xmlnsManager.AddNamespace("fo", "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0");
     xmlnsManager.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
     xmlnsManager.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
     xmlnsManager.AddNamespace("meta", "urn:oasis:names:tc:opendocument:xmlns:meta:1.0");
     xmlnsManager.AddNamespace("number", "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0");
     xmlnsManager.AddNamespace("svg", "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0");
     xmlnsManager.AddNamespace("dr3d", "urn:oasis:names:tc:opendocument:xmlns:chart:1.0");
     xmlnsManager.AddNamespace("math", "http://www.w3.org/1998/Math/MathML");
     xmlnsManager.AddNamespace("form", "urn:oasis:names:tc:opendocument:xmlns:form:1.0");
     xmlnsManager.AddNamespace("script", "urn:oasis:names:tc:opendocument:xmlns:script:1.0");
     xmlnsManager.AddNamespace("ooo", "http://openoffice.org/2004/office");
     xmlnsManager.AddNamespace("ooow", "http://openoffice.org/2004/writer");
     xmlnsManager.AddNamespace("oooc", "http://openoffice.org/2004/calc");
     xmlnsManager.AddNamespace("dom", "http://www.w3.org/2001/xml-events");
     xmlnsManager.AddNamespace("xforms", "http://www.w3.org/2002/xforms");
     xmlnsManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
     xmlnsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
     return(xmlnsManager);
 }
Exemplo n.º 60
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);
        }