Ejemplo n.º 1
0
        public System.Collections.Generic.IEnumerable<Table> ListTables(string xmsclientrequestId = null)
        {
            List<Table> lTables = new List<Table>();

            string strResult = Internal.InternalMethods.QueryTables(AccountName, SharedKey, UseHTTPS, xmsclientrequestId);

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            using (System.Xml.XmlReader re = System.Xml.XmlReader.Create(new System.IO.StringReader(strResult)))
            {
                doc.Load(re);
            }
            System.Xml.XmlNamespaceManager man = new System.Xml.XmlNamespaceManager(doc.NameTable);
            man.AddNamespace("f", "http://www.w3.org/2005/Atom");
            man.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
            man.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");

            foreach (System.Xml.XmlNode n in doc.SelectNodes("//f:feed/f:entry", man))
            {
                yield return new Table()
                {
                    AzureTableService = this,
                    Url = new Uri(n.SelectSingleNode("f:id", man).InnerText),
                    Name = n.SelectSingleNode("f:content/m:properties/d:TableName", man).InnerText
                };

            }
        }
Ejemplo n.º 2
0
 PdfFormatter()
 {
     NestingPoint = "fo:flow[@flow-name='xsl-region-body']/fo:block";
     nsmgr        = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
     nsmgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
     nsmgr.AddNamespace("fo", "http://www.w3.org/1999/XSL/Format");
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Get currency exchange rate in euro's
        /// </summary>
        public static float GetCurrencyRateInEuro(string currency)
        {
            if (currency.ToLower() == "")
            {
                throw new ArgumentException("Invalid Argument! Currency parameter cannot be empty!");
            }

            if (currency.ToLower() == "eur")
            {
                throw new ArgumentException("Invalid Argument! Cannot get exchange rate from EURO to EURO");
            }

            try
            {
                // Create with currency parameter, a valid RSS url to ECB euro exchange rate feed
                string rssUrl = string.Concat("http://www.ecb.int/rss/fxref-", currency.ToLower() + ".html");

                // Create & Load New Xml Document
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(rssUrl);

                // Create XmlNamespaceManager for handling XML namespaces.
                System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("rdf", "http://purl.org/rss/1.0/");
                nsmgr.AddNamespace("cb", "http://www.cbwiki.net/wiki/index.php/Specification_1.1");

                // Get list of daily currency exchange rate between selected "currency" and the EURO
                System.Xml.XmlNodeList nodeList = doc.SelectNodes("//rdf:item", nsmgr);

                // Loop Through all XMLNODES with daily exchange rates
                foreach (System.Xml.XmlNode node in nodeList)
                {
                    // Create a CultureInfo, this is because EU and USA use different sepperators in float (, or .)
                    CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
                    ci.NumberFormat.CurrencyDecimalSeparator = ".";

                    try
                    {
                        // Get currency exchange rate with EURO from XMLNODE
                        float exchangeRate = float.Parse(
                            node.SelectSingleNode("//cb:statistics//cb:exchangeRate//cb:value", nsmgr).InnerText,
                            NumberStyles.Any,
                            ci);

                        return(exchangeRate);
                    }
                    catch { }
                }

                // currency not parsed!!
                // return default value
                return(0);
            }
            catch
            {
                // currency not parsed!!
                // return default value
                return(0);
            }
        }
        public System.Collections.Generic.IEnumerable <Table> ListTables(string xmsclientrequestId = null)
        {
            List <Table> lTables = new List <Table>();

            string strResult = Internal.InternalMethods.QueryTables(AccountName, SharedKey, UseHTTPS, xmsclientrequestId);

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            using (System.Xml.XmlReader re = System.Xml.XmlReader.Create(new System.IO.StringReader(strResult)))
            {
                doc.Load(re);
            }
            System.Xml.XmlNamespaceManager man = new System.Xml.XmlNamespaceManager(doc.NameTable);
            man.AddNamespace("f", "http://www.w3.org/2005/Atom");
            man.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
            man.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");

            foreach (System.Xml.XmlNode n in doc.SelectNodes("//f:feed/f:entry", man))
            {
                yield return(new Table()
                {
                    AzureTableService = this,
                    Url = new Uri(n.SelectSingleNode("f:id", man).InnerText),
                    Name = n.SelectSingleNode("f:content/m:properties/d:TableName", man).InnerText
                });
            }
        }
Ejemplo n.º 5
0
        private static System.Xml.XmlNamespaceManager GetReportNamespaceManager(System.Xml.XmlDocument doc)
        {
            if (doc == null)
            {
                throw new System.ArgumentNullException(nameof(doc));
            }

            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(doc.NameTable);

            // <Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">

            if (doc.DocumentElement != null)
            {
                // string strNamespace = doc.DocumentElement.NamespaceURI;
                // System.Console.WriteLine(strNamespace);
                // nsmgr.AddNamespace("dft", strNamespace);

                System.Xml.XPath.XPathNavigator xNav = doc.CreateNavigator();
                while (xNav.MoveToFollowing(System.Xml.XPath.XPathNodeType.Element))
                {
                    System.Collections.Generic.IDictionary <string, string> localNamespaces = xNav.GetNamespacesInScope(System.Xml.XmlNamespaceScope.Local);

                    foreach (System.Collections.Generic.KeyValuePair <string, string> kvp in localNamespaces)
                    {
                        string prefix = kvp.Key;
                        if (string.IsNullOrEmpty(prefix))
                        {
                            prefix = "dft";
                        }

                        nsmgr.AddNamespace(prefix, kvp.Value);
                    } // Next kvp
                }     // Whend



                //System.Xml.XmlNodeList _xmlNameSpaceList = doc.SelectNodes(@"//namespace::*[not(. = ../../namespace::*)]");

                //foreach (System.Xml.XmlNode currentNamespace in _xmlNameSpaceList)
                //{
                //    if (StringComparer.InvariantCultureIgnoreCase.Equals(currentNamespace.LocalName, "xmlns"))
                //    {
                //        nsmgr.AddNamespace("dft", currentNamespace.Value);
                //    }
                //    else
                //        nsmgr.AddNamespace(currentNamespace.LocalName, currentNamespace.Value);

                //}

                return(nsmgr);
            } // End if (doc.DocumentElement != null)

            nsmgr.AddNamespace("dft", "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");
            // nsmgr.AddNamespace("dft", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition");

            return(nsmgr);
        } // End Function GetReportNamespaceManager
Ejemplo n.º 6
0
        internal List <TableEntity> _QueryInternal(
            string NextPartitionKey,
            string NextRowKey,
            out string continuationNextPartitionKey,
            out string continuationNextRowKey,
            string xmsclientrequestId = null)
        {
            List <TableEntity> lEntities = new List <TableEntity>();

            string res = ITPCfSQL.Azure.Internal.InternalMethods.QueryTable(
                AzureTableService.UseHTTPS, AzureTableService.SharedKey, AzureTableService.AccountName, this.Name,
                NextPartitionKey, NextRowKey,
                out continuationNextPartitionKey, out continuationNextRowKey,
                xmsclientrequestId);

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            using (System.IO.StringReader sr = new System.IO.StringReader(res))
            {
                using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(sr))
                {
                    doc.Load(reader);
                }
            }

            System.Xml.XmlNamespaceManager man = new System.Xml.XmlNamespaceManager(doc.NameTable);
            man.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
            man.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
            man.AddNamespace("f", "http://www.w3.org/2005/Atom");


            foreach (System.Xml.XmlNode node in doc.SelectNodes("f:feed/f:entry", man))
            {
                System.Xml.XmlNode nCont      = node.SelectSingleNode("f:content/m:properties", man);
                System.Xml.XmlNode nTimeStamp = nCont.SelectSingleNode("d:Timestamp", man);
                TableEntity        te         = new TableEntity()
                {
                    PartitionKey = nCont.SelectSingleNode("d:PartitionKey", man).InnerText,
                    RowKey       = nCont.SelectSingleNode("d:RowKey", man).InnerText,
                    TimeStamp    = DateTime.Parse(nTimeStamp.InnerText)
                };

                // custom attrib handling
                System.Xml.XmlNode nFollow = nTimeStamp.NextSibling;
                while (nFollow != null)
                {
                    te.Attributes[nFollow.LocalName] = nFollow.InnerText;
                    nFollow = nFollow.NextSibling;
                }

                lEntities.Add(te);
            }
            return(lEntities);
        }
Ejemplo n.º 7
0
        public void Valid_UniqueIdentifiers()
        {
            var xDoc = System.Xml.Linq.XDocument.Parse
                       (
                Resources.ContentValidation.UniqueValidator.Valid.UniqueIdentifiers,
                System.Xml.Linq.LoadOptions.SetLineInfo
                       );

            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
            nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
            nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            XCRI.Validation.ContentValidation.UniqueValidator v = new XCRI.Validation.ContentValidation.UniqueValidator()
            {
                XPathSelector    = "//dc:identifier[not(@xsi:type)]",
                NamespaceManager = nsmgr
            };
            var vrc = v.Validate(xDoc.Root);

            Assert.AreEqual <int>(1, vrc.Count());
            var vr = vrc.ElementAt(0);

            Assert.IsNotNull(vr);
            Assert.AreEqual <XCRI.Validation.ContentValidation.ValidationStatus>
            (
                XCRI.Validation.ContentValidation.ValidationStatus.Passed,
                vr.Status
            );

            /*
             * Assert.AreEqual<int>
             *  (
             *  2,
             *  vr.Count
             *  );
             * Assert.AreEqual<int>
             *  (
             *  2,
             *  vr.SuccessCount
             *  );
             */
            Assert.AreEqual <int>
            (
                0,
                vr.FailedCount
            );
            Assert.AreEqual <int>
            (
                0,
                vr.Count
            );
        }
        public void Invalid_NotUniqueIdentifiers()
        {
            var xDoc = System.Xml.Linq.XDocument.Parse
                       (
                Resources.ContentValidation.UniqueValidator.Invalid.NotUnique,
                System.Xml.Linq.LoadOptions.SetLineInfo
                       );

            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
            nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
            nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            XCRI.Validation.ContentValidation.UniqueValidator v = new XCRI.Validation.ContentValidation.UniqueValidator()
            {
                XPathSelector    = "//dc:identifier[not(@xsi:type)]",
                NamespaceManager = nsmgr
            };
            var vrc = v.Validate(xDoc.Root);

            Assert.AreEqual <int>(1, vrc.Count());
            var vr = vrc.ElementAt(0);

            Assert.IsNotNull(vr);
            Assert.AreEqual <XCRI.Validation.ContentValidation.ValidationStatus>
            (
                XCRI.Validation.ContentValidation.ValidationStatus.Exception,
                vr.Status
            );
            Assert.AreEqual <int>
            (
                2,
                vr.Count
            );
            Assert.AreEqual <int>
            (
                0,
                vr.SuccessCount
            );
            Assert.AreEqual <int>
            (
                2,
                vr.FailedCount
            );
            Assert.IsTrue(vr.Instances[0].LineNumber.HasValue);
            Assert.IsTrue(vr.Instances[0].LinePosition.HasValue);
            Assert.AreEqual <int>(vr.Instances[0].LineNumber.Value, 11);
            Assert.AreEqual <int>(vr.Instances[0].LinePosition.Value, 8);
            Assert.IsTrue(vr.Instances[1].LineNumber.HasValue);
            Assert.IsTrue(vr.Instances[1].LinePosition.HasValue);
            Assert.AreEqual <int>(vr.Instances[1].LineNumber.Value, 15);
            Assert.AreEqual <int>(vr.Instances[1].LinePosition.Value, 8);
        }
 public void Invalid_NotUniqueIdentifiers()
 {
     var xDoc = System.Xml.Linq.XDocument.Parse
         (
         Resources.ContentValidation.UniqueValidator.Invalid.NotUnique,
         System.Xml.Linq.LoadOptions.SetLineInfo
         );
     System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
     nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
     nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
     XCRI.Validation.ContentValidation.UniqueValidator v = new XCRI.Validation.ContentValidation.UniqueValidator()
     {
         XPathSelector = "//dc:identifier[not(@xsi:type)]",
         NamespaceManager = nsmgr
     };
     var vrc = v.Validate(xDoc.Root);
     Assert.AreEqual<int>(1, vrc.Count());
     var vr = vrc.ElementAt(0);
     Assert.IsNotNull(vr);
     Assert.AreEqual<XCRI.Validation.ContentValidation.ValidationStatus>
         (
         XCRI.Validation.ContentValidation.ValidationStatus.Exception,
         vr.Status
         );
     Assert.AreEqual<int>
         (
         2,
         vr.Count
         );
     Assert.AreEqual<int>
         (
         0,
         vr.SuccessCount
         );
     Assert.AreEqual<int>
         (
         2,
         vr.FailedCount
         );
     Assert.IsTrue(vr.Instances[0].LineNumber.HasValue);
     Assert.IsTrue(vr.Instances[0].LinePosition.HasValue);
     Assert.AreEqual<int>(vr.Instances[0].LineNumber.Value, 11);
     Assert.AreEqual<int>(vr.Instances[0].LinePosition.Value, 8);
     Assert.IsTrue(vr.Instances[1].LineNumber.HasValue);
     Assert.IsTrue(vr.Instances[1].LinePosition.HasValue);
     Assert.AreEqual<int>(vr.Instances[1].LineNumber.Value, 15);
     Assert.AreEqual<int>(vr.Instances[1].LinePosition.Value, 8);
 }
