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
        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;

        }
 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_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);
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Writes DataSet as .ods file.
        /// </summary>
        /// <param name="odsFile">DataSet that represent .ods file.</param>
        /// <param name="outputFilePath">The name of the file to save to.</param>
        public void WriteOdsFile(System.Data.DataSet odsFile, string outputFilePath)
        {
            Ionic.Zip.ZipFile templateFile = this.GetZipFile(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(OdsReaderWriter).Namespace + ".template.ods"));

            System.Xml.XmlDocument contentXml = this.GetContentXmlFile(templateFile);

            System.Xml.XmlNamespaceManager nmsManager = this.InitializeXmlNamespaceManager(contentXml);

            System.Xml.XmlNode sheetsRootNode = this.GetSheetsRootNodeAndRemoveChildrens(contentXml, nmsManager);

            foreach (System.Data.DataTable sheet in odsFile.Tables)
            {
                this.SaveSheet(sheet, sheetsRootNode);
            }

            this.SaveContentXml(templateFile, contentXml);

            templateFile.Save(outputFilePath);
        }
Ejemplo n.º 6
0
        } // End Function GetTableNodes

        private System.Data.DataTable GetSheet(
            System.Xml.XmlNode tableNode
            , System.Xml.XmlNamespaceManager nmsManager)
        {
            System.Data.DataTable sheet =
                new System.Data.DataTable(tableNode.Attributes["table:name"].Value);

            System.Xml.XmlNodeList rowNodes = tableNode
                                              .SelectNodes("table:table-row", nmsManager);

            int rowIndex = 0;

            foreach (System.Xml.XmlNode rowNode in rowNodes)
            {
                this.GetRow(rowNode, sheet, nmsManager, ref rowIndex);
            }

            return(sheet);
        } // End Function GetSheet
Ejemplo n.º 7
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.º 8
0
        /// <summary>
        /// Read .ods file and store it in DataSet.
        /// </summary>
        /// <param name="inputFilePath">Path to the .ods file.</param>
        /// <returns>DataSet that represents .ods file.</returns>
        public System.Data.DataSet ReadOdsFile(string inputFilePath)
        {
            Ionic.Zip.ZipFile odsZipFile = this.GetZipFile(inputFilePath);

            // Get content.xml file
            System.Xml.XmlDocument contentXml = this.GetContentXmlFile(odsZipFile);

            // Initialize XmlNamespaceManager
            System.Xml.XmlNamespaceManager nmsManager = this.InitializeXmlNamespaceManager(contentXml);

            System.Data.DataSet odsFile = new System.Data.DataSet(System.IO.Path.GetFileName(inputFilePath));

            foreach (System.Xml.XmlNode tableNode in this.GetTableNodes(contentXml, nmsManager))
            {
                odsFile.Tables.Add(this.GetSheet(tableNode, nmsManager));
            }

            return(odsFile);
        }
Ejemplo n.º 9
0
        private System.Xml.XmlNamespaceManager CreateNamespaceMgr(DefaultNsBehaviourEnum defaultNsBehaviour, string prefixForDefaultNS)
        {
            if (DefaultNsBehaviourEnum.Remove == defaultNsBehaviour)
            {
                base.InnerXml = System.Text.RegularExpressions.Regex.Replace(base.InnerXml, "xmlns=\"[^ ]*\" ", "");
            }

            System.Collections.Specialized.NameValueCollection namespaces = GetNamespaces(base.DocumentElement, prefixForDefaultNS ?? "");
            System.Xml.XmlNamespaceManager namespaceMgr = null;
            if (0 != namespaces.Count)
            {
                namespaceMgr = new System.Xml.XmlNamespaceManager(base.NameTable);
                for (int i = 0; i < namespaces.Count; i++)
                {
                    namespaceMgr.AddNamespace(namespaces.Keys[i], namespaces[i]);
                }
            }
            return(namespaceMgr);
        }
