public void Diagnosis_SDataCode_Should_Be_An_Enum_Test()
        {
            var diagnosis = new Diagnosis
                            {
                                SDataCode = DiagnosisCode.ApplicationDiagnosis,
                                ApplicationCode = "Application error"
                            };
            string xml;

            using (var textWriter = new StringWriter())
            using (var xmlWriter = new XmlTextWriter(textWriter))
            {
                diagnosis.WriteTo(xmlWriter, null);
                xml = textWriter.ToString();
            }

            XPathNavigator nav;

            using (var textReader = new StringReader(xml))
            using (var xmlReader = new XmlTextReader(textReader))
            {
                nav = new XPathDocument(xmlReader).CreateNavigator();
            }

            var node = nav.SelectSingleNode("diagnosis/sdataCode");
            Assert.IsNotNull(node);
            Assert.AreEqual("ApplicationDiagnosis", node.Value);

            node = nav.SelectSingleNode("diagnosis/applicationCode");
            Assert.IsNotNull(node);
            Assert.AreEqual("Application error", node.Value);
        }
Beispiel #2
0
        /// <summary>
        /// Generates an object from its XML representation.
        /// </summary>
        /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
        public void ReadXml(XmlReader reader)
        {
            var navigator = new XPathDocument(reader).CreateNavigator();

            XPathNavigator propertyNameNode = navigator.SelectSingleNode("//Fault/PropertyName");

            if (propertyNameNode != null)
            {
                PropertyName = propertyNameNode.Value;
            }

            XPathNavigator messageNode = navigator.SelectSingleNode("//Fault/Message");

            if (messageNode != null)
            {
                Message = messageNode.Value;
            }

            XPathNavigator detailNode = navigator.SelectSingleNode("//Fault/Detail");

            if (detailNode != null)
            {
                Detail = detailNode.Value;
            }
        }
        public void Diagnosis_SDataCode_Should_Be_An_Enum_Test()
        {
            var diagnosis = new Diagnosis
                                {
                                    SDataCode = DiagnosisCode.ApplicationDiagnosis,
                                    ApplicationCode = "Application error"
                                };
            string xml;

            using (var stream = new MemoryStream())
            {
                var settings = new XmlWriterSettings
                                   {
                                       Indent = true,
                                       Encoding = new UTF8Encoding(false)
                                   };
                var xmlWriter = XmlWriter.Create(stream, settings);
                new XmlSerializer(typeof (Diagnosis)).Serialize(xmlWriter, diagnosis);
                xml = Encoding.UTF8.GetString(stream.ToArray());
            }

            #if NET_2_0 || NET_3_5
            XPathNavigator nav;
            using (var textReader = new StringReader(xml))
            using (var xmlReader = new XmlTextReader(textReader))
            {
                nav = new XPathDocument(xmlReader).CreateNavigator();
            }
            #else
            var nav = XDocument.Parse(xml).CreateNavigator();
            #endif

            var mgr = new XmlNamespaceManager(nav.NameTable);
            mgr.AddNamespace("sdata", Common.SData.Namespace);

            var node = nav.SelectSingleNode("sdata:diagnosis/sdata:sdataCode", mgr);
            Assert.IsNotNull(node);
            Assert.AreEqual("ApplicationDiagnosis", node.Value);

            node = nav.SelectSingleNode("sdata:diagnosis/sdata:applicationCode", mgr);
            Assert.IsNotNull(node);
            Assert.AreEqual("Application error", node.Value);
        }
        private static Tuple<Version, string> GetVersion()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://code.google.com/feeds/p/spotify-auto-pauser/downloads/basic");
            WebResponse resp = req.GetResponse();

            XPathNavigator xml = new XPathDocument(resp.GetResponseStream()).CreateNavigator();
            XmlNamespaceManager mgr = new XmlNamespaceManager(xml.NameTable);
            mgr.AddNamespace("x", "http://www.w3.org/2005/Atom");
            string url = xml.SelectSingleNode("/x:feed/x:entry/x:link", mgr).GetAttribute("href", "");

            Regex reg = new Regex("v([0-9]{1,2}).([0-9]{1,2}).([0-9]{1,2})");
            if (reg.IsMatch(url))
            {
                Match m = reg.Match(url);
                Version v = new Version(m.Groups[0].ToString().Substring(1) + ".0");
                return new Tuple<Version, String>(v, url);
            }

            return null;
        }
Beispiel #5
0
        public Definitions(string definitionFile)
        {
            using (XmlReader reader = XmlReader.Create(definitionFile)) {
                XPathNavigator navigator = new XPathDocument(reader).CreateNavigator();

                bool caseSensitive = XmlConvert.ToBoolean(navigator.SelectSingleNode("/NxDSL-Defs").GetAttribute("caseSensitive", ""));

                XPathNodeIterator atomPatterns = navigator.SelectDescendants("AtomPattern", "", false);

                while (atomPatterns.MoveNext()) {
                    XPathNavigator atomPattern = atomPatterns.Current;

                    RegexOptions options = RegexOptions.Compiled;

                    if (!caseSensitive) {
                        options |= RegexOptions.IgnoreCase;
                    }

                    Regex regex = new Regex("^\\s*" + atomPattern.GetAttribute("regex", "") + "$", options);

                    definitions.Add(regex, atomPattern.InnerXml);
                }
            }
        }