Ejemplo n.º 10
0
        public static Dictionary <string, string> ParseParams(string paramString, IEventAggregator eventAggregator)
        {
            var d = new Dictionary <string, string>();

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            try
            {
                doc.LoadXml(paramString);
                var nsMgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
                nsMgr.AddNamespace("x", "urn:schemas-microsoft-com:xml-analysis");
                foreach (System.Xml.XmlNode n in doc.SelectNodes("/x:Parameters/x:Parameter", nsMgr))
                {
                    d.Add(n["Name"].InnerText, n["Value"].InnerText);
                }

                // if we did not find the proper namespace try searching for just the raw names
                if (d.Count == 0)
                {
                    foreach (System.Xml.XmlNode n in doc.SelectNodes("/Parameters/Parameter", nsMgr))
                    {
                        d.Add(n["Name"].InnerText, n["Value"].InnerText);
                    }
                }
            } catch (Exception ex)
            {
                Log.Error(ex, "{class} {method} Error merging query parameters", "DaxHelper", "ParseParams");
                eventAggregator.PublishOnUIThread(new OutputMessage(MessageType.Error, "The Following Error occurred while trying to parse a parameter block: " + ex.Message));
            }
            return(d);
        }
Ejemplo n.º 11
0
        public Record Get(string url)
        {
            var record = new Record();

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.KeepAlive = false;
                request.Method    = "GET";

                var r    = request.GetResponse();
                var xDoc = new System.Xml.XmlDocument();
                xDoc.Load(r.GetResponseStream());

                var ns = new System.Xml.XmlNamespaceManager(xDoc.NameTable);
                ns.AddNamespace("rcrd", "http://beacon.nist.gov/record/0.1/");
                var recordNode = xDoc.SelectSingleNode("/rcrd:record", ns);

                record.Version             = GetElmStr(recordNode, ns, "version");
                record.Frequency           = GetElmInt(recordNode, ns, "frequency");
                record.TimeStamp           = GetElmLong(recordNode, ns, "timeStamp");
                record.SeedValue           = GetElmStr(recordNode, ns, "seedValue");
                record.PreviousOutputValue = GetElmStr(recordNode, ns, "previousOutputValue");
                record.SignatureValue      = GetElmStr(recordNode, ns, "signatureValue");
                record.OutputValue         = GetElmStr(recordNode, ns, "outputValue");

                record.StatusCode = GetElmStr(recordNode, ns, "statusCode");
            }
            catch (Exception)
            {
            }


            return(record);
        }
Ejemplo n.º 12
0
        //pass in a marcxml record and return
        //the record id if present
        public string GetRecordId(string xml, string field, string subfield)
        {
            string xpath = "";

            try
            {
                if (xml.IndexOf("marc:collection") > -1)
                {
                    xpath = "/marc:collection/marc:record/marc:datafield[@tag='" + field + "']";
                }
                else
                {
                    xpath = "/marc:record/marc:datafield[@tag='" + field + "']";
                }

                System.Xml.XmlDocument         objXML = new System.Xml.XmlDocument();
                System.Xml.XmlNamespaceManager ns     = new System.Xml.XmlNamespaceManager(objXML.NameTable);
                ns.AddNamespace("marc", "http://www.loc.gov/MARC21/slim");

                System.Xml.XmlNode objNode;
                System.Xml.XmlNode objSubfield;
                objXML.LoadXml(xml);
                objNode     = objXML.SelectSingleNode(xpath, ns);
                objNode     = objXML.SelectSingleNode(xpath, ns);
                objSubfield = objNode.SelectSingleNode("marc:subfield[@code='" + subfield + "']", ns);
                return(objSubfield.InnerText);
            }
            catch (System.Exception xe)
            {
                perror_message += xe.ToString();
                return("");
            }
        }
        public static System.IO.Stream CreateNewSolution(System.Xml.XmlNode nodeDirective, string rootSourceName, string slnFile, string SkipDirectories, string EmptyDirectories, string basePath)
        {
            // The memory stream will be returned empty as this is a self
            // contained process and nothing is output
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            string rootTargetName;

            string[] emptyDirArray;
            System.Xml.XmlNamespaceManager nsmgr         = new System.Xml.XmlNamespaceManager(nodeDirective.OwnerDocument.NameTable);
            System.Xml.XmlNode             nodeFilePaths = Generation.GetFilePathNode();
            nsmgr.AddNamespace("kg", "http://kadgen.com/KADGenDriving.xsd");
            System.IO.DirectoryInfo dirSourceRoot;
            System.IO.DirectoryInfo dirTargetRoot;
            rootTargetName = Utility.Tools.GetAttributeOrEmpty(nodeDirective, "kg:SinglePass", "OutputFile", nsmgr);
            rootTargetName = Utility.Tools.FixPath(rootTargetName, basePath, null, nodeFilePaths);
            dirSourceRoot  = new System.IO.DirectoryInfo(rootSourceName);
            dirTargetRoot  = new System.IO.DirectoryInfo(rootTargetName);

            emptyDirArray = SplitToArray(EmptyDirectories);
            BuildDirectoryStructure(dirSourceRoot, dirTargetRoot, SplitToArray(SkipDirectories), emptyDirArray);

            if (slnFile.IndexOf(@"\") < 0)
            {
                slnFile = rootSourceName + @"\" + slnFile;
            }

            UpdateProjectAndSolution(slnFile, rootSourceName, rootTargetName, emptyDirArray);

            return(stream);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// 从HTML读取器中加载对象数据
 /// </summary>
 /// <param name="myReader"></param>
 /// <returns></returns>
 internal override bool InnerRead(HTMLTextReader myReader)
 {
     strLoadErrorMsg = null;
     strSourceXML    = myReader.ReadToEndTag(this.TagName);
     try
     {
         myXMLDocument.RemoveAll();
         System.Xml.XmlNamespaceManager nsm = new System.Xml.XmlNamespaceManager(myXMLDocument.NameTable);
         foreach (HTMLAttribute attr in myOwnerDocument.Attributes)
         {
             string vName = attr.Name;
             if (vName.ToLower().StartsWith(StringConstAttributeName.XMLNS))
             {
                 int index = vName.IndexOf(":");
                 if (index > 0)
                 {
                     string NsName = vName.Substring(index + 1);
                     nsm.AddNamespace(NsName, attr.Value);
                 }
             }
         }
         System.Xml.XmlParserContext pc          = new System.Xml.XmlParserContext(myXMLDocument.NameTable, nsm, null, System.Xml.XmlSpace.None);
         System.Xml.XmlTextReader    myXMLReader = new System.Xml.XmlTextReader(strSourceXML, System.Xml.XmlNodeType.Element, pc);
         myXMLDocument.Load(myXMLReader);
         myXMLReader.Close();
     }
     catch (Exception ext)
     {
         myXMLDocument.RemoveAll();
         strLoadErrorMsg = "加载XML数据岛信息错误 - " + ext.Message;
     }
     return(true);
 }
        private void TransformNewRelicConfig()
        {
            var path = $@"{RootDirectory}\newrelic.config";
            var xml  = new System.Xml.XmlDocument();

            // Update the 'newrelic.config' file
            xml.Load(path);
            var ns = new System.Xml.XmlNamespaceManager(xml.NameTable);

            ns.AddNamespace("x", "urn:newrelic-config");

            // Remove the 'application' element
            var node = xml.SelectSingleNode("//x:configuration/x:application", ns);

            node.ParentNode.RemoveChild(node);

            // Re-create the 'application' element
            var nodeLog = (System.Xml.XmlElement)xml.SelectSingleNode("//x:configuration/x:log", ns);
            var app     = xml.CreateElement("application", "urn:newrelic-config");

            xml.DocumentElement.InsertBefore(app, nodeLog);

            // Set the 'directory' attribute
            nodeLog.SetAttribute("directory", @"c:\Home\LogFiles\NewRelic");
            xml.Save(path);
        }
Ejemplo n.º 16
0
        private void ReadAppConfig()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            try
            {
                doc.Load(System.Reflection.Assembly.GetExecutingAssembly().Location + ".config");
            }
            catch (FileNotFoundException)
            {
                return;
            }

            System.Xml.XmlNamespaceManager manager = new System.Xml.XmlNamespaceManager(doc.NameTable);
            manager.AddNamespace("bindings", "urn:schemas-microsoft-com:asm.v1");

            System.Xml.XmlNode root = doc.DocumentElement;

            System.Xml.XmlNode node = root.SelectSingleNode("//bindings:bindingRedirect", manager);

            if (node == null)
            {
                throw (new Exception("Invalid Configuration File"));
            }

            node = node.SelectSingleNode("@newVersion");

            if (node == null)
            {
                throw (new Exception("Invalid Configuration File"));
            }
        }
Ejemplo n.º 17
0
        protected virtual DataSet LoadFromFile()
        {
            if (m_FileName == null)
            {
                throw new ApplicationException("FileName is null");
            }

            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.Load(m_FileName);

            System.Xml.XmlNamespaceManager namespaceMan = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable);
            namespaceMan.AddNamespace("fileds", c_DataNamespace);

            System.Xml.XmlNode tmp = xmlDoc.DocumentElement.SelectSingleNode("fileds:header", namespaceMan);
            if (tmp == null)
            {
                throw new ApplicationException("File header not found");
            }
            System.Xml.XmlElement header = (System.Xml.XmlElement)tmp;

            //File Version
            string strFileVersion = header.GetAttribute(c_FileVersion);
            int    fileVersion    = int.Parse(strFileVersion);

            if (fileVersion == c_FileVersionNumber)
            {
                string strDataFormat = header.GetAttribute(c_DataFormat);
                mFileDataFormat = (StreamDataSetFormat)int.Parse(strDataFormat);
            }
            else if (fileVersion == 0)
            {
                mFileDataFormat = StreamDataSetFormat.XML;
            }
            else if (fileVersion > c_FileVersionNumber)
            {
                throw new ApplicationException("File Version not supported, expected: " + c_FileVersionNumber.ToString());
            }

            //Data Version
            string  strDataVersion = header.GetAttribute(c_DataVersion);
            int     dataVersion    = int.Parse(strDataVersion);
            DataSet dataSet        = CreateData(dataVersion);

            //Data
            tmp = xmlDoc.DocumentElement.SelectSingleNode("fileds:data", namespaceMan);
            if (tmp == null)
            {
                throw new ApplicationException("File data not found");
            }
            System.Xml.XmlElement xmlDataNode = (System.Xml.XmlElement)tmp;

            byte[] xmlBuffer = System.Convert.FromBase64String(xmlDataNode.InnerText);
            using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(xmlBuffer))
            {
                StreamDataSet.Read(memStream, dataSet, mFileDataFormat, MergeReadedSchema);
                //dataSet.ReadXml(memStream);
            }

            return(dataSet);
        }
Ejemplo n.º 18
0
        public static float GetCurrencyRateInEuro(string currency)
        {
            if (currency.ToLower() == "")
            {
                throw new ArgumentException("Invalid Argument! currency parameter connot be empty");
            }
            if (currency.ToLower() == "eur")
            {
                throw new ArgumentException("Invalid Argument! cannot get exchange rate from EURO to EURO");
            }

            try
            {
                string rssUrl = string.Concat("http://www.ecb.int/rss/fxref-", currency.ToLower() + ".html");

                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(rssUrl);

                System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("rdf", "http://purl.org/rss/1.0/");
                nsmgr.AddNamespace("cb", "http://www.cbwiki.net/wiki/index.php/Specification_1.1");

                System.Xml.XmlNodeList nodeList = doc.SelectNodes("//rdf:item", nsmgr);

                foreach (System.Xml.XmlNode node in nodeList)
                {
                    CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
                    ci.NumberFormat.CurrencyDecimalSeparator = ".";

                    try
                    {
                        float exchangeRate = float.Parse(
                            node.SelectSingleNode("//cb:statistics//cb:exchangeRate//cb:value", nsmgr).InnerText,
                            NumberStyles.Any, ci);
                        return(exchangeRate);
                    }
                    catch { }
                }

                return(0);
            }
            catch
            {
                return(0);
            }
        }
Ejemplo n.º 19
0
        public static System.Xml.XmlNamespaceManager BuildNamespaceManager(System.Xml.XmlDocument xmlDoc, System.Xml.XmlNode node, string elemName, System.Xml.XmlNamespaceManager nsmgr, string prefix)
        {
            string namespaceName = GetAttributeOrEmpty(node, elemName, prefix + "Namespace", nsmgr);
            string NSPrefix      = GetAttributeOrEmpty(node, elemName, prefix + "NSPrefix", nsmgr);

            System.Xml.XmlNamespaceManager newNsmgr = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable);
            newNsmgr.AddNamespace(NSPrefix, namespaceName);
            return(newNsmgr);
        }