Ejemplo n.º 10
0
        public static AtomFeed load_from_dom(System.Xml.XmlDocument dom, System.Xml.XmlNamespaceManager nsmgr)
        {
            var root = dom.DocumentElement;

            var afeed = new AtomFeed();

            afeed.ID        = root.SelectSingleInnerText("atom:id", nsmgr);
            afeed._title    = root.SelectSingleInnerText("atom:title", nsmgr);
            afeed._subTitle = root.SelectSingleInnerText("atom:subtitle", nsmgr);


            afeed._links = new List <AtomLink>();
            afeed._links.AddRange(get_links(root, nsmgr));

            var entry_nodes = root.SelectNodes("atom:entry", nsmgr);

            foreach (var entry_node in entry_nodes.AsEnumerable())
            {
                var aentry = new AtomEntry();
                aentry.AuthorName  = entry_node.SelectSingleInnerText("atom:author/atom:name", nsmgr);
                aentry.AuthorEmail = entry_node.SelectSingleInnerText("atom:author/atom:email", nsmgr);
                aentry.AuthorURI   = entry_node.SelectSingleInnerText("atom:author/atom:uri", nsmgr);
                aentry.Updated     = System.DateTimeOffset.Parse(entry_node.SelectSingleInnerText("atom:updated", nsmgr), System.Globalization.CultureInfo.InvariantCulture);

                aentry.Content = entry_node.SelectSingleInnerText("atom:content", nsmgr);
                var content_node = (System.Xml.XmlElement)entry_node.SelectSingleNode("atom:content", nsmgr);
                if (content_node != null)
                {
                    aentry.ContentType = content_node.GetAttribute("type");
                }

                aentry.Link    = entry_node.SelectSingleInnerText("atom:link", nsmgr);
                aentry.Id      = entry_node.SelectSingleInnerText("atom:id", nsmgr);
                aentry.Title   = entry_node.SelectSingleInnerText("atom:title", nsmgr);
                aentry.Summary = entry_node.SelectSingleInnerText("atom:summary", nsmgr);
                aentry.Links   = new List <AtomLink>();
                aentry.Links.AddRange(get_links(entry_node, nsmgr));
                afeed._entries.Add(aentry);
            }

            return(afeed);
        }
Ejemplo n.º 11
0
        public static bool _SelectNodes_System_Xml_XmlEntity_System_String_System_Xml_XmlNamespaceManager( )
        {
            //Parameters
            System.String xpath = null;
            System.Xml.XmlNamespaceManager nsmgr = null;

            //ReturnType/Value
            System.Xml.XmlNodeList returnVal_Real        = null;
            System.Xml.XmlNodeList returnVal_Intercepted = null;

            //Exception
            Exception exception_Real        = null;
            Exception exception_Intercepted = null;

            InterceptionMaintenance.disableInterception( );

            try
            {
                returnValue_Real = System.Xml.XmlEntity.SelectNodes(xpath, nsmgr);
            }

            catch (Exception e)
            {
                exception_Real = e;
            }


            InterceptionMaintenance.enableInterception( );

            try
            {
                returnValue_Intercepted = System.Xml.XmlEntity.SelectNodes(xpath, nsmgr);
            }

            catch (Exception e)
            {
                exception_Intercepted = e;
            }


            Return((exception_Real.Messsage == exception_Intercepted.Message) && (returnValue_Real == returnValue_Intercepted));
        }
Ejemplo n.º 12
0
        public static bool _SelectSingleNode_System_Configuration_ConfigXmlDocument_System_String_System_Xml_XmlNamespaceManager( )
        {
            //Parameters
            System.String xpath = null;
            System.Xml.XmlNamespaceManager nsmgr = null;

            //ReturnType/Value
            System.Xml.XmlNode returnVal_Real        = null;
            System.Xml.XmlNode returnVal_Intercepted = null;

            //Exception
            Exception exception_Real        = null;
            Exception exception_Intercepted = null;

            InterceptionMaintenance.disableInterception( );

            try
            {
                returnValue_Real = System.Configuration.ConfigXmlDocument.SelectSingleNode(xpath, nsmgr);
            }

            catch (Exception e)
            {
                exception_Real = e;
            }


            InterceptionMaintenance.enableInterception( );

            try
            {
                returnValue_Intercepted = System.Configuration.ConfigXmlDocument.SelectSingleNode(xpath, nsmgr);
            }

            catch (Exception e)
            {
                exception_Intercepted = e;
            }


            Return((exception_Real.Messsage == exception_Intercepted.Message) && (returnValue_Real == returnValue_Intercepted));
        }