Beispiel #6
0
		public static void Read(string filepath, ProjectManager projects, ReferenceTable references, IdTable ids) {
			var xml = new XPathDocument(filepath).CreateNavigator();
			var project = new Project();
			var pnode = xml.SelectSingleNode("/Project");
			ids[project] = new Guid(pnode.GetAttribute("id", ""));
			AssignProperties(pnode, project, references);
			references.Update(ids);// force Project.Property assignment
			var aci = pnode.Select("Assignments/FlatAssignmentCollection");
			while ( aci.MoveNext() ) {
				var acnode = aci.Current;
				var flatid = acnode.SelectSingleNode("Flat").Value;
				var collection = project.Assignments.First(ac => ids[ac.Flat].ToString() == flatid);
				ids[collection] = new Guid(acnode.GetAttribute("id", ""));
				AssignProperties(acnode, collection, references);
				var ai = acnode.Select("FlatAssignment");
				while ( ai.MoveNext() ) {
					var anode = ai.Current;
					var a = new FlatAssignment(project);
					ids[a] = new Guid(anode.GetAttribute("id", ""));
					AssignProperties(anode, a, references);
					collection.Add(a);
				}
			}
			references.Update(ids);// force Assignments for CostOptions generation
			var ci = pnode.Select("Costs/Cost");
			while ( ci.MoveNext() ) {
				var cnode = ci.Current;
				var c = project.CreateCost();
				ids[c] = new Guid(cnode.GetAttribute("id", ""));
				AssignProperties(cnode, c, references);
				var oi = cnode.Select("Options/CostOptions");
				while ( oi.MoveNext() ) {
					var onode = oi.Current;
					var lesseeid = onode.SelectSingleNode("Lessee").Value;
					var option = c.Options.First(o => ids[o.Lessee].ToString() == lesseeid);
					ids[option] = new Guid(onode.GetAttribute("id", ""));
					AssignProperties(onode, option, references);
				}
			}
			projects.Add(project);
		}
 public void Write_Tracking_Test()
 {
     var tracking = new Tracking
                        {
                            Phase = "Archiving FY 2007",
                            PhaseDetail = "Compressing file archive.dat",
                            Progress = 12M,
                            ElapsedSeconds = 95M,
                            RemainingSeconds = 568M,
                            PollingMillis = 500
                        };
     XPathNavigator nav;
     using (var stream = new MemoryStream())
     {
         new XmlContentHandler().WriteTo(tracking, stream);
         stream.Seek(0, SeekOrigin.Begin);
     #if NET_2_0 || NET_3_5
         nav = new XPathDocument(stream).CreateNavigator();
     #else
         nav = XDocument.Load(stream).CreateNavigator();
     #endif
     }
     var mgr = new XmlNamespaceManager(nav.NameTable);
     mgr.AddNamespace("sdata", "http://schemas.sage.com/sdata/2008/1");
     var node = nav.SelectSingleNode("sdata:tracking", mgr);
     Assert.That(node, Is.Not.Null);
     Assert.That(node.SelectSingleNode("sdata:phase", mgr).Value, Is.EqualTo("Archiving FY 2007"));
     Assert.That(node.SelectSingleNode("sdata:phaseDetail", mgr).Value, Is.EqualTo("Compressing file archive.dat"));
     Assert.That(node.SelectSingleNode("sdata:progress", mgr).Value, Is.EqualTo("12"));
     Assert.That(node.SelectSingleNode("sdata:elapsedSeconds", mgr).Value, Is.EqualTo("95"));
     Assert.That(node.SelectSingleNode("sdata:remainingSeconds", mgr).Value, Is.EqualTo("568"));
     Assert.That(node.SelectSingleNode("sdata:pollingMillis", mgr).Value, Is.EqualTo("500"));
 }
 public void Write_Unknown_Test()
 {
     const string xml = @"<dummy/>";
     XPathNavigator nav;
     using (var stream = new MemoryStream())
     {
         new XmlContentHandler().WriteTo(xml, stream);
         stream.Seek(0, SeekOrigin.Begin);
     #if NET_2_0 || NET_3_5
         nav = new XPathDocument(stream).CreateNavigator();
     #else
         nav = XDocument.Load(stream).CreateNavigator();
     #endif
     }
     var node = nav.SelectSingleNode("dummy");
     Assert.That(node, Is.Not.Null);
     Assert.That(node.IsEmptyElement, Is.True);
 }
        // Methods
        public static int Main(string[] args)
        {
            XPathDocument document;

            ConsoleApplication.WriteBanner();

            OptionCollection options = new OptionCollection {
                new SwitchOption("?", "Show this help page."),
                new StringOption("config", "Specify a configuration file.", "versionCatalog"),
                new StringOption("out", "Specify an output file containing version information.", "outputFile"),
                new BooleanOption("rip", "Specify whether to rip old APIs which are not supported by the " +
                    "latest versions.")
            };

            ParseArgumentsResult result = options.ParseArguments(args);

            if(result.Options["?"].IsPresent)
            {
                Console.WriteLine("VersionBuilder [options]");
                options.WriteOptionSummary(Console.Out);
                return 0;
            }

            if(!result.Success)
            {
                result.WriteParseErrors(Console.Out);
                return 1;
            }

            if(result.UnusedArguments.Count != 0)
            {
                Console.WriteLine("No non-option arguments are supported.");
                return 1;
            }

            if(!result.Options["config"].IsPresent)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "You must specify a version catalog file.");
                return 1;
            }

            bool rip = true;

            if(result.Options["rip"].IsPresent && !((bool)result.Options["rip"].Value))
                rip = false;

            string uri = (string)result.Options["config"].Value;

            try
            {
                document = new XPathDocument(uri);
            }
            catch(IOException ioEx)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture,
                    "An error occurred while accessing the version catalog file '{0}'. The error message " +
                    "is: {1}", uri, ioEx.Message));
                return 1;
            }
            catch(XmlException xmlEx)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture,
                    "The version catalog file '{0}' is not well-formed. The error message is: {1}", uri,
                    xmlEx.Message));
                return 1;
            }

            XPathNavigator navigator = document.CreateNavigator().SelectSingleNode("versions");
            XPathExpression expr = XPathExpression.Compile("string(ancestor::versions/@name)");
            List<VersionInfo> allVersions = new List<VersionInfo>();
            List<string> latestVersions = new List<string>();

            foreach(XPathNavigator navigator2 in document.CreateNavigator().Select("versions//version[@file]"))
            {
                string group = (string)navigator2.Evaluate(expr);
                string attribute = navigator2.GetAttribute("name", String.Empty);

                if(string.IsNullOrEmpty(attribute))
                    ConsoleApplication.WriteMessage(LogLevel.Error, "Every version element must have a name attribute.");

                string name = navigator2.GetAttribute("file", String.Empty);

                if(String.IsNullOrEmpty(attribute))
                    ConsoleApplication.WriteMessage(LogLevel.Error, "Every version element must have a file attribute.");

                string ripOldString = navigator2.GetAttribute("ripOldApis", String.Empty);
                bool ripOld = ripOldString == "1" || String.Equals("true", ripOldString, StringComparison.OrdinalIgnoreCase);

                name = Environment.ExpandEnvironmentVariables(name);
                VersionInfo item = new VersionInfo(attribute, group, name, ripOld);
                allVersions.Add(item);
            }

            string str5 = String.Empty;

            foreach(VersionInfo info2 in allVersions)
                if(!info2.RipOldApis && (!rip || info2.Group != str5))
                {
                    latestVersions.Add(info2.Name);
                    str5 = info2.Group;
                }

            bool ripAny = rip || allVersions.Any(i => i.RipOldApis);

            if(Cancel)
            {
                ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled");
                return 1;
            }

            XmlReaderSettings settings = new XmlReaderSettings
            {
                IgnoreWhitespace = true
            };

            XmlWriterSettings settings2 = new XmlWriterSettings
            {
                Indent = true
            };

            Dictionary<string, List<KeyValuePair<string, string>>> versionIndex = new Dictionary<string, List<KeyValuePair<string, string>>>();
            Dictionary<string, Dictionary<string, ElementInfo>> dictionary2 = new Dictionary<string, Dictionary<string, ElementInfo>>();
            Dictionary<string, Dictionary<String, XPathNavigator>> extensionMethods = new Dictionary<string, Dictionary<String, XPathNavigator>>();
            XPathExpression expression2 = XPathExpression.Compile("string(/api/@id)");
            XPathExpression expression4 = XPathExpression.Compile("/api/elements/element");
            XPathExpression expression = XPathExpression.Compile("/api/attributes/attribute[type[@api='T:System.ObsoleteAttribute']]");
            XPathExpression extensionAttributeExpression = XPathExpression.Compile("/api/attributes/attribute[type[@api='T:System.Runtime.CompilerServices.ExtensionAttribute']]");
            XPathExpression extensionFirstParameterExpression = XPathExpression.Compile("/api/parameters/parameter[1]/*");
            XPathExpression specialization = XPathExpression.Compile("./specialization");
            XPathExpression templates = XPathExpression.Compile("./template[boolean(@index) and starts-with(@api, 'M:')]");
            XPathExpression skipFirstParam = XPathExpression.Compile("./parameter[position()>1]" );
            XPathExpression expression6 = XPathExpression.Compile("boolean(argument[type[@api='T:System.Boolean'] and value[.='True']])");
            XPathExpression apiChild = XPathExpression.Compile("./api");

            foreach(VersionInfo info3 in allVersions)
            {
                if(Cancel)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled");
                    return 1;
                }

                ConsoleApplication.WriteMessage(LogLevel.Info, String.Format(CultureInfo.CurrentCulture,
                    "Indexing version '{0}' using file '{1}'.", info3.Name, info3.File));
                try
                {
                    XmlReader reader = XmlReader.Create(info3.File, settings);
                    try
                    {
                        reader.MoveToContent();
                        while(reader.Read())
                        {
                            if((reader.NodeType == XmlNodeType.Element) && (reader.LocalName == "api"))
                            {
                                string key = String.Empty;
                                List<KeyValuePair<string, string>> list3 = null;
                                string str7 = String.Empty;
                                Dictionary<string, ElementInfo> dictionary3 = null;
                                XmlReader reader2 = reader.ReadSubtree();
                                XPathNavigator navigator3 = new XPathDocument(reader2).CreateNavigator();

                                key = (string)navigator3.Evaluate(expression2);

                                if(!versionIndex.TryGetValue(key, out list3))
                                {
                                    list3 = new List<KeyValuePair<string, string>>();
                                    versionIndex.Add(key, list3);
                                }

                                if(!dictionary2.TryGetValue(key, out dictionary3))
                                {
                                    dictionary3 = new Dictionary<string, ElementInfo>();
                                    dictionary2.Add(key, dictionary3);
                                }

                                foreach(XPathNavigator navigator4 in navigator3.Select(expression4))
                                {
                                    ElementInfo info4;
                                    string str8 = navigator4.GetAttribute("api", String.Empty);
                                    if(!dictionary3.TryGetValue(str8, out info4))
                                    {
                                        XPathNavigator elementNode = null;
                                        if((navigator4.SelectSingleNode("*") != null) || (navigator4.SelectChildren(XPathNodeType.Attribute).Count > 1))
                                        {
                                            elementNode = navigator4;
                                        }
                                        info4 = new ElementInfo(info3.Group, info3.Name, elementNode);
                                        dictionary3.Add(str8, info4);
                                        continue;
                                    }
                                    if(!info4.Versions.ContainsKey(info3.Group))
                                    {
                                        info4.Versions.Add(info3.Group, info3.Name);
                                    }
                                }
                                XPathNavigator navigator6 = navigator3.SelectSingleNode(expression);
                                if(navigator6 != null)
                                {
                                    str7 = ((bool)navigator6.Evaluate(expression6)) ? "error" : "warning";
                                }

                                if(key.StartsWith("M:", StringComparison.Ordinal))
                                {
                                    // Only check for extension methods when this is actually a method in question
                                    var navigator7 = navigator3.SelectSingleNode(extensionAttributeExpression);
                                    if(navigator7 != null)
                                    {
                                        // Check first parameter
                                        var navigator8 = navigator3.SelectSingleNode(extensionFirstParameterExpression);
                                        if(navigator8 != null)
                                        {
                                            // Get type node
                                            var typeID = navigator8.GetAttribute("api", String.Empty);
                                            if(navigator8.LocalName == "type")
                                            {
                                                var specNode = navigator8.SelectSingleNode(specialization);
                                                if(specNode == null || specNode.SelectChildren(XPathNodeType.Element).Count == specNode.Select(templates).Count)
                                                {
                                                    // Either non-generic type or all type parameters are from within this method
                                                    Dictionary<String, XPathNavigator> extMethods;
                                                    if(!extensionMethods.TryGetValue(typeID, out extMethods))
                                                    {
                                                        extMethods = new Dictionary<String, XPathNavigator>();
                                                        extensionMethods.Add(typeID, extMethods);
                                                    }
                                                    if(!extMethods.ContainsKey(key))
                                                    {
                                                        extMethods.Add(key, navigator3.SelectSingleNode(apiChild));
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                // TODO extension methods for generic parameters...
                                            }
                                        }
                                    }
                                }

                                list3.Add(new KeyValuePair<string, string>(info3.Name, str7));
                                str7 = String.Empty;
                                reader2.Close();
                            }
                        }
                    }
                    finally
                    {
                        reader.Close();
                    }
                    continue;
                }
                catch(IOException ioEx)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture,
                        "An error occurred while accessing the input file '{0}'. The error message is: {1}",
                        info3.File, ioEx.Message));
                    return 1;
                }
                catch(XmlException xmlEx)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture,
                        "The input file '{0}' is not well-formed. The error message is: {1}", info3.File,
                        xmlEx.Message));
                    return 1;
                }
            }

            if(ripAny)
                RemoveOldApis(versionIndex, latestVersions);

            ConsoleApplication.WriteMessage(LogLevel.Info, String.Format(CultureInfo.CurrentCulture,
                "Indexed {0} entities in {1} versions.", versionIndex.Count, allVersions.Count));

            try
            {
                XmlWriter writer;

                if(result.Options["out"].IsPresent)
                    writer = XmlWriter.Create((string)result.Options["out"].Value, settings2);
                else
                    writer = XmlWriter.Create(Console.Out, settings2);

                try
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("reflection");
                    writer.WriteStartElement("assemblies");
                    Dictionary<string, object> dictionary4 = new Dictionary<string, object>();

                    foreach(VersionInfo info5 in allVersions)
                    {
                        if(Cancel)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled");
                            return 1;
                        }

                        using(XmlReader reader3 = XmlReader.Create(info5.File, settings))
                        {
                            reader3.MoveToContent();

                            while(reader3.Read())
                            {
                                if((reader3.NodeType == XmlNodeType.Element) && (reader3.LocalName == "assembly"))
                                {
                                    string str9 = reader3.GetAttribute("name");
                                    if(!dictionary4.ContainsKey(str9))
                                    {
                                        XmlReader reader4 = reader3.ReadSubtree();
                                        writer.WriteNode(reader4, false);
                                        reader4.Close();
                                        dictionary4.Add(str9, null);
                                    }
                                }
                            }
                        }
                    }

                    writer.WriteEndElement();
                    writer.WriteStartElement("apis");
                    var readElements = new HashSet<String>();

                    foreach(VersionInfo info6 in allVersions)
                    {
                        if(Cancel)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled");
                            return 1;
                        }

                        XmlReader reader5 = XmlReader.Create(info6.File, settings);
                        reader5.MoveToContent();

                        while(reader5.Read())
                        {
                            if((reader5.NodeType == XmlNodeType.Element) && (reader5.LocalName == "api"))
                            {
                                string str10 = reader5.GetAttribute("id");
                                if(versionIndex.ContainsKey(str10))
                                {
                                    List<KeyValuePair<string, string>> versions = versionIndex[str10];
                                    KeyValuePair<string, string> pair = versions[0];
                                    if(info6.Name == pair.Key)
                                    {
                                        writer.WriteStartElement("api");
                                        writer.WriteAttributeString("id", str10);
                                        XmlReader reader6 = reader5.ReadSubtree();
                                        reader6.MoveToContent();
                                        reader6.ReadStartElement();
                                        Dictionary<String, XPathNavigator> eElems;
                                        var hasExtensionMethods = extensionMethods.TryGetValue(str10, out eElems);
                                        if(hasExtensionMethods)
                                        {
                                            readElements.Clear();
                                            readElements.UnionWith(extensionMethods[str10].Keys);
                                        }
                                        while(!reader6.EOF)
                                        {
                                            if((reader6.NodeType == XmlNodeType.Element) && (reader6.LocalName == "elements"))
                                            {
                                                Dictionary<string, ElementInfo> dictionary5 = dictionary2[str10];
                                                Dictionary<string, object> dictionary6 = new Dictionary<string, object>();
                                                writer.WriteStartElement("elements");
                                                XmlReader reader7 = reader6.ReadSubtree();
                                                foreach(XPathNavigator navigator8 in new XPathDocument(reader7).CreateNavigator().Select("elements/element"))
                                                {
                                                    string str11 = navigator8.GetAttribute("api", String.Empty);
                                                    dictionary6[str11] = null;
                                                    writer.WriteStartElement("element");
                                                    writer.WriteAttributeString("api", str11);
                                                    if(hasExtensionMethods)
                                                    {
                                                        readElements.Remove(str11);
                                                    }
                                                    foreach(string str12 in dictionary5[str11].Versions.Keys)
                                                    {
                                                        writer.WriteAttributeString(str12, dictionary5[str11].Versions[str12]);
                                                    }
                                                    foreach(XPathNavigator navigator9 in navigator8.Select("@*"))
                                                    {
                                                        if(navigator9.LocalName != "api")
                                                        {
                                                            writer.WriteAttributeString(navigator9.LocalName, navigator9.Value);
                                                        }
                                                    }
                                                    foreach(XPathNavigator navigator10 in navigator8.Select("*"))
                                                    {
                                                        writer.WriteNode(navigator10, false);
                                                    }
                                                    writer.WriteEndElement();
                                                }
                                                reader7.Close();
                                                if(dictionary6.Count != dictionary5.Count)
                                                {
                                                    foreach(string str13 in dictionary5.Keys)
                                                    {
                                                        if(dictionary6.ContainsKey(str13) || (ripAny && !IsLatestElement(dictionary5[str13].Versions.Values, latestVersions)))
                                                        {
                                                            continue;
                                                        }
                                                        writer.WriteStartElement("element");
                                                        writer.WriteAttributeString("api", str13);
                                                        if(hasExtensionMethods)
                                                        {
                                                            readElements.Remove(str13);
                                                        }
                                                        foreach(string str14 in dictionary5[str13].Versions.Keys)
                                                        {
                                                            writer.WriteAttributeString(str14, dictionary5[str13].Versions[str14]);
                                                        }
                                                        if(dictionary5[str13].ElementNode != null)
                                                        {
                                                            foreach(XPathNavigator navigator11 in dictionary5[str13].ElementNode.Select("@*"))
                                                            {
                                                                if(navigator11.LocalName != "api")
                                                                {
                                                                    writer.WriteAttributeString(navigator11.LocalName, navigator11.Value);
                                                                }
                                                            }
                                                            foreach(XPathNavigator navigator12 in dictionary5[str13].ElementNode.Select("*"))
                                                            {
                                                                writer.WriteNode(navigator12, false);
                                                            }
                                                        }
                                                        writer.WriteEndElement();
                                                    }
                                                }

                                                if(hasExtensionMethods)
                                                {
                                                    foreach(var eMethodID in readElements)
                                                    {
                                                        writer.WriteStartElement("element");
                                                        writer.WriteAttributeString("api", eMethodID);
                                                        writer.WriteAttributeString("source", "extension");
                                                        foreach(XPathNavigator extMember in eElems[eMethodID].SelectChildren(XPathNodeType.Element))
                                                        {
                                                            switch(extMember.LocalName)
                                                            {
                                                                case "apidata":
                                                                    writer.WriteStartElement("apidata");
                                                                    foreach(XPathNavigator apidataAttr in extMember.Select("@*"))
                                                                    {
                                                                        writer.WriteAttributeString(apidataAttr.LocalName, apidataAttr.Value);
                                                                    }
                                                                    writer.WriteAttributeString("subsubgroup", "extension");
                                                                    foreach(XPathNavigator child in extMember.SelectChildren(XPathNodeType.All & ~XPathNodeType.Attribute))
                                                                    {
                                                                        writer.WriteNode(child, false);
                                                                    }
                                                                    writer.WriteEndElement();
                                                                    break;
                                                                case "parameters":
                                                                    var noParamsWritten = true;
                                                                    foreach(XPathNavigator eParam in extMember.Select(skipFirstParam))
                                                                    {
                                                                        if(noParamsWritten)
                                                                        {
                                                                            writer.WriteStartElement("parameters");
                                                                            noParamsWritten = false;
                                                                        }
                                                                        writer.WriteNode(eParam, false);
                                                                    }
                                                                    if(!noParamsWritten)
                                                                    {
                                                                        writer.WriteEndElement();
                                                                    }
                                                                    break;
                                                                case "memberdata":
                                                                    writer.WriteStartElement("memberdata");
                                                                    foreach(XPathNavigator mDataAttr in extMember.Select("@*"))
                                                                    {
                                                                        if(mDataAttr.LocalName != "static")
                                                                        {
                                                                            writer.WriteAttributeString(mDataAttr.LocalName, mDataAttr.Value);
                                                                        }
                                                                    }
                                                                    foreach(XPathNavigator child in extMember.SelectChildren(XPathNodeType.All & ~XPathNodeType.Attribute))
                                                                    {
                                                                        writer.WriteNode(child, false);
                                                                    }
                                                                    writer.WriteEndElement();
                                                                    break;
                                                                case "attributes":
                                                                    break;
                                                                default:
                                                                    writer.WriteNode(extMember, false);
                                                                    break;
                                                            }
                                                        }
                                                        writer.WriteEndElement();
                                                    }
                                                }

                                                writer.WriteEndElement();
                                                reader6.Read();
                                            }
                                            else if(reader6.NodeType == XmlNodeType.Element)
                                            {
                                                writer.WriteNode(reader6, false);
                                            }
                                            else
                                            {
                                                reader6.Read();
                                            }
                                        }
                                        reader6.Close();
                                        writer.WriteStartElement("versions");
                                        foreach(XPathNavigator navigator13 in navigator.SelectChildren(XPathNodeType.Element))
                                        {
                                            WriteVersionTree(versions, navigator13, writer);
                                        }
                                        writer.WriteEndElement();
                                        writer.WriteEndElement();
                                    }
                                }
                            }
                        }

                        reader5.Close();
                    }

                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                }
                finally
                {
                    writer.Close();
                }
            }
            catch(IOException ioEx)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while generating the " +
                    "output file. The error message is: {0}", ioEx.Message);
                return 1;
            }

            return 0;
        }
        public void Write_Properties_Without_Types_Specified_Test()
        {
            var schema = new SDataSchema("http://schemas.sage.com/crmErp/2008")
                             {
                                 Types =
                                     {
                                         new SDataSchemaComplexType("tradingAccount")
                                             {
                                                 Properties =
                                                     {
                                                         new SDataSchemaValueProperty("active")
                                                     }
                                             }
                                     }
                             };

            XPathNavigator nav;
            using (var stream = new MemoryStream())
            {
                schema.Write(stream);
                stream.Seek(0, SeekOrigin.Begin);
            #if NET_2_0 || NET_3_5
                nav = new XPathDocument(stream).CreateNavigator();
            #else
                nav = XDocument.Load(stream).CreateNavigator();
            #endif
            }

            var mgr = new XmlNamespaceManager(nav.NameTable);
            mgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

            var resource = nav.SelectSingleNode("xs:schema/xs:complexType[@name='tradingAccount--type']", mgr);
            Assert.That(resource, Is.Not.Null);
            Assert.That(resource.Select("xs:all/xs:element", mgr).Count, Is.EqualTo(1));
            var property = resource.SelectSingleNode("xs:all/xs:element", mgr);
            Assert.That(property, Is.Not.Null);
            Assert.That(property.SelectSingleNode("@name").Value, Is.EqualTo("active"));
            Assert.That(property.SelectSingleNode("@type"), Is.Null);
        }
        public void Write_Enum_Schema_Types_Support_List_Types_Test()
        {
            var schema = new SDataSchema
                             {
                                 Types =
                                     {
                                         new SDataSchemaEnumType("test")
                                             {
                                                 BaseType = XmlTypeCode.String,
                                                 ListName = "test--list",
                                                 ListItemName = "test"
                                             }
                                     }
                             };

            XPathNavigator nav;
            using (var stream = new MemoryStream())
            {
                schema.Write(stream);
                stream.Seek(0, SeekOrigin.Begin);
            #if NET_2_0 || NET_3_5
                nav = new XPathDocument(stream).CreateNavigator();
            #else
                nav = XDocument.Load(stream).CreateNavigator();
            #endif
            }

            var mgr = new XmlNamespaceManager(nav.NameTable);
            mgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

            var type = nav.SelectSingleNode("xs:schema/xs:simpleType[@name='test--enum']", mgr);
            Assume.That(type, Is.Not.Null);
            var list = nav.SelectSingleNode("xs:schema/xs:complexType[@name='test--list']", mgr);
            Assert.That(list, Is.Not.Null);
            Assert.That(list.SelectSingleNode("xs:sequence/xs:element[@name='test']", mgr), Is.Not.Null);
        }
        public void Write_Element_Then_Complex_Type_Then_List_Type_Test()
        {
            var schema = new SDataSchema("http://schemas.sage.com/crmErp/2008")
                             {
                                 Types =
                                     {
                                         new SDataSchemaResourceType("tradingAccount")
                                     }
                             };

            XPathNavigator nav;
            using (var stream = new MemoryStream())
            {
                schema.Write(stream);
                stream.Seek(0, SeekOrigin.Begin);
            #if NET_2_0 || NET_3_5
                nav = new XPathDocument(stream).CreateNavigator();
            #else
                nav = XDocument.Load(stream).CreateNavigator();
            #endif
            }

            var mgr = new XmlNamespaceManager(nav.NameTable);
            mgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

            var resource = nav.SelectSingleNode("xs:schema/xs:element[@name='tradingAccount']", mgr);
            Assert.That(resource, Is.Not.Null);
            Assert.That(nav.SelectSingleNode("xs:schema/xs:complexType[@name='tradingAccount--type']", mgr), Is.Not.Null);
            Assert.That(nav.SelectSingleNode("xs:schema/xs:complexType[@name='tradingAccount--list']", mgr), Is.Not.Null);
        }