Ejemplo n.º 20
0
        public static void ParseParams(string paramString, Dictionary <string, QueryParameter> paramDict, IEventAggregator eventAggregator)
        {
            bool foundXmlNameSpacedParams = false;

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            try
            {
                doc.LoadXml(paramString);
                var nsMgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
                nsMgr.AddNamespace("x", "urn:schemas-microsoft-com:xml-analysis");
                foreach (System.Xml.XmlNode n in doc.SelectNodes("/x:Parameters/x:Parameter", nsMgr))
                {
                    foundXmlNameSpacedParams = true;
                    string paramTypeName = n["Value"].Attributes["xsi:type"].Value;
                    Type   paramType     = DaxStudio.Common.XmlTypeMapper.GetSystemType(paramTypeName);
                    object val           = Convert.ChangeType(n["Value"].InnerText, paramType);
                    if (!paramDict.ContainsKey(n["Name"].InnerText))
                    {
                        paramDict.Add(n["Name"].InnerText, new QueryParameter(n["Name"].InnerText, val, paramTypeName));
                    }
                    else
                    {
                        paramDict[n["Name"].InnerText] = new QueryParameter(n["Name"].InnerText, val, paramTypeName);
                    }
                }

                // if we did not find the proper namespace try searching for just the raw names
                if (!foundXmlNameSpacedParams)
                {
                    foreach (System.Xml.XmlNode n in doc.SelectNodes("/Parameters/Parameter", nsMgr))
                    {
                        string paramTypeName = "xsd:string";
                        if (n["Value"].Attributes.Count > 0)
                        {
                            if (n["Value"].Attributes["xsi:type"] != null)
                            {
                                paramTypeName = n["Value"].Attributes["xsi:type"].Value;
                            }
                        }


                        if (!paramDict.ContainsKey(n["Name"].InnerText))
                        {
                            paramDict.Add(n["Name"].InnerText, new QueryParameter(n["Name"].InnerText, n["Value"].InnerText, paramTypeName));
                        }
                        else
                        {
                            paramDict[n["Name"].InnerText] = new QueryParameter(n["Name"].InnerText, n["Value"].InnerText, paramTypeName);
                        }
                    }
                }
            } catch (Exception ex)
            {
                Log.Error(ex, "{class} {method} Error merging query parameters", "DaxHelper", "ParseParams");
                eventAggregator.PublishOnUIThread(new OutputMessage(MessageType.Error, "The Following Error occurred while trying to parse a parameter block: " + ex.Message));
            }
        }
Ejemplo n.º 21
0
 public static System.Xml.XmlNamespaceManager BuildNamespaceManager(System.Xml.XmlDocument doc, string prefix, bool includeXSD)
 {
     if (doc == null)
     {
         System.Diagnostics.Debug.WriteLine("oops");
     }
     else
     {
         System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
         nsmgr.AddNamespace(prefix, Tools.GetNamespace(doc, prefix));
         if (includeXSD)
         {
             nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
         }
         return(nsmgr);
     }
     return(null);
 }
Ejemplo n.º 22
0
        /// <summary>
        /// 载入C#工程项目文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        public override void LoadProjectFile(string fileName)
        {
            this.projectFileName = fileName;

            System.IO.StreamReader myReader = new System.IO.StreamReader(fileName, System.Text.Encoding.GetEncoding(936));
            string strText = myReader.ReadToEnd();

            myReader.Close();

            System.Xml.XmlDocument myXMLDoc = new System.Xml.XmlDocument();
            myXMLDoc.LoadXml(strText);

            this.rootPath = System.IO.Path.GetDirectoryName(fileName);
            this.files.Clear();

            bool For2005 = false;

            if (myXMLDoc.DocumentElement.Name == "Project")
            {
                if (myXMLDoc.DocumentElement.GetAttribute("xmlns") == "http://schemas.microsoft.com/developer/msbuild/2003")
                {
                    For2005 = true;
                }
            }

            if (For2005)
            {
                System.Xml.XmlNamespaceManager ns = new System.Xml.XmlNamespaceManager(myXMLDoc.NameTable);
                ns.AddNamespace("a", "http://schemas.microsoft.com/developer/msbuild/2003");
                foreach (System.Xml.XmlElement myFileElement in myXMLDoc.SelectNodes("a:Project/a:ItemGroup/a:Compile", ns))
                {
                    ProjectFileEntity NewFile = new ProjectFileEntity();
                    NewFile.FileName = myFileElement.GetAttribute("Include");
                    string name = NewFile.FileName;
                    name = name.Trim().ToLower();
                    if (name.EndsWith(".cs"))
                    {
                        NewFile.CanAnalyse = true;
                    }
                    else
                    {
                        NewFile.CanAnalyse = false;
                    }
                    this.files.Add(NewFile);
                }
            }
            else
            {
                foreach (System.Xml.XmlElement myFileElement in myXMLDoc.SelectNodes("VisualStudioProject/CSHARP/Files/Include/File"))
                {
                    ProjectFileEntity NewFile = new ProjectFileEntity();
                    NewFile.FileName   = myFileElement.GetAttribute("RelPath");
                    NewFile.CanAnalyse = (myFileElement.GetAttribute("BuildAction") == "Compile");
                    this.files.Add(NewFile);
                }
            }
        }
        public void Invalid_MultipleVenuesAtTheSamePresentationWithSameProviderIdentifier()
        {
            var xDoc = System.Xml.Linq.XDocument.Parse
                       (
                Resources.ContentValidation.UniqueValidator.Invalid.MultipleVenuesAtTheSamePresentationWithSameProviderIdentifier,
                System.Xml.Linq.LoadOptions.SetLineInfo
                       );

            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
            nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
            nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            XCRI.Validation.ContentValidation.UniqueValidator v = new XCRI.Validation.ContentValidation.UniqueValidator()
            {
                XPathSelector    = "//dc:identifier[not(@xsi:type)]",
                NamespaceManager = nsmgr,
                UniqueAcross     = XCRI.Validation.ContentValidation.UniqueValidator.UniqueAcrossTypes.Context
            };
            var vrc = v.Validate(xDoc.Root);

            Assert.AreEqual <int>(1, vrc.Count());
            var vr = vrc.ElementAt(0);

            Assert.IsNotNull(vr);
            Assert.AreEqual <XCRI.Validation.ContentValidation.ValidationStatus>
            (
                XCRI.Validation.ContentValidation.ValidationStatus.Exception,
                vr.Status
            );
            Assert.AreEqual <int>
            (
                3,
                vr.Count
            );
            Assert.AreEqual <int>
            (
                1,
                vr.SuccessCount
            );
            Assert.AreEqual <int>
            (
                2,
                vr.FailedCount
            );
        }
Ejemplo n.º 24
0
        //pass in a marcxml record and return
        //the record id if present
        public string GetRecordId(string xml, string field, string subfield)
        {
            string xpath = "";

            try
            {
                if (xml.IndexOf("marc:collection") > -1)
                {
                    if (System.Convert.ToInt32(field) > 10)
                    {
                        xpath = "/marc:collection/marc:record/marc:datafield[@tag='" + field + "']";
                    }
                    else
                    {
                        xpath = "/marc:collection/marc:record/marc:controlfield[@tag='" + field + "']";
                    }
                }
                else
                {
                    if (System.Convert.ToInt32(field) > 10)
                    {
                        xpath = "/marc:record/marc:datafield[@tag='" + field + "']";
                    }
                    else
                    {
                        xpath = "/marc:record/marc:controlfield[@tag='" + field + "']";
                    }
                }


                //System.Windows.Forms.MessageBox.Show(xpath);
                System.Xml.XmlDocument         objXML = new System.Xml.XmlDocument();
                System.Xml.XmlNamespaceManager ns     = new System.Xml.XmlNamespaceManager(objXML.NameTable);
                ns.AddNamespace("marc", "http://www.loc.gov/MARC21/slim");

                System.Xml.XmlNode objNode;
                System.Xml.XmlNode objSubfield;
                objXML.LoadXml(xml);
                objNode = objXML.SelectSingleNode(xpath, ns);
                //objNode = objXML.SelectSingleNode(xpath, ns);
                if (!string.IsNullOrEmpty(subfield))
                {
                    objSubfield = objNode.SelectSingleNode("marc:subfield[@code='" + subfield + "']", ns);
                }
                else
                {
                    objSubfield = objNode;
                }
                return(objSubfield.InnerText);
            }
            catch (System.Exception xe)
            {
                perror_message += xe.ToString();
                return("");
            }
        }
Ejemplo n.º 25
0
        } // End Function SanitizeXml

        // <text x="20" y="105" style="fill:#FF0064;font-family:Times New Roman;" font-size="56">
        //      Evaluation Only. Created with Aspose.Pdf. Copyright 2002-2014 Aspose Pty Ltd.
        // </text>
        public static string RemoveEvalString(string FileName, string URL)
        {
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.XmlResolver        = null;
            xmlDoc.PreserveWhitespace = true;
            // xmlDoc.Load(FileName);

            string sanitizedContent = SanitizeXml(FileName);

            try
            {
                xmlDoc.LoadXml(sanitizedContent);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.Clipboard.SetText(sanitizedContent);
                System.Console.WriteLine(URL);
                System.Windows.Forms.MessageBox.Show(ex.Message);
                throw;
            }


            System.Xml.XmlAttribute attr = xmlDoc.DocumentElement.Attributes["xmlns"];
            string strDefaultNamespace   = null;

            if (attr != null)
            {
                strDefaultNamespace = attr.Value;
            }

            if (string.IsNullOrEmpty(strDefaultNamespace))
            {
                strDefaultNamespace = "http://www.w3.org/2000/svg";
            }

            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable);
            nsmgr.AddNamespace("dft", strDefaultNamespace);


            System.Xml.XmlNodeList EvalVersionTags = xmlDoc.SelectNodes("//dft:text[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜÉÈÊÀÁÂÒÓÔÙÚÛÇÅÏÕÑŒ', 'abcdefghijklmnopqrstuvwxyzäöüéèêàáâòóôùúûçåïõñœ'),'aspose')]", nsmgr);
            //System.Xml.XmlNodeList EvalVersionTags = xmlDoc.SelectNodes("//dft:text[contains(text(),'Aspose')]", nsmgr);

            foreach (System.Xml.XmlNode EvalVersionTag in EvalVersionTags)
            {
                if (EvalVersionTag.ParentNode != null)
                {
                    EvalVersionTag.ParentNode.RemoveChild(EvalVersionTag);
                }
            } // Next EvalVersionTag

            // string str = xmlDoc.OuterXml;
            string str = BeautifyXML(xmlDoc);

            xmlDoc = null;
            return(str);
        } // End Sub RemoveEvalString
Ejemplo n.º 26
0
        public static System.Xml.XmlNamespaceManager GetNamespaceManager(System.Xml.XmlDocument doc)
        {
            if (doc == null)
            {
                throw new System.ArgumentNullException("doc");
            }

            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(doc.NameTable);

            // <Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">

            if (doc.DocumentElement != null)
            {
                // string strNamespace = doc.DocumentElement.NamespaceURI;
                // System.Console.WriteLine(strNamespace);
                // nsmgr.AddNamespace("dft", strNamespace);

                System.Xml.XPath.XPathNavigator xNav = doc.CreateNavigator();
                while (xNav.MoveToFollowing(System.Xml.XPath.XPathNodeType.Element))
                {
                    System.Collections.Generic.IDictionary <string, string> localNamespaces =
                        xNav.GetNamespacesInScope(System.Xml.XmlNamespaceScope.Local);

                    foreach (System.Collections.Generic.KeyValuePair <string, string> kvp in localNamespaces)
                    {
                        string prefix = kvp.Key;
                        if (string.IsNullOrEmpty(prefix))
                        {
                            prefix = "dft";
                        }

                        nsmgr.AddNamespace(prefix, kvp.Value);
                    } // Next kvp
                }     // Whend

                return(nsmgr);
            } // End if (doc.DocumentElement != null)

            nsmgr.AddNamespace("dft", "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");
            // nsmgr.AddNamespace("dft", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition");

            return(nsmgr);
        } // End Function GetReportNamespaceManager
Ejemplo n.º 27
0
 public static System.Xml.XmlNode GetSchemaForNode(string nodeName, System.Xml.XmlDocument xsdDoc)
 {
     if (xsdDoc != null)
     {
         System.Xml.XmlNamespaceManager namespaceManager = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
         namespaceManager.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
         return(xsdDoc.SelectSingleNode("//xs:element[@name='" + nodeName + "']", namespaceManager));
     }
     return(null);
 }
Ejemplo n.º 28
0
        private static string ManuallyGetUpdateVersion(string appcastPath)
        {
            System.Xml.XmlDocument xmlDocManual = new System.Xml.XmlDocument();
            xmlDocManual.Load(appcastPath);

            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(xmlDocManual.NameTable);
            nsmgr.AddNamespace("sparkle", "http://www.andymatuschak.org/xml-namespaces/sparkle");

            return(xmlDocManual.SelectSingleNode("/rss/channel/item/enclosure/@sparkle:version", nsmgr).Value);
        }