Ejemplo n.º 13
0
        public static void AddOrReplaceParameter(string strFilename, string parameterName, string strAppendAfterParameter, string fragment)
        {
            string strName = GetNameFromFragment(fragment);

            if (!StringComparer.InvariantCultureIgnoreCase.Equals(strName, parameterName))
            {
                throw new Exception("Parameter name mismatch - \"" + parameterName + "\" != \"" + strName + "\"");
            }

            System.Xml.XmlNode xnPrevious = null;
            System.Xml.XmlNode xn         = GetParameter(strFilename, parameterName);
            bool bFirst = false;


            if (xn != null)
            {
                xnPrevious = xn.PreviousSibling;
                xn.ParentNode.RemoveChild(xn);
                XmlTools.SaveDocument(xn.OwnerDocument, strFilename, true);
            } // End if (xn != null)

            if (xnPrevious == null)
            {
                xnPrevious = GetParameter(strFilename, strAppendAfterParameter);
            } // End if (xnPrevious == null)

            if (xnPrevious == null)
            {
                System.Xml.XmlDocument         doc   = XmlTools.File2XmlDocument(strFilename);
                System.Xml.XmlNamespaceManager nsmgr = GetReportNamespaceManager(doc);
                xnPrevious = doc.SelectSingleNode("/dft:Report/dft:ReportParameters", nsmgr);
                bFirst     = true;


                if (xnPrevious == null)
                {
                    return;
                }
            } // End if (xnPrevious == null)

            AddCustomParameter(strFilename, xnPrevious, bFirst, false, fragment);
        } // End Sub AddOrReplaceParameter
        /// <summary>
        /// Set the current element's content from the current XML node
        /// </summary>
        /// <param name="node"></param>
        /// <param name="mgr"></param>
        protected override void ReadXml(System.Xml.XmlNode node, System.Xml.XmlNamespaceManager mgr)
        {
            var gt   = Utility.GetFdoAttribute(node, "geometricTypes");   //NOXLATE
            var gt2  = Utility.GetFdoAttribute(node, "geometryTypes");    //NOXLATE
            var gtro = Utility.GetFdoAttribute(node, "geometryReadOnly"); //NOXLATE
            var hms  = Utility.GetFdoAttribute(node, "hasMeasure");       //NOXLATE
            var hev  = Utility.GetFdoAttribute(node, "hasElevation");     //NOXLATE
            var srs  = Utility.GetFdoAttribute(node, "srsName");          //NOXLATE

            this.GeometricTypes = ProcessGeometricTypes(gt.Value);
            if (gt2 != null)
            {
                this.SpecificGeometryTypes = ProcessSpecificGeometryTypes(gt2.Value);
            }

            this.IsReadOnly   = (gtro != null && Convert.ToBoolean(gtro.Value));
            this.HasElevation = (hev != null && Convert.ToBoolean(hev.Value));
            this.HasMeasure   = (hms != null && Convert.ToBoolean(hms.Value));
            this.SpatialContextAssociation = (srs != null ? srs.Value : string.Empty);
        }
Ejemplo n.º 15
0
        public static string ShowNamespaceManager(System.Xml.XmlNamespaceManager nsmgr)
        {
            string s = "";
            string sThis;

            foreach (object ns in nsmgr)
            {
                sThis = ns.GetType().Name + vbTab;
                if (sThis == null)
                {
                    sThis += "null" + vbcrlf;
                }
                else
                {
                    sThis += s.ToString() + vbcrlf;
                }
                s += sThis;
            }
            return(s);
        }
 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
         );
 }
 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.º 18
0
        private static void ColumnMethods(System.CodeDom.Compiler.IndentedTextWriter inWriter,
                                          System.Xml.XmlNamespaceManager nsmgr,
                                          System.Xml.XmlNode node)
        {
            string netTypeName = Utility.Tools.GetAttributeOrEmpty(node, "NETType");
            string name        = Utility.Tools.GetAttributeOrEmpty(node, "Name");

            if (netTypeName.Trim().Length == 0)
            {
                inWriter.WriteLine("");
                inWriter.WriteLine("// Column " + name + " is not included because it uses");
                inWriter.WriteLine("// a SQLType (" + netTypeName + ") that is not yet supported");
                inWriter.WriteLine("");
            }
            else
            {
                inWriter.WriteLine("public ColumnInfo " + name + "()");
                Support.WriteLineAndIndent(inWriter, "{");
                inWriter.WriteLine("ColumnInfo columnInfo = new ColumnInfo");
                inWriter.WriteLine("columnInfo.FieldName = " + Support.DQ + name + Support.DQ);
                inWriter.WriteLine("columnInfo.FieldType = GetType(" + netTypeName + ")");
                inWriter.WriteLine("columnInfo.SQLType = " + Support.DQ + Utility.Tools.GetAttributeOrEmpty(node, "SQLType") + Support.DQ);
                inWriter.WriteLine("columnInfo.Caption = " + Support.DQ + Utility.Tools.GetAttributeOrEmpty(node, "Caption") + Support.DQ);
                inWriter.WriteLine("columnInfo.Desc = " + Support.DQ + Utility.Tools.GetAttributeOrEmpty(node, "Desc") + Support.DQ);
                inWriter.WriteLine("return columnInfo");
                Support.WriteLineAndOutdent(inWriter, "}");

                inWriter.WriteLine("");
                inWriter.WriteLine("public " + netTypeName + " " + name);
                Support.WriteLineAndIndent(inWriter, "{");
                inWriter.WriteLine("get");
                Support.WriteLineAndIndent(inWriter, "{");
                inWriter.WriteLine("return m" + name + ";");
                Support.WriteLineAndOutdent(inWriter, "}");
                inWriter.WriteLine("set");
                Support.WriteLineAndIndent(inWriter, "{");
                inWriter.WriteLine("m" + name + " = value;");
                Support.WriteLineAndOutdent(inWriter, "}");
                Support.WriteLineAndOutdent(inWriter, "}");
            }
        }
        ParseArtifactNamesAndVersionsFromXML
        (
            string xml
        )
        {
            System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
            xmldoc.LoadXml(xml);
            System.Xml.XmlNamespaceManager ns = new System.Xml.XmlNamespaceManager(xmldoc.NameTable);

            System.Xml.XmlNodeList node_list = xmldoc.SelectNodes($"/{this.Name}/*", ns);
            foreach (System.Xml.XmlNode xn in node_list)
            {
                string   n  = xn.Name;
                string[] vs = xn.Attributes["versions"].InnerXml.Split
                              (
                    new string[] { "," },
                    StringSplitOptions.RemoveEmptyEntries
                              );
                yield return(name : n, versions : vs);
            }
        }