Beispiel #13
0
        protected override Dictionary<string, Tuple<Cipher, byte[]>> GetSessionKeys(ZipFile zipFile, string originalFilePath)
        {
            XPathNavigator navigator;
            using (var s = new MemoryStream())
            {
                zipFile["META-INF/rights.xml"].Extract(s);
                s.Seek(0, SeekOrigin.Begin);
                navigator = new XPathDocument(s).CreateNavigator();
            }
            var nsm = new XmlNamespaceManager(navigator.NameTable);
            nsm.AddNamespace("a", "http://ns.adobe.com/adept");
            nsm.AddNamespace("e", "http://www.w3.org/2001/04/xmlenc#");
            XPathNavigator node = navigator.SelectSingleNode("//a:encryptedKey[1]", nsm);
            if (node == null)
                throw new InvalidOperationException("Can't find session key.");

            string base64Key = node.Value;
            byte[] contentKey = Convert.FromBase64String(base64Key);

            var possibleKeys = new List<byte[]>();

            foreach (var masterKey in MasterKeys)
            {
                var rsa = GetRsaEngine(masterKey);
                var bookkey = rsa.ProcessBlock(contentKey, 0, contentKey.Length);
                //Padded as per RSAES-PKCS1-v1_5
                if (bookkey[bookkey.Length - 17] == 0x00)
                    possibleKeys.Add(bookkey.Copy(bookkey.Length - 16));
            }
            if (possibleKeys.Count == 0)
                throw new InvalidOperationException("Problem decrypting session key");

            using (var s = new MemoryStream())
            {
                zipFile["META-INF/encryption.xml"].Extract(s);
                s.Seek(0, SeekOrigin.Begin);
                navigator = new XPathDocument(s).CreateNavigator();
            }
            XPathNodeIterator contentLinks = navigator.Select("//e:EncryptedData", nsm);
            var result = new Dictionary<string, Tuple<Cipher, byte[]>>(contentLinks.Count);
            foreach (XPathNavigator link in contentLinks)
            {
                string em = link.SelectSingleNode("./e:EncryptionMethod/@Algorithm", nsm).Value;
                string path = link.SelectSingleNode("./e:CipherData/e:CipherReference/@URI", nsm).Value;
                var cipher = GetCipher(em);
                if (cipher == Cipher.Unknown)
                    throw new InvalidOperationException("This ebook uses unsupported encryption method: " + em);

                result[path] = Tuple.Create(cipher, possibleKeys[0]);
            }
            if (IsValidDecryptionKey(zipFile, result))
                return result;

            var keys = result.Keys.ToList();
            for (var i = 1; i < possibleKeys.Count; i++)
            {
                foreach (var key in keys)
                    result[key] = Tuple.Create(result[key].Item1, possibleKeys[i]);
                if (IsValidDecryptionKey(zipFile, result))
                    return result;
            }
            throw new InvalidOperationException("Couldn't find a valid book decryption key.");
        }