Ejemplo n.º 29
0
        public static AtomFeed LoadXML(string xml)
        {
            var dom = new System.Xml.XmlDocument();
            var nsmgr = new System.Xml.XmlNamespaceManager(dom.NameTable);
            nsmgr.AddNamespace(NamespaceShortName, NamespaceURI);
            dom.LoadXml(xml);

            var feed = load_from_dom(dom, nsmgr);
            return feed;

        }
Ejemplo n.º 30
0
        private System.Xml.XmlNamespaceManager InitializeXmlNamespaceManager(System.Xml.XmlDocument xmlDocument)
        {
            System.Xml.XmlNamespaceManager nmsManager = new System.Xml.XmlNamespaceManager(xmlDocument.NameTable);

            for (int i = 0; i < namespaces.GetLength(0); i++)
            {
                nmsManager.AddNamespace(namespaces[i, 0], namespaces[i, 1]);
            }

            return(nmsManager);
        }
 public void Invalid_MultipleVenuesAtTheSamePresentationWithSameProviderIdentifier()
 {
     var xDoc = System.Xml.Linq.XDocument.Parse
         (
         Resources.ContentValidation.UniqueValidator.Invalid.MultipleVenuesAtTheSamePresentationWithSameProviderIdentifier,
         System.Xml.Linq.LoadOptions.SetLineInfo
         );
     System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
     nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
     nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
     XCRI.Validation.ContentValidation.UniqueValidator v = new XCRI.Validation.ContentValidation.UniqueValidator()
     {
         XPathSelector = "//dc:identifier[not(@xsi:type)]",
         NamespaceManager = nsmgr,
         UniqueAcross = XCRI.Validation.ContentValidation.UniqueValidator.UniqueAcrossTypes.Context
     };
     var vrc = v.Validate(xDoc.Root);
     Assert.AreEqual<int>(1, vrc.Count());
     var vr = vrc.ElementAt(0);
     Assert.IsNotNull(vr);
     Assert.AreEqual<XCRI.Validation.ContentValidation.ValidationStatus>
         (
         XCRI.Validation.ContentValidation.ValidationStatus.Exception,
         vr.Status
         );
     Assert.AreEqual<int>
         (
         3,
         vr.Count
         );
     Assert.AreEqual<int>
         (
         1,
         vr.SuccessCount
         );
     Assert.AreEqual<int>
         (
         2,
         vr.FailedCount
         );
 }
Ejemplo n.º 32
0
        public static AtomFeed LoadXML(string xml)
        {
            var dom   = new System.Xml.XmlDocument();
            var nsmgr = new System.Xml.XmlNamespaceManager(dom.NameTable);

            nsmgr.AddNamespace(NamespaceShortName, NamespaceURI);
            dom.LoadXml(xml);

            var feed = load_from_dom(dom, nsmgr);

            return(feed);
        }
Ejemplo n.º 33
0
        public FGDData Make(string filename)
        {
            System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
            myXmlDocument.Load(filename);
            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(myXmlDocument.NameTable);
            nsmgr.AddNamespace("fgd", "http://fgd.gsi.go.jp/spec/2008/FGD_GMLSchema");
            nsmgr.AddNamespace("gml", "http://www.opengis.net/gml/3.2");
            nsmgr.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
            nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
            nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            return(new FGDData
                   (
                       Swap <float>(Split <float>(myXmlDocument.SelectSingleNode("/fgd:Dataset/fgd:DEM/fgd:coverage/gml:boundedBy/gml:Envelope/gml:lowerCorner", nsmgr).InnerText)),
                       Swap <float>(Split <float>(myXmlDocument.SelectSingleNode("/fgd:Dataset/fgd:DEM/fgd:coverage/gml:boundedBy/gml:Envelope/gml:upperCorner", nsmgr).InnerText)),
                       Split <int>(myXmlDocument.SelectSingleNode("/fgd:Dataset/fgd:DEM/fgd:coverage/gml:gridDomain/gml:Grid/gml:limits/gml:GridEnvelope/gml:low", nsmgr).InnerText),
                       Split <int>(myXmlDocument.SelectSingleNode("/fgd:Dataset/fgd:DEM/fgd:coverage/gml:gridDomain/gml:Grid/gml:limits/gml:GridEnvelope/gml:high", nsmgr).InnerText),
                       Split <int>(myXmlDocument.SelectSingleNode("/fgd:Dataset/fgd:DEM/fgd:coverage/gml:coverageFunction/gml:GridFunction/gml:startPoint", nsmgr).InnerText),
                       SplitStrings(myXmlDocument.SelectSingleNode("/fgd:Dataset/fgd:DEM/fgd:coverage/gml:rangeSet/gml:DataBlock/gml:tupleList", nsmgr).InnerText)
                   ));
        }
Ejemplo n.º 34
0
        public static System.Xml.XmlNamespaceManager GetReportNamespaceManager(System.Xml.XmlDocument doc)
        {
            if (doc == null)
                throw new System.ArgumentNullException("doc");

            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(doc.NameTable);

            // <Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">

            if (doc.DocumentElement != null)
            {
                // string strNamespace = doc.DocumentElement.NamespaceURI;
                // System.Console.WriteLine(strNamespace);
                // nsmgr.AddNamespace("dft", strNamespace);

                System.Xml.XPath.XPathNavigator xNav = doc.CreateNavigator();
                while (xNav.MoveToFollowing(System.Xml.XPath.XPathNodeType.Element))
                {
                    System.Collections.Generic.IDictionary<string, string> localNamespaces =
                        xNav.GetNamespacesInScope(System.Xml.XmlNamespaceScope.Local);

                    foreach (System.Collections.Generic.KeyValuePair<string, string> kvp in localNamespaces)
                    {
                        string prefix = kvp.Key;
                        if (string.IsNullOrEmpty(prefix))
                            prefix = "dft";

                        nsmgr.AddNamespace(prefix, kvp.Value);
                    } // Next kvp

                } // Whend

                return nsmgr;
            } // End if (doc.DocumentElement != null)

            nsmgr.AddNamespace("dft", "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");
            // nsmgr.AddNamespace("dft", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition");

            return nsmgr;
        }