Ejemplo n.º 20
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.º 21
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.º 22
0
        private void buttonDoFilter_Click(object sender, EventArgs e)
        {
            try
            {
                var xml = new System.Xml.XmlDocument();
                xml.LoadXml(textBoxExInput.Text);

                var xnm = new System.Xml.XmlNamespaceManager(xml.NameTable);

                var result = xml.SelectNodes(comboBoxXPath.Text, xnm);
                textBoxExOutput.Text = string.Join("\r\n\r\n--------------------\r\n\r\n", result.Cast <System.Xml.XmlNode>().Select(f => FormatXmlDocument(f.OuterXml)));
                if (textBoxExOutput.Text.Length == 0)
                {
                    textBoxExOutput.Text = "No results.";
                }
            }
            catch (System.Exception ex)
            {
                textBoxExOutput.Text = string.Format("[{0}]\r\n{1}", ex.GetType().Name, ex.Message);
            }
        }
Ejemplo n.º 23
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.º 24
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.º 25
0
        /// <summary>
        /// Validates the given XML document.
        /// </summary>
        /// <param name="input">XML document as stream.</param>
        /// <param name="ser">Serialiser.</param>
        /// <exception cref="InvalidOperationException">Thrown if the document is invalid.</exception>
        public void Validate(System.IO.Stream input, Type type)
        {
            var settings = GetSettings();

            // Adding the event handler of this object
            settings.ValidationEventHandler += Settings_ValidationEventHandler;

            // Clearing validation messages
            m_validationMessages.Clear();

            // Out of the box, XLink attributes have not worked as they should.
            // They exist as default attributes in some places (have forgotten if
            // this is in the XML schemata or added manually in MessageSerialiser).
            // Anyway, because XLink attributes come from a namespace unknown to the parser,
            // there must be a namespace manager to explicitly declare the XLink namespace.
            var nametable    = new System.Xml.NameTable();
            var xmlNsManager = new System.Xml.XmlNamespaceManager(nametable);

            xmlNsManager.AddNamespace("xlink", "http://www.w3.org/1999/xlink");

            // This context object is mandatory to pass the namespace manager to the parser.
            var parserContext = new System.Xml.XmlParserContext(null, xmlNsManager, null, System.Xml.XmlSpace.None);

            using (var reader = System.Xml.XmlReader.Create(input, settings, parserContext))
            {
                // Deserialising the document
                var serializer = new System.Xml.Serialization.XmlSerializer(type);
                serializer.Deserialize(reader);
            }

            // Removing the event handler of this object (this would
            // otherwise cause conflicts when multiple documents are validated)
            settings.ValidationEventHandler -= Settings_ValidationEventHandler;

            if (m_validationMessages.Count > 0)
            {
                var msg = string.Format("The XML document has {0} errors. First error: {1}", m_validationMessages.Count, m_validationMessages[0]);
                throw new InvalidOperationException(msg);
            }
        }
Ejemplo n.º 26
0
        public static System.IO.Stream GetStream(string name,
                                                 string fileName,
                                                 string genDateTime,
                                                 System.Xml.XmlNode nodeSelect)
        {
            System.Console.WriteLine("Test");
            System.Console.ReadLine();
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.CodeDom.Compiler.IndentedTextWriter inWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(stream));

            System.Xml.XmlNodeList nodeList;
            string singularName = Utility.Tools.GetAttributeOrEmpty(nodeSelect, "SingularName");

            System.Xml.XmlNamespaceManager nsmgr = Utility.Tools.BuildNamespaceManager(nodeSelect.OwnerDocument, "dbs", false);

            Support.FileOpen(inWriter, "KADGen,System", fileName, genDateTime);
            inWriter.WriteLine("");
            Support.WriteLineAndIndent(inWriter, "public class " + singularName + "Collection : CollectionBase");
            CollectionConstructors(inWriter, nsmgr, nodeSelect);
            PublicAndFriend(inWriter, nsmgr, nodeSelect);
            Support.WriteLineAndOutdent(inWriter, "}");

            inWriter.WriteLine("");
            inWriter.WriteLine("");
            Support.WriteLineAndIndent(inWriter, "public class " + singularName + " : RowBase");
            ClassLevelDeclarations(inWriter, nsmgr, nodeSelect);
            Constructors(inWriter, nsmgr, nodeSelect);
            BaseClassImplementation(inWriter, nsmgr, nodeSelect);
            Support.MakeRegion(inWriter, "Field access properties");
            nodeList = nodeSelect.SelectNodes("dbs:TableColumns/*", nsmgr);
            foreach (System.Xml.XmlNode nodeColumn in nodeList)
            {
                ColumnMethods(inWriter, nsmgr, nodeColumn);
            }
            Support.EndRegion(inWriter);
            Support.WriteLineAndIndent(inWriter, "End Class");

            inWriter.Flush();
            return(stream);
        }