Beispiel #14
0
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            if (strands.Services.Settings.CheckLegacyRoutes == true)
            {
                var request = httpContext.Request;
                var response = httpContext.Response;
                var legacyUrl = request.Url.ToString();
                string urlPrefix = "http://" + HttpContext.Current.Request.ServerVariables["HTTP_HOST"] + HttpRuntime.AppDomainAppVirtualPath;
                string newUrl = "";
                string testUrl = "";
                string testUrlPostfix = "";
                XPathNavigator config = null;
                XPathNavigator node = null;

                if (request.QueryString.Get(strands.Services.AjaxCrawlable.Fragment) != null) return null;
                if (legacyUrl.ToLower().Contains("default.aspx") || legacyUrl.Contains("?"))
                {
                    //const string status = "301 Moved Permanently";
                    string t = string.IsNullOrEmpty(request.QueryString["tabid"]) ? request.QueryString["amp;tabid"] : request.QueryString["tabid"];
                    string l = string.IsNullOrEmpty(request.QueryString["L"]) ? request.QueryString["amp;L"] : request.QueryString["L"];
                    string s = string.IsNullOrEmpty(request.QueryString["S"]) ? request.QueryString["amp;S"] : request.QueryString["S"];
                    string strand = "";
                    string section = "";

                    l = (!string.IsNullOrEmpty(l) && l.Contains("/")) ? l.Substring(0, l.IndexOf("/")) : l;
                    if (!string.IsNullOrEmpty(l))
                    {
                        strand = string.IsNullOrEmpty(t) ? l : "Themes";
                        section = string.IsNullOrEmpty(t) ? (string.IsNullOrEmpty(s) ? "/1" : "/" + s) : "/" + t;
                        newUrl = System.Text.RegularExpressions.Regex.Replace((strand + section), @"[^\u0000-\u007F]", string.Empty);
                    }
                    else
                        newUrl = urlPrefix;
                }
                testUrl = (string.IsNullOrEmpty(newUrl)) ? legacyUrl.Replace(urlPrefix + "/", "") : newUrl.Replace(urlPrefix + "/", "");
                try
                {
                    config = new XPathDocument(HttpContext.Current.Server.MapPath(HttpRuntime.AppDomainAppVirtualPath + "/App_Data/xml/StrandsConfig.xml")).CreateNavigator();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex.InnerException);
                }
                while (!string.IsNullOrEmpty(testUrl))
                {
                    node = config.SelectSingleNode("/configuration/legacy-routes/route[@old='" + testUrl + "']");
                    if (node != null)
                    {
                        node.MoveToAttribute("new", "");
                        newUrl = urlPrefix + "/" + node.InnerXml + testUrlPostfix;
                        break;
                    }
                    if (testUrl.Contains("/"))
                    {
                        testUrlPostfix = testUrl.Substring(testUrl.LastIndexOf("/"));
                        testUrl = testUrl.Substring(0, testUrl.LastIndexOf("/"));
                    }
                    else
                        testUrl = "";
                }
                if (newUrl != "")
                    response.Redirect(newUrl, true);
            }
            return null;
        }