Ejemplo n.º 35
0
        private TableDefinition XSDToTableDefinition(string XsdPath, string TableName, string schemaName = "fias")
        {
            System.Xml.XmlDocument _doc = new System.Xml.XmlDocument();
            _doc.Load(XsdPath);
            System.Xml.XmlNamespaceManager _nsMan = new System.Xml.XmlNamespaceManager(_doc.NameTable);
            _nsMan.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

            string tableComment;

            try
            {
                tableComment = _doc.
                               SelectSingleNode("xs:schema/xs:element/xs:complexType/xs:sequence/xs:element/xs:annotation/xs:documentation", _nsMan).
                               InnerText;
            }
            catch (Exception q)
            {
                tableComment = q.Message;
            }

            TableDefinition _table = new TableDefinition(schemaName.ToLower(), TableName.ToLower(), tableComment);

            System.Xml.XmlNodeList xsdColumns = _doc.SelectNodes(".//xs:attribute", _nsMan);

            List <XSD2PGTypes.XSD2PGType> typesConversion = (new XSD2PGTypes()).Types;

            // Список столбцов
            for (int i = 0; i <= xsdColumns.Count - 1; i++)
            {
                System.Xml.XmlNode _c         = xsdColumns[i];
                string             colName    = _c.SelectSingleNode("@name", _nsMan).Value.ToLower();
                string             colComment = _c.SelectSingleNode("xs:annotation/xs:documentation", _nsMan).InnerText;
                string             xsdcolType;
                try
                {
                    xsdcolType = _c.SelectSingleNode("@type|xs:simpleType/xs:restriction/@base", _nsMan).Value;
                }
                catch (Exception exc)
                {
                    colComment = "АШИПКА" + exc.Message;
                    xsdcolType = "xs:string";
                }

#if DEBUG
                Console.WriteLine(xsdcolType);
#endif
                string colType = typesConversion.Where(x => x.xsdType == xsdcolType).Single().pgType;

                _table.AddColumn(colName, colType, colComment);
            }
            return(_table);
        }
 public void Invalid_DescriptionsWithHrefMustNotContainContent_HTML()
 {
     var xDoc = System.Xml.Linq.XDocument.Parse
         (
         Resources.ContentValidation.StringLengthValidator.Invalid.DescriptionsWithHrefMustNotContainContent_HTML,
         System.Xml.Linq.LoadOptions.SetLineInfo
         );
     System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
     nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
     XCRI.Validation.ContentValidation.StringLengthValidator v = new XCRI.Validation.ContentValidation.StringLengthValidator()
     {
         XPathSelector = "//dc:description[@href]",
         NamespaceManager = nsmgr,
         MaximumCharacters = 0,
         FailedValidationStatus = XCRI.Validation.ContentValidation.ValidationStatus.Exception
     };
     var vrc = v.Validate(xDoc.Root);
     Assert.AreEqual<int>(1, vrc.Count());
     var vr = vrc.ElementAt(0);
     Assert.IsNotNull(vr);
     Assert.AreEqual<XCRI.Validation.ContentValidation.ValidationStatus>
         (
         XCRI.Validation.ContentValidation.ValidationStatus.Exception,
         vr.Status
         );
     Assert.AreEqual<int>
         (
         1,
         vr.Count
         );
     Assert.AreEqual<int>
         (
         0,
         vr.SuccessCount
         );
     Assert.AreEqual<int>
         (
         1,
         vr.FailedCount
         );
     Assert.IsTrue(vr.Instances[0].LineNumber.HasValue);
     Assert.IsTrue(vr.Instances[0].LinePosition.HasValue);
     Assert.AreEqual<int>(vr.Instances[0].LineNumber.Value, 3);
     Assert.AreEqual<int>(vr.Instances[0].LinePosition.Value, 4);
 }
 public void Valid_DescriptionsWithoutHrefMustContainContent()
 {
     var xDoc = System.Xml.Linq.XDocument.Parse
         (
         Resources.ContentValidation.StringLengthValidator.Valid.DescriptionsWithoutHrefMustContainContent,
         System.Xml.Linq.LoadOptions.SetLineInfo
         );
     System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
     nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
     XCRI.Validation.ContentValidation.StringLengthValidator v = new XCRI.Validation.ContentValidation.StringLengthValidator()
     {
         XPathSelector = "//dc:description[not(@href)]",
         NamespaceManager = nsmgr,
         MinimumCharacters = 1,
         FailedValidationStatus = XCRI.Validation.ContentValidation.ValidationStatus.Exception
     };
     var vrc = v.Validate(xDoc.Root);
     Assert.AreEqual<int>(1, vrc.Count());
     var vr = vrc.ElementAt(0);
     Assert.IsNotNull(vr);
     Assert.AreEqual<XCRI.Validation.ContentValidation.ValidationStatus>
         (
         XCRI.Validation.ContentValidation.ValidationStatus.Passed,
         vr.Status
         );
     Assert.AreEqual<int>
         (
         1,
         vr.Count
         );
     Assert.AreEqual<int>
         (
         1,
         vr.SuccessCount
         );
     Assert.AreEqual<int>
         (
         0,
         vr.FailedCount
         );
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Extract the value of the statistic from the specified XML data.
        /// </summary>
        /// <param name="nav">A navigator into an XML document containing the statistic data.</param>
        /// <returns>The statistic value.</returns>
		protected override object Evaluate(XPathNavigator nav)
		{
			XPathNodeIterator nodeIterator;

            if (NameSpaces.Length == 0)
            {
                nodeIterator = nav.Select(xpath);
            }
            else
            {
                System.Xml.XmlNamespaceManager nmsp = new System.Xml.XmlNamespaceManager(nav.NameTable);

                foreach (var s in NameSpaces)
                {
                    nmsp.AddNamespace(s.Prefix, s.Url);
                }
                nodeIterator = nav.Select(xpath,nmsp);
            }

			return nodeIterator.MoveNext() ? nodeIterator.Current.Value : null;
		}
Ejemplo n.º 39
0
        internal static bool IsError(string xmlResponse, out string sMessage)
        {
            System.Xml.XmlDocument objXML = new System.Xml.XmlDocument();
            objXML.LoadXml(xmlResponse);
            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(objXML.NameTable);
            nsmgr.AddNamespace("x", objXML.DocumentElement.NamespaceURI);
            sMessage = "";

            if (objXML.SelectSingleNode("/x:error/x:code", nsmgr) != null)
            {
                //System.Windows.Forms.MessageBox.Show(objXML.SelectSingleNode("/x:error/x:code", nsmgr).InnerText);
                sMessage = objXML.SelectSingleNode("/x:error/x:code", nsmgr).InnerText + ": " + objXML.SelectSingleNode("/x:error/x:message", nsmgr).InnerText;
                if (objXML.SelectSingleNode("/x:error/detail", nsmgr) !=null) {
                    //System.Windows.Forms.MessageBox.Show("here");
                    foreach (System.Xml.XmlNode node in objXML.SelectNodes("/x:error/x:detail/validationErrors")) {
                        sMessage += ": " + node.SelectSingleNode("validationError/message").InnerText;
                    }
                }
                return true;
            }

            return false;
        }
Ejemplo n.º 40
0
        public static Dictionary<string, string> ParseParams(string paramString)
        {
            var d = new Dictionary<string,string>();
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(paramString);
            var nsMgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
            nsMgr.AddNamespace("x", "urn:schemas-microsoft-com:xml-analysis");
            foreach( System.Xml.XmlNode n in doc.SelectNodes("/x:Parameters/x:Parameter",nsMgr))
            {
                d.Add(n["Name"].InnerText, n["Value"].InnerText);
            }

            // if we did not find the proper namespace try searching for just the raw names
            if (d.Count == 0)
            {
                foreach (System.Xml.XmlNode n in doc.SelectNodes("/Parameters/Parameter", nsMgr))
                {
                    d.Add(n["Name"].InnerText, n["Value"].InnerText);
                }

            }
            return d;
        }
Ejemplo n.º 41
0
        private System.Xml.XmlNodeList getItems(String title, String searchIndex, String Itempage)
        {
            SprightlySoftAWS.REST MyREST = new SprightlySoftAWS.REST();

            String RequestURL;
            RequestURL = "https://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&Operation=ItemSearch&Version=2011-08-01";
            RequestURL += "&AWSAccessKeyId=" + System.Uri.EscapeDataString("AKIAJIS6X7GHSGTU7AQQ");
            RequestURL += "&AssociateTag=ENTER_YOUR_ASSOCIATE_TAG_HERE";
            RequestURL += "&SignatureVersion=2&SignatureMethod=HmacSHA256";
            RequestURL += "&Timestamp=" + Uri.EscapeDataString(DateTime.UtcNow.ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z"));
            RequestURL += "&Title=" + System.Uri.EscapeDataString(title);
            RequestURL += "&SearchIndex=" + searchIndex;
            RequestURL += "&ResponseGroup=" + System.Uri.EscapeDataString("ItemAttributes,Images,EditorialReview");
            RequestURL += "&Sort=salesrank";
            RequestURL += "&ItemPage=" + Itempage;

            String RequestMethod;
            RequestMethod = "GET";

            String SignatureValue;
            SignatureValue = MyREST.GetSignatureVersion2Value(RequestURL, RequestMethod, "", "ydILyRh/cOIs3c2JDRpORf0o/C1gTf8cm5iGcIEt");

            RequestURL += "&Signature=" + System.Uri.EscapeDataString(SignatureValue);

            Boolean RetBool;
            RetBool = MyREST.MakeRequest(RequestURL, RequestMethod, null);

            if (RetBool == true)
            {
                System.Xml.XmlDocument MyXmlDocument;
                System.Xml.XmlNamespaceManager MyXmlNamespaceManager;
                System.Xml.XmlNodeList MyXmlNodeList;

                MyXmlDocument = new System.Xml.XmlDocument();
                MyXmlDocument.LoadXml(MyREST.ResponseString);

                MyXmlNamespaceManager = new System.Xml.XmlNamespaceManager(MyXmlDocument.NameTable);
                MyXmlNamespaceManager.AddNamespace("amz", "http://webservices.amazon.com/AWSECommerceService/2011-08-01");

                MyXmlNodeList = MyXmlDocument.SelectNodes("amz:ItemSearchResponse/amz:Items/amz:Item", MyXmlNamespaceManager);

                return MyXmlNodeList;
            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 42
0
        //pass in a marcxml record and return
        //the record id if present
        public string GetRecordId(string xml, string field, string subfield)
        {
            string xpath = "";
            try
            {

                if (xml.IndexOf("marc:collection") > -1)
                {
                    xpath = "/marc:collection/marc:record/marc:datafield[@tag='" + field + "']";
                }
                else
                {
                    xpath = "/marc:record/marc:datafield[@tag='" + field + "']";
                }

                System.Xml.XmlDocument objXML = new System.Xml.XmlDocument();
                System.Xml.XmlNamespaceManager ns = new System.Xml.XmlNamespaceManager(objXML.NameTable);
                ns.AddNamespace("marc", "http://www.loc.gov/MARC21/slim");

                System.Xml.XmlNode objNode;
                System.Xml.XmlNode objSubfield;
                objXML.LoadXml(xml);
                objNode = objXML.SelectSingleNode(xpath, ns);
                objNode = objXML.SelectSingleNode(xpath, ns);
                objSubfield = objNode.SelectSingleNode("marc:subfield[@code='" + subfield + "']", ns);
                return objSubfield.InnerText;

            }
            catch (System.Exception xe)
            {
                perror_message += xe.ToString();
                return "";
            }
        }
Ejemplo n.º 43
0
        public bool GetCFDI(string user, string password, CFDI.Comprobante comprobante)
        {
            //throw new NotImplementedException();

            string invoiceFileName = DateTime.Now.ToString("yyyyMMddHHmmss_" + comprobante.PublicKey.ToString("N"));
            byte[] sendFileBytes;
            byte[] responseFileBytes;

            CloudStorageAccount account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureDefaultStorageConnectionString"]);
            CloudBlobClient client = account.CreateCloudBlobClient();
            CloudBlobContainer container = client.GetContainerReference(ConfigurationManager.AppSettings["AzureDefaultStorage"]);

            try {

                using (MemoryStream ms = new MemoryStream()) {
                    using (MemoryStream zipMs = new MemoryStream()) {
                        CFDIXmlTextWriter writer =
                            new CFDIXmlTextWriter(comprobante, ms, System.Text.Encoding.UTF8);
                        writer.WriteXml();
                        ms.Position = 0;

                        using (ZipArchive zip = new ZipArchive(zipMs, ZipArchiveMode.Create, true)) {
                            var entry = zip.CreateEntry(invoiceFileName + "_send.xml");
                            using (Stream s = entry.Open()) {
                                ms.CopyTo(s);
                            }
                            zipMs.Flush();
                        } // zip.Dispose() => Close();

                        // container.CreateIfNotExists();
                        CloudBlockBlob blob = container.GetBlockBlobReference(invoiceFileName + "_send.zip");
                        zipMs.Position = 0;

                        blob.UploadFromStream(zipMs);
                        blob.Properties.ContentType = "application/x-zip-compressed";
                        blob.SetMetadata();
                        blob.SetProperties();

                        zipMs.Position = 0;
                        sendFileBytes = zipMs.ToArray();
                    } // zipMs.Dispose() => Close();
                } // ms.Dispose() => Close();

                //CFDI.EDICOM.TestCFDI.CFDiService webService = new CFDI.EDICOM.TestCFDI.CFDiService();
                //responseFileBytes = webService.getCfdiTest(user, password, sendFileBytes);
                ICFDIService webService = CFDiServiceFactory.Create();
                responseFileBytes = webService.GetCFDI(user, password, sendFileBytes);

                CloudBlockBlob blob2 = container.GetBlockBlobReference(invoiceFileName + "_response.zip");
                //zipMs.Position = 0;

                blob2.UploadFromByteArray(responseFileBytes, 0, responseFileBytes.Length); // .UploadFromStream(zipMs);
                blob2.Properties.ContentType = "application/x-zip-compressed";
                blob2.SetMetadata();
                blob2.SetProperties();

                using (var responseStream = new MemoryStream(responseFileBytes)) {
                    using (var archive = new ZipArchive(responseStream, ZipArchiveMode.Read, true)) {
                        var fileInArchive = archive.Entries[0]; //
                        using (var entryStream = fileInArchive.Open()) {
                            using (var reader = new StreamReader(entryStream)) {
                                string output = reader.ReadToEnd();

                                System.Xml.XmlDocument invoice = new System.Xml.XmlDocument();
                                invoice.LoadXml(output);

                                System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(invoice.NameTable);
                                nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3");
                                nsmgr.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital");
                                System.Xml.XmlNode timbre = invoice.SelectSingleNode("//tfd:TimbreFiscalDigital", nsmgr);

                                TimbreFiscalDigital complemento = new TimbreFiscalDigital();

                                complemento.Version = timbre.Attributes.GetNamedItem("version").Value.ToString();
                                complemento.UUID = timbre.Attributes.GetNamedItem("UUID").Value.ToString();
                                complemento.FechaTimbrado = DateTime.Parse(timbre.Attributes.GetNamedItem("FechaTimbrado").Value);
                                complemento.SelloCFD = timbre.Attributes.GetNamedItem("selloCFD").Value.ToString();
                                complemento.NoCertificadoSAT = timbre.Attributes.GetNamedItem("noCertificadoSAT").Value.ToString();
                                complemento.SelloSAT = timbre.Attributes.GetNamedItem("selloSAT").Value.ToString();

                                if (comprobante.Complementos == null)
                                    comprobante.Complementos = new List<Complemento>();
                                comprobante.Complementos.Add(complemento);
                                //Complemento complemento = new Complemento();
                                //complemento.

                                //           //    Sistrategia.Server.SAT.CFDI.Comprobante comprobante2 = Sistrategia.Server.SAT.SATManager.GetComprobante(Guid.Parse(post["comprobanteId"]));
                                //           //    comprobante2.Complemento = new Sistrategia.Server.SAT.CFDI.ComprobanteComplemento();
                                //           //    comprobante2.Complemento.TimbreFiscalDigitalSpecified = true;
                                //           //    comprobante2.Complemento.TimbreFiscalDigital = new Sistrategia.Server.SAT.CFDI.ComprobanteTimbre();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.SatTimbreId = Guid.NewGuid();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.Version = timbre.Attributes.GetNamedItem("version").Value.ToString();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.UUID = timbre.Attributes.GetNamedItem("UUID").Value.ToString();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.FechaTimbrado = DateTime.Parse(timbre.Attributes.GetNamedItem("FechaTimbrado").Value);
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.SelloCFD = timbre.Attributes.GetNamedItem("selloCFD").Value.ToString();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.NoCertificadoSAT = timbre.Attributes.GetNamedItem("noCertificadoSAT").Value.ToString();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.SelloSAT = timbre.Attributes.GetNamedItem("selloSAT").Value.ToString();

                                // entryStream.Position = 0;
                              //  entryStream.Position

                                // SAVE final xml:
                                 Sistrategia.SAT.CFDiWebSite.CloudStorage.CloudStorageMananger manager =
                                     new Sistrategia.SAT.CFDiWebSite.CloudStorage.CloudStorageMananger();
                            //manager.UploadFromStream(ConfigurationManager.AppSettings["AzureAccountName"],
                                manager.UploadFromString(ConfigurationManager.AppSettings["AzureAccountName"],
                                ConfigurationManager.AppSettings["AzureAccountKey"],
                                comprobante.Emisor.PublicKey.ToString("N"),
                                comprobante.PublicKey.ToString("N") + ".xml",
                                comprobante.Serie + comprobante.Folio + ".xml", //model.ComprobanteArchivo.FileName,
                                "text/xml", //model.ComprobanteArchivo.ContentType,
                                output); // model.ComprobanteArchivo.InputStream);

                                comprobante.GeneratedCadenaOriginal = comprobante.GetCadenaOriginal();
                                comprobante.GeneratedXmlUrl = string.Format(@"https://sistrategiacfdi1.blob.core.windows.net/{0}/{1}.xml",
                                comprobante.Emisor.PublicKey.ToString("N"),
                                comprobante.PublicKey.ToString("N"));
                                comprobante.Status = "A";
                            }
                        }
                        //using (var fileToCompressStream = new MemoryStream(fileBytes)) {
                        //    fileToCompressStream.CopyTo(entryStream);
                        //}
                    }
                }

            }
            catch (Exception ex){
                CloudBlockBlob blob2 = container.GetBlockBlobReference(invoiceFileName + "_exception.txt");
                //zipMs.Position = 0;
                blob2.UploadText(ex.ToString());
                blob2.Properties.ContentType = "text/plain";
                blob2.SetMetadata();
                blob2.SetProperties();

                throw;
            }

            return true;
        }
        private void ReadAppConfig()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            try
            {
                doc.Load(System.Reflection.Assembly.GetExecutingAssembly().Location + ".config");
            }
            catch (FileNotFoundException)
            {
                return;
            }

            System.Xml.XmlNamespaceManager manager = new System.Xml.XmlNamespaceManager(doc.NameTable);
            manager.AddNamespace("bindings", "urn:schemas-microsoft-com:asm.v1");

            System.Xml.XmlNode root = doc.DocumentElement;

            System.Xml.XmlNode node = root.SelectSingleNode("//bindings:bindingRedirect", manager);

            if (node == null)
            {
                throw (new Exception("Invalid Configuration File"));
            }

            node = node.SelectSingleNode("@newVersion");

            if (node == null)
            {
                throw (new Exception("Invalid Configuration File"));
            }
        }
Ejemplo n.º 45
0
        private System.Collections.ArrayList Process_SRU(string xml)
        {
            System.Xml.XmlTextReader rd;
            System.Collections.ArrayList tp = new System.Collections.ArrayList();

            System.Xml.XmlDocument objDoc = new System.Xml.XmlDocument();
            objDoc.XmlResolver = null;
            System.Xml.XmlNamespaceManager Manager = new System.Xml.XmlNamespaceManager(objDoc.NameTable);
            System.Xml.XmlNodeList objNodes;
            string RetrievedRecords = "0";
            System.Collections.ArrayList RecordSet = new System.Collections.ArrayList();

            rd = new System.Xml.XmlTextReader(xml, System.Xml.XmlNodeType.Document, null);
            string RecordPosition = "1";

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name.IndexOf("numberOfRecords") > -1)
                    {
                        RetrievedRecords = rd.ReadString();
                    }
                    if (rd.Name.IndexOf("recordData") > -1)
                    {
                        RecordSet.Add(rd.ReadInnerXml());
                        //this needs to go somewhere
                    }
                    if (rd.Name.IndexOf("recordPosition") > -1)
                    {
                        RecordPosition = rd.ReadString();
                    }
                }
            }

            rd.Close();

            for (int x = 0; x < RecordSet.Count; x++)
            {
                struct_Records st_recs = new struct_Records();
                st_recs.xml = (string)RecordSet[x];

                Manager.AddNamespace("marc", "http://www.loc.gov/MARC21/slim");
                //try
                //{
                objDoc.LoadXml((string)RecordSet[x]);
                objNodes = objDoc.SelectNodes("marc:record/marc:datafield[@tag='150']", Manager);
                if (objNodes == null)
                {
                    objNodes = objDoc.SelectNodes("record/datafield[@tag='150']", Manager);
                }
                foreach (System.Xml.XmlNode objNode in objNodes)
                {
                    st_recs.xml = objNode.InnerXml;

                    System.Xml.XmlNodeList codes = objNode.SelectNodes("marc:subfield", Manager);
                    if (codes == null)
                    {
                        codes = objNode.SelectNodes("subfield", Manager);
                    }

                    foreach (System.Xml.XmlNode objN in codes)
                    {
                        st_recs.display += objN.InnerText + " -- ";
                        st_recs.main += "$" + objN.Attributes["code"].InnerText + objN.InnerText;
                    }

                    if (st_recs.display != null)
                    {
                        st_recs.display = st_recs.display.TrimEnd(" -".ToCharArray());
                    }
                    else
                    {
                        st_recs.display = "";
                    }

                }

                if (objNodes.Count <= 0)
                {

                    st_recs.main = "Undefined";
                    st_recs.xml = "<undefined>undefined</undefined>";
                }
                //}
                //catch
                //{
                //    return null;
                //}
                tp.Add(st_recs);
            }

            RecordCount = System.Convert.ToInt32(RetrievedRecords);
            return tp;
        }