Ejemplo n.º 27
0
        public void Valid_IdentifierReusedByMultipleCourses()
        {
            var xDoc = System.Xml.Linq.XDocument.Parse
                       (
                Resources.ContentValidation.UniqueValidator.Valid.IdentifierReusedByMultipleCourses,
                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.Passed,
                vr.Status
            );
            Assert.AreEqual <int>
            (
                3,
                vr.Count
            );
            Assert.AreEqual <int>
            (
                3,
                vr.SuccessCount
            );
        }
        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));
            }
        }
        public static bool _ctor_System_Xml_XmlParserContext_System_Xml_XmlNameTable_System_Xml_XmlNamespaceManager_System_String_System_Xml_XmlSpace_System_Text_Encoding( )
        {
            //Parameters
            System.Xml.XmlNameTable        nt    = null;
            System.Xml.XmlNamespaceManager nsMgr = null;
            System.String        xmlLang         = null;
            System.Xml.XmlSpace  xmlSpace        = null;
            System.Text.Encoding enc             = null;


            //Exception
            Exception exception_Real        = null;
            Exception exception_Intercepted = null;

            InterceptionMaintenance.disableInterception( );

            try
            {
                returnValue_Real = System.Xml.XmlParserContext.ctor(nt, nsMgr, xmlLang, xmlSpace, enc);
            }

            catch (Exception e)
            {
                exception_Real = e;
            }


            InterceptionMaintenance.enableInterception( );

            try
            {
                returnValue_Intercepted = System.Xml.XmlParserContext.ctor(nt, nsMgr, xmlLang, xmlSpace, enc);
            }

            catch (Exception e)
            {
                exception_Intercepted = e;
            }
        }
Ejemplo n.º 30
0
        public static System.Xml.XmlNamespaceManager BuildNamespacesManagerForDoc(System.Xml.XmlDocument xmlDoc, string defaultNamespacePrefix)
        {
            System.Xml.XmlNodeList         nodes;
            System.Xml.XmlNamespaceManager nsmgrXML = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable);
            nspaceLookup nSpace;

            System.Collections.Hashtable collection = new System.Collections.Hashtable();
            System.Diagnostics.Debug.WriteLine(DateTime.Now);
            nodes = xmlDoc.SelectNodes("//*");
            foreach (System.Xml.XmlNode node in nodes)
            {
                nSpace        = new nspaceLookup();
                nSpace.nspace = node.NamespaceURI;
                nSpace.prefix = node.Prefix;
                if (!collection.Contains(nSpace.prefix + ":" + nSpace.nspace))
                {
                    collection.Add(nSpace.prefix + ":" + nSpace.nspace, nSpace);
                }
            }
            System.Diagnostics.Debug.WriteLine(DateTime.Now);

            foreach (System.Collections.DictionaryEntry d in collection)
            {
                nSpace = ((nspaceLookup)(d.Value));
                if (nSpace.prefix.Trim().Length == 0)
                {
                    nSpace.prefix = defaultNamespacePrefix;
                }
                nsmgrXML.AddNamespace(nSpace.prefix, nSpace.nspace);
            }
            nsmgrXML.AddNamespace("kg", "http://kadgen.com/KADGenDriving.xsd");

            foreach (string prefix in nsmgrXML)
            {
                Console.WriteLine("Prefix={0}, Namespace={1}", prefix, nsmgrXML.LookupNamespace(prefix));
            }

            return(nsmgrXML);
        }
        static StackObject *AddNamespace_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.String @uri = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.String @prefix = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Xml.XmlNamespaceManager instance_of_this_method = (System.Xml.XmlNamespaceManager) typeof(System.Xml.XmlNamespaceManager).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            instance_of_this_method.AddNamespace(@prefix, @uri);

            return(__ret);
        }
Ejemplo n.º 32
0
        private void GetCell(System.Xml.XmlNode cellNode, System.Data.DataRow row, System.Xml.XmlNamespaceManager nmsManager, ref int cellIndex)
        {
            System.Xml.XmlAttribute cellRepeated = cellNode.Attributes["table:number-columns-repeated"];

            if (cellRepeated == null)
            {
                System.Data.DataTable sheet = row.Table;

                while (sheet.Columns.Count <= cellIndex)
                {
                    sheet.Columns.Add();
                }

                row[cellIndex] = this.ReadCellValue(cellNode);

                cellIndex++;
            }
            else
            {
                cellIndex += System.Convert.ToInt32(cellRepeated.Value, System.Globalization.CultureInfo.InvariantCulture);
            }
        }