Beispiel #15
0
        public void Parse()
        {
            Episodes = new List<Episode>();

            using (XmlReader feedReader = XmlReader.Create(this.URL))
            {
                SyndicationFeed feedContent = SyndicationFeed.Load(feedReader);
                //XmlQualifiedName n = new XmlQualifiedName("itunes", "http://www.w3.org/2000/xmlns/");
                String itunesNs = "http://www.itunes.com/dtds/podcast-1.0.dtd";
                //feedContent.AttributeExtensions.Add(n, itunesNs);
                if (feedContent == null)
                {
                    return;
                }

                foreach (SyndicationItem item in feedContent.Items)
                {
                    SyndicationPerson author = item.Authors[0];

                    // Get values of syndication extension elements for a given namespace
                    string extensionNamespaceUri = "http://www.itunes.com/dtds/podcast-1.0.dtd";
                    SyndicationElementExtension extension = item.ElementExtensions.Where<SyndicationElementExtension>(x => x.OuterNamespace == extensionNamespaceUri).FirstOrDefault();
                    XPathNavigator dataNavigator = new XPathDocument(extension.GetReader()).CreateNavigator();

                    XmlNamespaceManager resolver = new XmlNamespaceManager(dataNavigator.NameTable);
                    resolver.AddNamespace("itunes", extensionNamespaceUri);

                    XPathNavigator authorNavigator = dataNavigator.SelectSingleNode("itunes:author", resolver);
                    XPathNavigator subtitleNavigator = dataNavigator.SelectSingleNode("itunes:subtitle", resolver);
                    XPathNavigator summaryNavigator = dataNavigator.SelectSingleNode("itunes:summary", resolver);
                    XPathNavigator durationNavigator = dataNavigator.SelectSingleNode("itunes:duration", resolver);
                    XPathNavigator imageNavigator = dataNavigator.SelectSingleNode("itunes:image", resolver);
                    String imageOuterXML = imageNavigator.OuterXml;

                    String imageUrl = String.Empty;
                    if (imageNavigator.MoveToFirstAttribute())
                    {
                        if (imageNavigator.Name == "href")
                        {
                            imageUrl = imageNavigator.Value.ToString();
                        }
                        while (imageNavigator.MoveToNextAttribute())
                        {
                            if (imageNavigator.Name == "href")
                            {
                                imageUrl = imageNavigator.Value.ToString();
                            }
                        }

                        // go back from the attributes to the parent element
                        imageNavigator.MoveToParent();
                    }

                    String authorx = authorNavigator != null ? authorNavigator.Value : String.Empty;
                    String subtitle = subtitleNavigator != null ? subtitleNavigator.Value : String.Empty;
                    String summary = summaryNavigator != null ? summaryNavigator.Value : String.Empty;
                    String duration = durationNavigator != null ? durationNavigator.Value : String.Empty;

                    Uri url = null;
                    long length = 0;
                    String mediaType = String.Empty;

                    foreach (SyndicationLink links in item.Links.Where<SyndicationLink>(links => links.RelationshipType == "enclosure"))
                    {
                        url = links.Uri;
                        length = links.Length;
                        mediaType = links.MediaType;
                    }

                    Episode podcastEpisode = new Episode()
                    {
                        Title = item.Title.Text,
                        Authors = author.Email,
                        PubData = item.PublishDate.LocalDateTime,
                        FileUrl = url,
                        Length = length,
                        Type = mediaType,
                        ImageUrl = new Uri(imageUrl),
                        Description = item.Summary.Text
                    };

                    this.Episodes.Add(podcastEpisode);

                }

            }
        }