Ejemplo n.º 46
0
        public List<IFileEntry> List()
        {
            System.Net.HttpWebRequest req = CreateRequest("");

            req.Method = "PROPFIND";
            req.Headers.Add("Depth", "1");
            req.ContentType = "text/xml";
            req.ContentLength = PROPFIND_BODY.Length;

            using (System.IO.Stream s = req.GetRequestStream())
                s.Write(PROPFIND_BODY, 0, PROPFIND_BODY.Length);

            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse())
                {
                    int code = (int)resp.StatusCode;
                    if (code < 200 || code >= 300) //For some reason Mono does not throw this automatically
                        throw new System.Net.WebException(resp.StatusDescription, null, System.Net.WebExceptionStatus.ProtocolError, resp);

                    if (!string.IsNullOrEmpty(m_debugPropfindFile))
                    {
                        using (System.IO.FileStream fs = new System.IO.FileStream(m_debugPropfindFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
                            Utility.Utility.CopyStream(resp.GetResponseStream(), fs, false);

                        doc.Load(m_debugPropfindFile);
                    }
                    else
                        doc.Load(resp.GetResponseStream());
                }

                System.Xml.XmlNamespaceManager nm = new System.Xml.XmlNamespaceManager(doc.NameTable);
                nm.AddNamespace("D", "DAV:");

                List<IFileEntry> files = new List<IFileEntry>();
                m_filenamelist = new List<string>();

                foreach (System.Xml.XmlNode n in doc.SelectNodes("D:multistatus/D:response/D:href", nm))
                {
                    //IIS uses %20 for spaces and %2B for +
                    //Apache uses %20 for spaces and + for +
                    string name = System.Web.HttpUtility.UrlDecode(n.InnerText.Replace("+", "%2B"));

                    string cmp_path;

                    //TODO: This list is getting ridiculous, should change to regexps

                    if (name.StartsWith(m_url))
                        cmp_path = m_url;
                    else if (name.StartsWith(m_rawurl))
                        cmp_path = m_rawurl;
                    else if (name.StartsWith(m_rawurlPort))
                        cmp_path = m_rawurlPort;
                    else if (name.StartsWith(m_path))
                        cmp_path = m_path;
                    else if (name.StartsWith(m_sanitizedUrl))
                        cmp_path = m_sanitizedUrl;
                    else if (name.StartsWith(m_reverseProtocolUrl))
                        cmp_path = m_reverseProtocolUrl;
                    else
                        continue;

                    if (name.Length <= cmp_path.Length)
                        continue;

                    name = name.Substring(cmp_path.Length);

                    long size = -1;
                    DateTime lastAccess = new DateTime();
                    DateTime lastModified = new DateTime();
                    bool isCollection = false;

                    System.Xml.XmlNode stat = n.ParentNode.SelectSingleNode("D:propstat/D:prop", nm);
                    if (stat != null)
                    {
                        System.Xml.XmlNode s = stat.SelectSingleNode("D:getcontentlength", nm);
                        if (s != null)
                            size = long.Parse(s.InnerText);
                        s = stat.SelectSingleNode("D:getlastmodified", nm);
                        if (s != null)
                            try
                            {
                                //Not important if this succeeds
                                lastAccess = lastModified = DateTime.Parse(s.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                            }
                            catch { }

                        s = stat.SelectSingleNode("D:iscollection", nm);
                        if (s != null)
                            isCollection = s.InnerText.Trim() == "1";
                        else
                            isCollection = (stat.SelectSingleNode("D:resourcetype/D:collection", nm) != null);
                    }

                    FileEntry fe = new FileEntry(name, size, lastAccess, lastModified);
                    fe.IsFolder = isCollection;
                    files.Add(fe);
                    m_filenamelist.Add(name);
                }

                return files;
            }
            catch (System.Net.WebException wex)
            {
                if (wex.Response as System.Net.HttpWebResponse != null &&
                        ((wex.Response as System.Net.HttpWebResponse).StatusCode == System.Net.HttpStatusCode.NotFound || (wex.Response as System.Net.HttpWebResponse).StatusCode == System.Net.HttpStatusCode.Conflict))
                    throw new Interface.FolderMissingException(string.Format(Strings.WEBDAV.MissingFolderError, m_path, wex.Message), wex);

                throw;
            }
        }
Ejemplo n.º 47
0
        private string[] ProcessHoldingResponse(string xmlResponse)
        {
            System.Collections.ArrayList alist = new System.Collections.ArrayList();
            string sMessage = "";

            System.Xml.XmlDocument objXML = new System.Xml.XmlDocument();
            objXML.LoadXml(xmlResponse);
            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(objXML.NameTable);
            nsmgr.AddNamespace("x", "http://www.w3.org/2005/Atom");
            nsmgr.AddNamespace("os", "http://a9.com/-/spec/opensearch/1.1/");
            nsmgr.AddNamespace("oclc", "http://worldcat.org/rb/holdinglibrary");

            sMessage = "";

            System.Xml.XmlNodeList nodes = objXML.SelectNodes("/x:feed/x:entry", nsmgr);
            if (nodes != null)
            {
                foreach (System.Xml.XmlNode node in nodes)
                {
                    sMessage = node.SelectSingleNode("x:content/oclc:library/oclc:holdingCode", nsmgr).InnerText;
                    alist.Add(sMessage);
                }
            }

            if (alist.Count > 0)
            {
                string[] arrOut = new string[alist.Count];
                alist.CopyTo(arrOut);
                return arrOut;
            }

            return null;
        }
Ejemplo n.º 48
0
        public static eagle Deserialize(string xml) {
            System.IO.StringReader stringReader = null;
            try {
                stringReader = new System.IO.StringReader(xml);

                // add a settings to allow DTD
                System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
                settings.DtdProcessing = System.Xml.DtdProcessing.Ignore;
                // map empty namespace to eagle for DTD based XML
                var nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
                // Add your namespaces used in the XML
                nsmgr.AddNamespace(String.Empty, "eagle");
                // Create the XmlParserContext using the previous declared XmlNamespaceManager
                var ctx = new System.Xml.XmlParserContext(null, nsmgr, null, System.Xml.XmlSpace.None);

                return ((eagle)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader, settings, ctx))));
            }
            finally {
                if ((stringReader != null)) {
                    stringReader.Dispose();
                }
            }
        }
 public void Valid_SingleUrlWithNamespace()
 {
     var xDoc = System.Xml.Linq.XDocument.Parse
         (
         Resources.ContentValidation.UrlValidator.Valid.SingleUrlWithNamespace,
         System.Xml.Linq.LoadOptions.SetLineInfo
         );
     System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
     nsmgr.AddNamespace("mlo", "http://purl.org/net/mlo");
     XCRI.Validation.ContentValidation.UrlValidator v = new XCRI.Validation.ContentValidation.UrlValidator()
     {
         XPathSelector = "//mlo:url",
         NamespaceManager = nsmgr
     };
     var vrc = v.Validate(xDoc.Root);
     Assert.AreEqual<int>(1, vrc.Count());
     var vr = vrc.ElementAt(0);
     Assert.IsNotNull(vr);
     Assert.AreEqual<XCRI.Validation.ContentValidation.ValidationStatus>
         (
         XCRI.Validation.ContentValidation.ValidationStatus.Passed,
         vr.Status
         );
     Assert.AreEqual<int>
         (
         1,
         vr.Count
         );
     Assert.AreEqual<int>
         (
         1,
         vr.SuccessCount
         );
     Assert.AreEqual<int>
         (
         0,
         vr.FailedCount
         );
     Assert.IsTrue(vr.Instances[0].LineNumber.HasValue);
     Assert.IsTrue(vr.Instances[0].LinePosition.HasValue);
     Assert.AreEqual<int>(vr.Instances[0].LineNumber.Value, 2);
     Assert.AreEqual<int>(vr.Instances[0].LinePosition.Value, 4);
 }
Ejemplo n.º 50
0
		protected virtual DataSet LoadFromFile()
		{
			if (m_FileName == null)
				throw new ApplicationException("FileName is null");

			System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
			xmlDoc.Load(m_FileName);

			System.Xml.XmlNamespaceManager namespaceMan = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable);
			namespaceMan.AddNamespace("fileds", c_DataNamespace);

			System.Xml.XmlNode tmp = xmlDoc.DocumentElement.SelectSingleNode("fileds:header", namespaceMan);
			if (tmp == null)
				throw new ApplicationException("File header not found");
			System.Xml.XmlElement header = (System.Xml.XmlElement)tmp;

			//File Version
			string strFileVersion = header.GetAttribute(c_FileVersion);
			int fileVersion = int.Parse( strFileVersion );
			if (fileVersion == c_FileVersionNumber)
			{
				string strDataFormat = header.GetAttribute(c_DataFormat);
				mFileDataFormat = (StreamDataSetFormat)int.Parse(strDataFormat);
			}
			else if (fileVersion == 0)
			{
				mFileDataFormat = StreamDataSetFormat.XML;
			}
			else if (fileVersion > c_FileVersionNumber)
				throw new ApplicationException("File Version not supported, expected: " + c_FileVersionNumber.ToString());

			//Data Version
			string strDataVersion = header.GetAttribute(c_DataVersion);
			int dataVersion = int.Parse( strDataVersion );
			DataSet dataSet = CreateData(dataVersion);

			//Data
			tmp = xmlDoc.DocumentElement.SelectSingleNode("fileds:data", namespaceMan);
			if (tmp == null)
				throw new ApplicationException("File data not found");
			System.Xml.XmlElement xmlDataNode = (System.Xml.XmlElement)tmp;

			byte[] xmlBuffer = System.Convert.FromBase64String( xmlDataNode.InnerText );
			using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(xmlBuffer))
			{
				StreamDataSet.Read(memStream, dataSet, mFileDataFormat, MergeReadedSchema);
				//dataSet.ReadXml(memStream);
			}

			return dataSet;
		}