Ejemplo n.º 33
0
        static StackObject *SelectSingleNode_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Xml.XmlNamespaceManager @nsmgr = (System.Xml.XmlNamespaceManager) typeof(System.Xml.XmlNamespaceManager).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.String @xpath = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Xml.XmlNode instance_of_this_method = (System.Xml.XmlNode) typeof(System.Xml.XmlNode).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.SelectSingleNode(@xpath, @nsmgr);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Ejemplo n.º 34
0
        public static void ClassLevelDeclarations(System.CodeDom.Compiler.IndentedTextWriter inWriter,
                                                  System.Xml.XmlNamespaceManager nsmgr,
                                                  System.Xml.XmlNode node)
        {
            System.Xml.XmlNodeList nodeList;
            string pre = "";

            Support.MakeRegion(inWriter, "Class Level Declarations");
            inWriter.WriteLine(string.Format("protected {0} mCollection;", Utility.Tools.GetAttributeOrEmpty(node, "SingularName")));
            inWriter.WriteLine("private static int mNextPrimaryKey = -1;");
            nodeList = node.SelectNodes("dbs:TableColumns/*", nsmgr);
            inWriter.WriteLine("");
            foreach (System.Xml.XmlNode nodeSub in nodeList)
            {
                if (Utility.Tools.GetAttributeOrEmpty(nodeSub, "NETType").Length == 0)
                {
                    pre = "// ";
                }
                inWriter.WriteLine(string.Format("{0}private {1} {2};", pre, Utility.Tools.GetAttributeOrEmpty(nodeSub, "NETType"), Utility.Tools.GetAttributeOrEmpty(nodeSub, "Name")));
            }
            Support.EndRegion(inWriter);
        }