Ejemplo n.º 51
0
		/// <summary>
		/// This static method will force a snapshot restore. Do not call this method as a matter of course - 
		/// only call it if your test absolutely requires that the database be restored from the snapshot.
		/// Consider rewriting your test to not require this restore (because a restore takes time, which causes 
		/// tests to run longer).
		/// In most cases, you don't need to call this method because the test input context and the URL test object
		/// will call it for you. Those will call the one-off RestoreFromSnapshot method instead.
		/// </summary>
		public static void ForceRestore(bool clearConnections)
		{
			try
			{
                Console.WriteLine("FORCE RESTORE");

                //get smallguide names
                string smallGuideName = "smallguide";
                string smallGuideSSName = "smallguideSS";

                if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["smallguideName"]))
                {
                    smallGuideName = ConfigurationManager.AppSettings["smallguideName"];
                }

                if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["smallguideSSName"]))
                {
                    smallGuideSSName = ConfigurationManager.AppSettings["smallguideSSName"];
                }

				//Use admin account for restoring small guide - get admin account for Web.Config ( alsoo used for creating dynamic lists)
				System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

				TestConfig config = TestConfig.GetConfig();
                doc.Load(config.GetRipleyServerPath() + @"\Web.Config");

				System.Xml.XmlNamespaceManager nsMgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
				nsMgr.AddNamespace("microsoft", @"http://schemas.microsoft.com/.NetConfiguration/v2.0");

				System.Xml.XmlNode node = doc.SelectSingleNode(@"/configuration/connectionStrings/add[@name='updateSP']", nsMgr);
				if (node == null)
				{
					Assert.Fail("Unable to read updateSP connnection string from Web.Config");
				}

                string updateSpConnString = node.Attributes["connectionString"].Value;



                // Check to make sure there are no connection on the small guide database
                bool noConnections = false;
                int tries = 0;
                DateTime start = DateTime.Now;
                Console.Write("Checking for connections on small guide -");

                // Keep checking while there's connections and we tried less than 24 times. We sleep for 5 seconds
                // in between each check. A total of 2 minutes before giving up.
                while (!noConnections && tries++ <= 24)
                {
                    using (IDnaDataReader reader = StoredProcedureReader.Create("", updateSpConnString))
                    {
                        string sql = "USE Master; SELECT 'count' = COUNT(*) FROM sys.sysprocesses sp INNER JOIN sys.databases db ON db.database_id = sp.dbid WHERE db.name = '" + smallGuideName + "' AND sp.SPID >= 50";
                        reader.ExecuteDEBUGONLY(sql);

                        if (reader.Read())
                        {
                            noConnections = (reader.GetInt32NullAsZero("count") == 0);
                        }

                        if (!noConnections)
                        {
                            if (clearConnections)
                            {
                                string clearConSql = @"ALTER DATABASE " + smallGuideName + @" SET OFFLINE WITH ROLLBACK IMMEDIATE;" +
                                                     @"ALTER DATABASE " + smallGuideName + @" SET ONLINE;";
                                reader.ExecuteDEBUGONLY(clearConSql);
                            }
                            else
                            {
                                // Goto sleep for 5 secs
                                System.Threading.Thread.Sleep(5000);
                                Console.Write("-");
                            }
                        }
                    }
                }

                // Change the tries into seconds and write to the console
                TimeSpan time = DateTime.Now.Subtract(start);
                Console.WriteLine("> waited for " + time.Seconds.ToString() + " seconds.");

				StringBuilder builder = new StringBuilder();
				builder.AppendLine("USE MASTER; ");
                //builder.AppendLine("ALTER DATABASE SmallGuide SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
				builder.AppendLine("RESTORE DATABASE " + smallGuideName +" FROM DATABASE_SNAPSHOT = '" + smallGuideSSName + "' ");
                //builder.AppendLine("ALTER DATABASE SmallGuide SET MULTI_USER WITH ROLLBACK IMMEDIATE");

				//Cannot Use Small Guide connection to restore Small Guide.
				//Cannot Restore SmallGuide whilst connections are open so close them by setting to single user.
                using (IDnaDataReader reader = StoredProcedureReader.Create("", updateSpConnString))
                {
                    Console.WriteLine(builder);
                    reader.ExecuteDEBUGONLY(builder.ToString());
                }
                //string conn = node.Attributes["connectionString"].InnerText;
                //BBC.Dna.DynamicLists.Dbo dbo = new BBC.Dna.DynamicLists.Dbo(conn);
				//dbo.ExecuteNonQuery(builder.ToString());

				//Need to force connection pool to drop connections too.
				//SqlConnection.ClearAllPools();

				Console.WriteLine("Restored SmallGuide from Snapshot successfully.");

				//DnaConfig config = new DnaConfig(System.Environment.GetEnvironmentVariable("dnapages") + @"\");
				//config.Initialise();
				//IDnaDataReader dataReader = new StoredProcedureReader("restoresmallguidefromsnapshot", config.ConnectionString, null);
				//dataReader.Execute();
				_hasRestored = true;
			}
			catch (Exception e)
			{
                Console.WriteLine("FAILED!!! SmallGuide Snapshot restore." + e.Message);
                Assert.Fail(e.Message);
            }
		}
Ejemplo n.º 52
0
        /// <summary>
        /// Extract the value of the statistic from the specified XML data.
        /// </summary>
        /// <param name="nav">A navigator into an XML document containing the statistic data.</param>
        /// <returns>The statistic value.</returns>
        protected virtual object Evaluate(XPathNavigator nav)
        {
            if (NameSpaces.Length == 0) return nav.Evaluate(xpath);

            System.Xml.XmlNamespaceManager nmsp = new System.Xml.XmlNamespaceManager(nav.NameTable);

            foreach (var s in NameSpaces)
            {
                if (s.Url == "default")
                {
                    nmsp.AddNamespace(s.Prefix, string.Empty);
                }
                else
                {
                    nmsp.AddNamespace(s.Prefix, s.Url);
                }
            }

            return nav.Evaluate(xpath,nmsp);
        }
Ejemplo n.º 53
0
        private Item createItem(System.Xml.XmlNode ItemXmlNode, String searchIndex)
        {
            Item item = new Item { };

            System.Xml.XmlNode MyXmlNode;
            System.Xml.XmlNode listPriceXmlNode;
            System.Xml.XmlDocument itemsXmlDocument;
            System.Xml.XmlNamespaceManager MyXmlNamespaceManager;
            itemsXmlDocument = new System.Xml.XmlDocument();
            itemsXmlDocument = new System.Xml.XmlDocument();
            MyXmlNamespaceManager = new System.Xml.XmlNamespaceManager(itemsXmlDocument.NameTable);
            MyXmlNamespaceManager.AddNamespace("amz", "http://webservices.amazon.com/AWSECommerceService/2011-08-01");

            MyXmlNode = ItemXmlNode.SelectSingleNode("amz:SmallImage/amz:URL", MyXmlNamespaceManager);
            if (MyXmlNode != null)
            {
                item.imgURL = MyXmlNode.InnerText;
            }

            MyXmlNode = ItemXmlNode.SelectSingleNode("amz:ItemAttributes/amz:Title", MyXmlNamespaceManager);
            item.Title = MyXmlNode.InnerText;

            if (searchIndex == "Books")
            {
                MyXmlNode = ItemXmlNode.SelectSingleNode("amz:ItemAttributes/amz:Author", MyXmlNamespaceManager);

                if (MyXmlNode != null)
                {
                    item.Author = "Author: " + MyXmlNode.InnerText;
                }
                else
                {
                    item.Author = "";
                }
            }
            else
            {
                item.Author = "";
            }

            MyXmlNode = ItemXmlNode.SelectSingleNode("amz:ItemAttributes/amz:ReleaseDate", MyXmlNamespaceManager);
            if (MyXmlNode != null)
            {
                item.ReleaseDate = "Release date: " + MyXmlNode.InnerText;
            }
            else
            {
                item.ReleaseDate = ""; ;
            }

            MyXmlNode = ItemXmlNode.SelectSingleNode("amz:ItemAttributes", MyXmlNamespaceManager);

            for (int i = 0; i < MyXmlNode.ChildNodes.Count; i++)
            {
                if (MyXmlNode.ChildNodes[i].LocalName == "ListPrice")
                {
                    listPriceXmlNode = MyXmlNode.ChildNodes[i];

                    for (int j = 0; j < listPriceXmlNode.ChildNodes.Count; j++)
                    {
                        if (listPriceXmlNode.ChildNodes[j].LocalName == "Amount")
                        {
                            double price = Convert.ToDouble(listPriceXmlNode.ChildNodes[j].InnerText) / 100;

                            item.Price = price;
                            item.strPrice = String.Format("{0:0.00}", price);
                        }
                    }
                    break;
                }
            }

            for (int k = 0; k < ItemXmlNode.ChildNodes.Count; k++)
            {
                if (ItemXmlNode.ChildNodes[k].LocalName == "EditorialReviews")
                {
                    item.productDescription = ItemXmlNode.ChildNodes[k].ChildNodes[0].ChildNodes[1].InnerText;
                    break;
                }
            }

            return item;
        }
Ejemplo n.º 54
0
        private string ProcessClassify(string s, oclc_api_classify.Class_Type ctype, bool bsummary, out string[] subjects)
        {
            LastError = "";

            subjects = null;
            System.Xml.XmlDocument objXML = new System.Xml.XmlDocument();
            System.Xml.XmlNamespaceManager oMan = new System.Xml.XmlNamespaceManager(objXML.NameTable);
            oMan.AddNamespace("oclc", "http://classify.oclc.org");
            try
            {

                objXML.LoadXml(s);

                //First check to see if this is is a record with multiple works
                System.Xml.XmlNodeList test_nodes = objXML.SelectNodes("//oclc:works/oclc:work", oMan);

                //System.Windows.Forms.MessageBox.Show(test_nodes.Count.ToString());
                if (test_nodes != null && test_nodes.Count > 0)
                {
                    try
                    {
                        string url = "http://classify.oclc.org/classify2/Classify?swid=" + test_nodes[0].Attributes["swid"].InnerText + "&summary=" + bsummary.ToString();
                        string txml = helpers.MakeOpenHTTPRequest(url, SetProxy, "GET"); // helpers.MakeHTTPRequest(url, SetProxy);

                        if (txml != "")
                        {
                            objXML.LoadXml(txml);
                        }
                        else
                        {
                            return "";
                        }
                    }
                    catch
                    {
                        return "";
                    }
                }

            }
            catch (System.Exception ee)
            {
                //System.Windows.Forms.MessageBox.Show(ee.ToString());
                LastError = s;
            }

            System.Xml.XmlNodeList objList;

            try
            {
                System.Collections.ArrayList tsubject = new System.Collections.ArrayList();
                //look to see if subjects are present
                objList = objXML.SelectNodes("//oclc:fast/oclc:headings/oclc:heading", oMan);
                if (objList != null)
                {
                    foreach (System.Xml.XmlNode objN in objList)
                    {
                        if (objN.Attributes["ident"] != null)
                        {
                            tsubject.Add(objN.Attributes["ident"].InnerText);
                        }
                    }
                    subjects = new string[tsubject.Count];
                    tsubject.CopyTo(subjects);
                }

                if (ctype == Class_Type.dd)
                {
                    objList = objXML.SelectNodes("//oclc:ddc/oclc:mostPopular", oMan);
                    if (objList != null)
                    {
                        foreach (System.Xml.XmlNode objN in objList)
                        {

                            if (objN.Attributes["nsfa"] != null)
                            {
                                return objN.Attributes["nsfa"].InnerText;
                                break;
                            }
                        }
                    }
                }
                else
                {

                    objList = objXML.SelectNodes("//oclc:lcc/oclc:mostPopular", oMan);
                    if (objList != null)
                    {
                        foreach (System.Xml.XmlNode objN in objList)
                        {
                            if (objN.Attributes["nsfa"] != null)
                            {
                                return objN.Attributes["nsfa"].InnerText;
                                break;
                            }
                        }
                    }
                    else
                    {
                        //System.Windows.Forms.MessageBox.Show("miss");
                    }
                }
                return "";
            }
            catch (Exception e)
            {
                LastError = e.ToString();
                return "";
            }
        }
Ejemplo n.º 55
0
        internal List<TableEntity> _QueryInternal(
            string NextPartitionKey,
            string NextRowKey,
            out string continuationNextPartitionKey,
            out string continuationNextRowKey,
            string xmsclientrequestId = null)
        {
            List<TableEntity> lEntities = new List<TableEntity>();

            string res = ITPCfSQL.Azure.Internal.InternalMethods.QueryTable(
                AzureTableService.UseHTTPS, AzureTableService.SharedKey, AzureTableService.AccountName, this.Name,
                NextPartitionKey, NextRowKey,
                out continuationNextPartitionKey, out continuationNextRowKey,
                xmsclientrequestId);

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            using (System.IO.StringReader sr = new System.IO.StringReader(res))
            {
                using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(sr))
                {
                    doc.Load(reader);
                }
            }

            System.Xml.XmlNamespaceManager man = new System.Xml.XmlNamespaceManager(doc.NameTable);
            man.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
            man.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
            man.AddNamespace("f", "http://www.w3.org/2005/Atom");

            foreach (System.Xml.XmlNode node in doc.SelectNodes("f:feed/f:entry", man))
            {
                System.Xml.XmlNode nCont = node.SelectSingleNode("f:content/m:properties", man);
                System.Xml.XmlNode nTimeStamp = nCont.SelectSingleNode("d:Timestamp", man);
                TableEntity te = new TableEntity()
                    {
                        PartitionKey = nCont.SelectSingleNode("d:PartitionKey", man).InnerText,
                        RowKey = nCont.SelectSingleNode("d:RowKey", man).InnerText,
                        TimeStamp = DateTime.Parse(nTimeStamp.InnerText)
                    };

                // custom attrib handling
                System.Xml.XmlNode nFollow = nTimeStamp.NextSibling;
                while (nFollow != null)
                {
                    te.Attributes[nFollow.LocalName] = nFollow.InnerText;
                    nFollow = nFollow.NextSibling;
                }

                lEntities.Add(te);

            }
            return lEntities;
        }
Ejemplo n.º 56
0
        static void Main(string[] _args)
        {
            List<string> args = new List<string>(_args);
            Dictionary<string, string> options = Duplicati.Library.Utility.CommandLineParser.ExtractOptions(args);

            if (args.Count != 1)
            {
                Console.WriteLine("Usage: ");
                Console.WriteLine("  WixProjBuilder.exe <projfile> [option=value]");
                return;
            }

            if (!System.IO.File.Exists(args[0]))
            {
                Console.WriteLine(string.Format("File not found: {0}", args[0]));
                return;
            }

            string wixpath;
            if (options.ContainsKey("wixpath"))
                wixpath = options["wixpath"];
            else
                wixpath = System.Environment.GetEnvironmentVariable("WIXPATH");

            if (string.IsNullOrEmpty(wixpath))
            {
                string[] known_wix_names = new string[] 
                {
                    "Windows Installer XML v3",
                    "Windows Installer XML v3.1",
                    "Windows Installer XML v3.2",
                    "Windows Installer XML v3.3",
                    "Windows Installer XML v3.4",
                    "Windows Installer XML v3.5",
                    "Windows Installer XML v3.6",
                    "Windows Installer XML v3.7",
                    "Windows Installer XML v3.8",
                    "Windows Installer XML v3.9",
                    "WiX Toolset v3.6",
                    "WiX Toolset v3.7",
                    "WiX Toolset v3.8",
                    "WiX Toolset v3.9",
                };

                foreach(var p in known_wix_names)
                {
                    foreach(var p2 in new string[] {"%ProgramFiles(x86)%", "%programfiles%"})
                    {
                        wixpath = System.IO.Path.Combine(System.IO.Path.Combine(Environment.ExpandEnvironmentVariables(p2), p), "bin");
                        if (System.IO.Directory.Exists(wixpath))
                        {
                            Console.WriteLine(string.Format("*** wixpath not specified, using: {0}", wixpath));
                            break;
                        }
                    }

                    if (System.IO.Directory.Exists(wixpath))
                        break;
                    }

            }


            if (!System.IO.Directory.Exists(wixpath))
            {
                Console.WriteLine(string.Format("WiX not found, please install Windows Installer XML 3 or greater"));
                Console.WriteLine(string.Format("  supply path to WiX bin folder with option --wixpath=...path..."));
                return;
            }

            args[0] = System.IO.Path.GetFullPath(args[0]);

            Console.WriteLine(string.Format("Parsing wixproj file: {0}", args[0]));

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(args[0]);

            string config = "Release";
            if (options.ContainsKey("configuration"))
                config = options["configuration"];

            string projdir = System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(args[0]));

            List<string> includes = new List<string>();
            List<string> refs = new List<string>();
            List<string> content = new List<string>();

            System.Xml.XmlNamespaceManager nm = new System.Xml.XmlNamespaceManager(doc.NameTable);
            nm.AddNamespace("ms", "http://schemas.microsoft.com/developer/msbuild/2003");

            foreach (System.Xml.XmlNode n in doc.SelectNodes("ms:Project/ms:ItemGroup/ms:Compile", nm))
                includes.Add(n.Attributes["Include"].Value);

            foreach (System.Xml.XmlNode n in doc.SelectNodes("ms:Project/ms:ItemGroup/ms:Content", nm))
                content.Add(n.Attributes["Include"].Value);

            foreach (System.Xml.XmlNode n in doc.SelectNodes("ms:Project/ms:ItemGroup/ms:WixExtension", nm))
                refs.Add(n.Attributes["Include"].Value);


            string objdir = System.IO.Path.Combine(System.IO.Path.Combine(projdir, "obj"), config);
            string packagename = "output";
            string outdir = System.IO.Path.Combine("bin", config);
            string outtype = "Package";

            //TODO: Support multiconfiguration system correctly
            foreach (System.Xml.XmlNode n in doc.SelectNodes("ms:Project/ms:PropertyGroup/ms:Configuration", nm))
                if (true) //if (string.Compare(n.InnerText, config, true) == 0)
                {
                    System.Xml.XmlNode p = n.ParentNode;
                    if (p["OutputName"] != null)
                        packagename = p["OutputName"].InnerText;
                    if (p["OutputType"] != null)
                        outtype = p["OutputType"].InnerText;
                    if (p["OutputPath"] != null)
                        outdir = p["OutputPath"].InnerText.Replace("$(Configuration)", config);
                    if (p["IntermediateOutputPath"] != null)
                        objdir = p["IntermediateOutputPath"].InnerText.Replace("$(Configuration)", config);
                }

            if (!objdir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                objdir += System.IO.Path.DirectorySeparatorChar;

            string msiname = System.IO.Path.Combine(outdir, packagename + ".msi");

            Console.WriteLine("  Compiling ... ");
            if (includes.Count == 0)
            {
                Console.WriteLine("No files found to compile in project file");
                return;
            }

            string compile_args = "\"" + string.Join("\" \"", includes.ToArray()) + "\"";
            compile_args += " -out \"" + objdir.Replace("\\", "\\\\") + "\"";

            if (options.ContainsKey("platform") && options["platform"] == "x64")
                compile_args += " -dPlatform=x64 -dWin64=yes";
            else
                compile_args += " -dPlatform=x86 -dWin64=no";

            int res = Execute(
                System.IO.Path.Combine(wixpath, "candle.exe"), 
                projdir,
                compile_args);

            if (res != 0)
            {
                Console.WriteLine("Compilation failed, aborting");
                return;
            }

            Console.WriteLine("  Linking ...");

            for (int i = 0; i < includes.Count; i++)
                includes[i] = System.IO.Path.Combine(objdir, System.IO.Path.GetFileNameWithoutExtension(includes[i]) + ".wixobj");

            for (int i = 0; i < refs.Count; i++)
                if (!System.IO.Path.IsPathRooted(refs[i]))
                {
                    refs[i] = FindDll(refs[i] + ".dll", new string[] { projdir, wixpath });
                    if (!System.IO.Path.IsPathRooted(refs[i]))
                        refs[i] = FindDll(refs[i]);
                }

            string link_args = "\"" + string.Join("\" \"", includes.ToArray()) + "\"";

            if (refs.Count > 0)
                link_args += " -ext \"" + string.Join("\" -ext \"", refs.ToArray()) + "\"";

            link_args += " -out \"" + msiname + "\"";

            res = Execute(
                System.IO.Path.Combine(wixpath, "light.exe"),
                projdir,
                link_args);

            if (res != 0)
            {
                Console.WriteLine("Link failed, aborting");
                return;
            }

            if (!System.IO.Path.IsPathRooted(msiname))
                msiname = System.IO.Path.GetFullPath(System.IO.Path.Combine(projdir, msiname));

            Console.WriteLine(string.Format("Done: {0}", msiname));
        }
 public IEnumerable<ContentValidation.IValidator> ExtractValidators(
     XDocument xdoc
     )
 {
     var xmlnsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
     // Extract namespace details
     foreach (var node in xdoc.XPathSelectElements("/contentValidators/namespaces/add"))
     {
         xmlnsmgr.AddNamespace
             (
             node.Attribute("prefix").Value,
             node.Attribute("namespace").Value
             );
     }
     // Extract document validators
     foreach (var node in xdoc.XPathSelectElements("/contentValidators/documentValidation"))
     {
         var d = new ContentValidation.DocumentValidator()
         {
             NamespaceManager = xmlnsmgr
         };
         if (null != this.Logs)
             foreach (var l in this.Logs)
                 d.Logs.Add(l);
         if (null != this.TimedLogs)
             foreach (var l in this.TimedLogs)
                 d.TimedLogs.Add(l);
         foreach (var validatorNode in node.XPathSelectElements("./*"))
         {
             var v = this.ExtractValidator(validatorNode);
             v.NamespaceManager = xmlnsmgr;
             d.Validators.Add(v);
         }
         yield return d;
     }
     // Extract element validators
     foreach (var node in xdoc.XPathSelectElements("/contentValidators/elementValidation"))
     {
         var selector = node.Attribute("selector").Value;
         var e = new ContentValidation.ElementValidator()
         {
             NamespaceManager = xmlnsmgr,
             XPathSelector = selector
         };
         if (null != this.Logs)
             foreach (var l in this.Logs)
                 e.Logs.Add(l);
         if (null != this.TimedLogs)
             foreach (var l in this.TimedLogs)
                 e.TimedLogs.Add(l);
         foreach (var validatorNode in node.XPathSelectElements("./*"))
         {
             var v = this.ExtractValidator(validatorNode);
             v.NamespaceManager = xmlnsmgr;
             e.Validators.Add(v);
         }
         yield return e;
     }
 }
Ejemplo n.º 58
0
		public static string GetExplicitIndexingInfo(bool fullTable)
		{
			var infoArray = new List<ExplicitPerFieldIndexingInfo>(Current.ContentTypes.Count * 5);
			foreach (var contentType in Current.ContentTypes.Values)
			{
				var xml = new System.Xml.XmlDocument();
				var nsmgr = new System.Xml.XmlNamespaceManager(xml.NameTable);
				var fieldCount = 0;

				nsmgr.AddNamespace("x", ContentType.ContentDefinitionXmlNamespace);
				xml.Load(contentType.Binary.GetStream());
				foreach (System.Xml.XmlElement fieldElement in xml.SelectNodes("/x:ContentType/x:Fields/x:Field", nsmgr))
				{
					var typeAttr = fieldElement.Attributes["type"];
					if (typeAttr == null)
						typeAttr = fieldElement.Attributes["handler"];

					var info = new ExplicitPerFieldIndexingInfo
					{
						ContentTypeName = contentType.Name,
						ContentTypePath = contentType.Path.Replace(Repository.ContentTypesFolderPath + "/", String.Empty),
						FieldName = fieldElement.Attributes["name"].Value,
						FieldType = typeAttr.Value
					};

					var fieldTitleElement = fieldElement.SelectSingleNode("x:DisplayName", nsmgr);
					if (fieldTitleElement != null)
						info.FieldTitle = fieldTitleElement.InnerText;

					var fieldDescElement = fieldElement.SelectSingleNode("x:Description", nsmgr);
					if (fieldDescElement != null)
						info.FieldDescription = fieldDescElement.InnerText;

					var hasIndexing = false;
					foreach (System.Xml.XmlElement element in fieldElement.SelectNodes("x:Indexing/*", nsmgr))
					{
						hasIndexing = true;
						switch (element.LocalName)
						{
							case "Analyzer": info.Analyzer = element.InnerText.Replace("Lucene.Net.Analysis", "."); break;
							case "IndexHandler": info.IndexHandler = element.InnerText.Replace("SenseNet.Search", "."); break;
							case "Mode": info.IndexingMode = element.InnerText; break;
							case "Store": info.IndexStoringMode = element.InnerText; break;
							case "TermVector": info.TermVectorStoringMode = element.InnerText; break;
						}
					}

					fieldCount++;

					if(hasIndexing || fullTable)
						infoArray.Add(info);
				}

				//hack: content type without fields
				if (fieldCount == 0 && fullTable)
				{
					var info = new ExplicitPerFieldIndexingInfo
					{
						ContentTypeName = contentType.Name,
						ContentTypePath = contentType.Path.Replace(Repository.ContentTypesFolderPath + "/", String.Empty),
					};

					infoArray.Add(info);
				}
			}

			var sb = new StringBuilder();
			sb.AppendLine("TypePath\tType\tField\tFieldTitle\tFieldDescription\tFieldType\tMode\tStore\tTVect\tHandler\tAnalyzer");
			foreach (var info in infoArray)
			{
				sb.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}",
					info.ContentTypePath,
					info.ContentTypeName,
					info.FieldName,
					info.FieldTitle,
					info.FieldDescription,
					info.FieldType,
					info.IndexingMode,
					info.IndexStoringMode,
					info.TermVectorStoringMode,
					info.IndexHandler,
					info.Analyzer);
				sb.AppendLine();
			}
			return sb.ToString();
		}
 public IEnumerable<XmlExceptionInterpretation.IInterpreter> ExtractInterpreters(
     XDocument xdoc
     )
 {
     var xmlnsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
     // Extract namespace details
     foreach (var node in xdoc.XPathSelectElements("/interpreters/namespaces/add"))
     {
         xmlnsmgr.AddNamespace
             (
             node.Attribute("prefix").Value,
             node.Attribute("namespace").Value
             );
     }
     // Extract interpreters
     foreach (var node in xdoc.XPathSelectElements("/interpreters/*"))
     {
         yield return this.ExtractInterpreter(node);
     }
 }