Ejemplo n.º 35
0
        public static MapInfoDocument Parse(XDocument xmldoc, System.Xml.XmlNamespaceManager NameSpaceManager)
        {
            MapInfoDocument doc = new MapInfoDocument();

            doc.map     = new CT_MapInfo();
            doc.map.Map = new System.Collections.Generic.List <CT_Map>();
            foreach (XElement mapNode in xmldoc.XPathSelectElements("d:MapInfo/d:Map", NameSpaceManager))
            {
                CT_Map ctMap = new CT_Map();
                ctMap.ID          = XmlHelper.ReadUInt(mapNode.GetAttributeNode("ID"));
                ctMap.Name        = XmlHelper.ReadString(mapNode.GetAttributeNode("Name"));
                ctMap.RootElement = XmlHelper.ReadString(mapNode.GetAttributeNode("RootElement"));
                ctMap.SchemaID    = XmlHelper.ReadString(mapNode.GetAttributeNode("SchemaID"));
                ctMap.ShowImportExportValidationErrors = XmlHelper.ReadBool(mapNode.GetAttributeNode("ShowImportExportValidationErrors"));
                ctMap.PreserveFormat       = XmlHelper.ReadBool(mapNode.GetAttributeNode("PreserveFormat"));
                ctMap.PreserveSortAFLayout = XmlHelper.ReadBool(mapNode.GetAttributeNode("PreserveSortAFLayout"));
                ctMap.Append  = XmlHelper.ReadBool(mapNode.GetAttributeNode("Append"));
                ctMap.AutoFit = XmlHelper.ReadBool(mapNode.GetAttributeNode("AutoFit"));
                doc.map.Map.Add(ctMap);
            }
            doc.map.Schema = new System.Collections.Generic.List <CT_Schema>();
            foreach (XElement schemaNode in xmldoc.XPathSelectElements("d:MapInfo/d:Schema", NameSpaceManager))
            {
                CT_Schema ctSchema = new CT_Schema();
                ctSchema.ID = schemaNode.AttributeValue("ID");
                if (schemaNode.Attribute("Namespace") != null)
                {
                    ctSchema.Namespace = schemaNode.AttributeValue("Namespace");
                }
                if (schemaNode.Attribute("SchemaRef") != null)
                {
                    ctSchema.Namespace = schemaNode.AttributeValue("SchemaRef");
                }
                ctSchema.InnerXml = schemaNode.InnerXml();
                doc.map.Schema.Add(ctSchema);
            }
            return(doc);
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Validates the given XML document.
        /// </summary>
        /// <param name="input">XML document as stream.</param>
        /// <param name="ser">Serialiser.</param>
        /// <exception cref="InvalidOperationException">Thrown if the document is invalid.</exception>
        public void Validate(System.IO.Stream input, Type type)
        {
            var settings = GetSettings();

            // Adding the event handler of this object
            settings.ValidationEventHandler += Settings_ValidationEventHandler;

            // Clearing validation messages
            m_validationMessages.Clear();

            // Declaring a prefix for the XLink namespace explicitly.
            // This is necessary to support scheduling parameters of type
            // Item_DataRecord from the library "Cocop.MessageSerialiser.Meas".
            var nametable    = new System.Xml.NameTable();
            var xmlNsManager = new System.Xml.XmlNamespaceManager(nametable);

            xmlNsManager.AddNamespace("xlink", "http://www.w3.org/1999/xlink");

            // Declaring a context object to pass the namespace manager to the parser
            var parserContext = new System.Xml.XmlParserContext(null, xmlNsManager, null, System.Xml.XmlSpace.None);

            using (var reader = System.Xml.XmlReader.Create(input, settings, parserContext))
            {
                // Deserialising the document
                var serializer = new System.Xml.Serialization.XmlSerializer(type);
                serializer.Deserialize(reader);
            }

            // Removing the event handler of this object (the event handler would
            // otherwise cause conflicts when multiple documents are validated)
            settings.ValidationEventHandler -= Settings_ValidationEventHandler;

            if (m_validationMessages.Count > 0)
            {
                var msg = string.Format("The XML document has {0} errors. First error: {1}", m_validationMessages.Count, m_validationMessages[0]);
                throw new InvalidOperationException(msg);
            }
        }
Ejemplo n.º 37
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.º 38
0
        static AppSettings()
        {
            m_document = new System.Xml.XmlDocument();
            // m_document.Load("filename");
            m_document.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<configuration>
    <appSettings>
        <add key=""count&quot;offiles"" value=""7&quot;8"" />
        <add key=""countoffiles"" value=""7&quot;8"" />
        <add key=""logfilelocation"" value=""abc.txt"" />
        <add key=""smtp_port"" value=""25""/>
        <add key=""smtp_user"" value=""""/>
        <add key=""smtp_passwort"" value=""""/>
        <add key=""smtp_authenticate"" value=""""/>
        <add key=""smtp_server"" value=""smtp.somedomain.com""/>
    </appSettings>
</configuration>
");

            m_nsmgr = new System.Xml.XmlNamespaceManager(m_document.NameTable);
            m_nsmgr.AddNamespace("dft", "");
            //m_nsmgr.AddNamespace("", "");
        }
Ejemplo n.º 39
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.º 40
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.º 41
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.º 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
		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.º 46
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.º 47
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;
            }
        }
 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.º 49
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();
                }
            }
        }
Ejemplo n.º 50
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.º 51
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;
        }
 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.º 53
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.º 54
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();
		}
Ejemplo n.º 55
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));
        }
Ejemplo n.º 56
0
        private Feed(System.Xml.XmlDocument i_FeedXmlDocument, int? i_SequenceIDBase, string i_Since, string i_Until)
        {
            m_XmlDocument = i_FeedXmlDocument;
            m_XmlNamespaceManager = new System.Xml.XmlNamespaceManager(m_XmlDocument.NameTable);

            if (m_XmlDocument.DocumentElement.LocalName == Microsoft.Samples.FeedSync.Constants.ATOM_FEED_ITEM_CONTAINER_ELEMENT_NAME)
                m_FeedType = Microsoft.Samples.FeedSync.Feed.FeedTypes.Atom;
            else
                m_FeedType = Microsoft.Samples.FeedSync.Feed.FeedTypes.RSS;

            this.InitializeXmlNamespaceManager(true);

            if (m_FeedType == Microsoft.Samples.FeedSync.Feed.FeedTypes.Atom)
            {
                m_FeedItemXPathQuery = System.String.Format
                    (
                    "{0}:{1}",
                    m_AtomNamespacePrefix,
                    Microsoft.Samples.FeedSync.Constants.ATOM_FEED_ITEM_ELEMENT_NAME
                    );

                if (m_XmlNamespaceManager.DefaultNamespace == Microsoft.Samples.FeedSync.Constants.ATOM_XML_NAMESPACE_URI)
                    m_FeedItemElementName = Microsoft.Samples.FeedSync.Constants.ATOM_FEED_ITEM_ELEMENT_NAME;
                else
                    m_FeedItemElementName = m_FeedItemXPathQuery;
            }
            else
            {
                m_FeedItemXPathQuery = Microsoft.Samples.FeedSync.Constants.RSS_FEED_ITEM_ELEMENT_NAME;
                m_FeedItemElementName = m_FeedItemXPathQuery;
            }

            //  Get reference to 'sx:sharing' element
            string XPathQuery = System.String.Format
                (
                "{0}:{1}",
                m_FeedSyncNamespacePrefix,
                Microsoft.Samples.FeedSync.Constants.SHARING_ELEMENT_NAME
                );

            System.Xml.XmlElement SharingXmlElement = (System.Xml.XmlElement)this.ItemContainerXmlElement.SelectSingleNode
                (
                XPathQuery,
                m_XmlNamespaceManager
                );

            XPathQuery = System.String.Format
                (
                "descendant::*[{0}:{1}]",
                m_FeedSyncNamespacePrefix,
                Microsoft.Samples.FeedSync.Constants.SYNC_ELEMENT_NAME
                );

            System.Xml.XmlNodeList SyncXmlNodeList = this.ItemContainerXmlElement.SelectNodes
                (
                XPathQuery,
                m_XmlNamespaceManager
                );

            if ((SharingXmlElement != null) || (SyncXmlNodeList.Count > 0))
                throw new System.Exception("Document is already a valid FeedSync document!");

            System.Xml.XmlNodeList FeedItemXmlNodeList = this.ItemContainerXmlElement.SelectNodes
                (
                m_FeedItemXPathQuery,
                m_XmlNamespaceManager
                );

            //  BIG HONKING NOTE:  Iterate nodes using index instead of enumerator
            for (int Index = 0; Index < FeedItemXmlNodeList.Count; ++Index)
            {
                System.Xml.XmlElement FeedItemXmlElement = (System.Xml.XmlElement)FeedItemXmlNodeList[Index];

                //  Remove item from document
                FeedItemXmlElement.ParentNode.RemoveChild(FeedItemXmlElement);

                string SyncNodeID = null;
                if (i_SequenceIDBase != null)
                {
                    ++i_SequenceIDBase;
                    SyncNodeID = i_SequenceIDBase.ToString();
                }

                //  Create new FeedItemNode and add it to feed
                Microsoft.Samples.FeedSync.FeedItemNode FeedItemNode = Microsoft.Samples.FeedSync.FeedItemNode.CreateNewFromXmlElement
                    (
                    this,
                    FeedItemXmlElement,
                    SyncNodeID
                    );

                this.AddFeedItem(FeedItemNode);
            }

            this.Initialize();
        }
Ejemplo n.º 57
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.º 58
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.º 59
0
        private Feed(System.Xml.XmlDocument i_FeedSyncXmlDocument)
        {
            m_XmlDocument = i_FeedSyncXmlDocument;
            m_XmlNamespaceManager = new System.Xml.XmlNamespaceManager(m_XmlDocument.NameTable);

            if (m_XmlDocument.DocumentElement.LocalName == Microsoft.Samples.FeedSync.Constants.ATOM_FEED_ITEM_CONTAINER_ELEMENT_NAME)
                m_FeedType = Microsoft.Samples.FeedSync.Feed.FeedTypes.Atom;
            else
                m_FeedType = Microsoft.Samples.FeedSync.Feed.FeedTypes.RSS;

            this.InitializeXmlNamespaceManager(false);

            if (m_FeedType == Microsoft.Samples.FeedSync.Feed.FeedTypes.Atom)
            {
                m_FeedItemXPathQuery = System.String.Format
                    (
                    "{0}:{1}",
                    m_AtomNamespacePrefix,
                    Microsoft.Samples.FeedSync.Constants.ATOM_FEED_ITEM_ELEMENT_NAME
                    );

                if (m_XmlNamespaceManager.DefaultNamespace == Microsoft.Samples.FeedSync.Constants.ATOM_XML_NAMESPACE_URI)
                    m_FeedItemElementName = Microsoft.Samples.FeedSync.Constants.ATOM_FEED_ITEM_ELEMENT_NAME;
                else
                    m_FeedItemElementName = m_FeedItemXPathQuery;
            }
            else
            {
                m_FeedItemXPathQuery = Microsoft.Samples.FeedSync.Constants.RSS_FEED_ITEM_ELEMENT_NAME;
                m_FeedItemElementName = m_FeedItemXPathQuery;
            }

            //  Get reference to 'sx:sharing' element
            string XPathQuery = System.String.Format
                (
                "{0}:{1}",
                m_FeedSyncNamespacePrefix,
                Microsoft.Samples.FeedSync.Constants.SHARING_ELEMENT_NAME
                );

            System.Xml.XmlElement SharingXmlElement = (System.Xml.XmlElement)this.ItemContainerXmlElement.SelectSingleNode
                (
                XPathQuery, 
                m_XmlNamespaceManager
                );

            if (SharingXmlElement != null)
                m_SharingNode = new Microsoft.Samples.FeedSync.SharingNode(this, SharingXmlElement);

            //  Iterate items
            System.Xml.XmlNodeList FeedItemXmlNodeList = this.ItemContainerXmlElement.SelectNodes
                (
                m_FeedItemXPathQuery,
                m_XmlNamespaceManager
                );

            foreach (System.Xml.XmlElement FeedItemXmlElement in FeedItemXmlNodeList)
            {
                Microsoft.Samples.FeedSync.FeedItemNode FeedItemNode = Microsoft.Samples.FeedSync.FeedItemNode.CreateFromXmlElement
                    (
                    this, 
                    FeedItemXmlElement
                    );

                m_FeedItemNodeSortedList[FeedItemNode.SyncNode.ID] = FeedItemNode;
            }

            this.Initialize();
        }
Ejemplo n.º 60
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;
            }
        }