static OSLanguageHelper()
        {
            AvailableUploadEnabledLanguagesList = new Dictionary<String,OSLanguage>();
            AvailableWebEnabledLanguagesList = new Dictionary<String, OSLanguage>();
            AllLanguagesList = new Dictionary<String, OSLanguage>();
            XPathNavigator xmlMetadataNavigator = new XPathDocument(new XmlTextReader(new StringReader(OpenSubtitlesDotNET.Resource.OSLanguageTableDump))).CreateNavigator();
            XPathNodeIterator languagesIter = xmlMetadataNavigator.Select("OSLanguageTableDump/language");
            if (languagesIter.Count > 0)
            {
                while (languagesIter.MoveNext())
                {
                    OSLanguage language = language = new OSLanguage(languagesIter.Current.SelectSingleNode("IdSubLanguage").Value,
                                languagesIter.Current.SelectSingleNode("ISO639").Value,
                                languagesIter.Current.SelectSingleNode("LanguageName").Value,
                                languagesIter.Current.SelectSingleNode("UploadEnabled").Value.Equals("0") ? false : true,
                                languagesIter.Current.SelectSingleNode("WebEnabled").Value.Equals("0") ? false : true);
                    if (!languagesIter.Current.SelectSingleNode("UploadEnabled").Value.Equals("0"))
                    {
                        AvailableUploadEnabledLanguagesList.Add(language.IdSubLanguage,language);
                    }
                    if (!languagesIter.Current.SelectSingleNode("WebEnabled").Value.Equals("0"))
                    {
                        AvailableWebEnabledLanguagesList.Add(language.IdSubLanguage,language);
                    }
                    AllLanguagesList.Add(language.IdSubLanguage, language);
                }
            }

        }
Example #2
0
		private static XPathNodeIterator GetCsprojNodeIterator(string select)
		{
			XPathNavigator navigator = new XPathDocument(arguments.ProjectFilePath).CreateNavigator();
			XmlNamespaceManager namespaceManager = new XmlNamespaceManager(navigator.NameTable);
			namespaceManager.AddNamespace("pr", "http://schemas.microsoft.com/developer/msbuild/2003");
			return navigator.Select(select, namespaceManager);
		}
Example #3
0
        public IDictionary<string, string> ProjectList()
        {
            XPathNavigator projects = new XPathDocument(_extractPath + "/desktop.xml").CreateNavigator();
            XPathNodeIterator nodes = projects.Select("/desktops/desktop/@name");
            Dictionary<string, string> result = new Dictionary<string,string>();

            while (nodes.MoveNext())
                result.Add(nodes.CurrentPosition.ToString(), nodes.Current.ToString());
            return result;
        }
        public void ParseLibrary(string pathName)
        {
            this.Tracks.Clear();

            var navigator = new XPathDocument(pathName).CreateNavigator();
            var iterator = navigator.Select("/plist/dict/dict/dict");
            while (iterator.MoveNext())
            {
                var track = this.parseTrack(iterator.Current.SelectChildren(XPathNodeType.All));
                if (track != null)
                {
                    this.Tracks.Add(track);
                }
            }
        }
 public static List<MapDescription> GetMapsFromReader(TextReader reader)
 {
     List<MapDescription> mapList = new List<MapDescription>();
     XPathNavigator nav = new XPathDocument(reader).CreateNavigator();
     XPathNodeIterator maps = nav.Select("/maps/map");
     while (maps.MoveNext()) {
         MapDescription map = new MapDescription();
         map.Name = maps.Current.SelectSingleNode("name").Value;
         map.Code = maps.Current.SelectSingleNode("code").Value;
         map.BaseLayer = maps.Current.SelectSingleNode("baseLayer").ValueAsBoolean;
         map.Covered = maps.Current.SelectSingleNode("covered").Value;
         map.Active = maps.Current.SelectSingleNode("active").ValueAsBoolean;
         mapList.Add(map);
     }
     return mapList;
 }
 private void LoadXml(XmlReader xmlReader)
 {
     var result = new List<INotifyAction>();
     XPathNavigator nav = new XPathDocument(xmlReader).CreateNavigator();
     var manager = new XmlNamespaceManager(nav.NameTable);
     manager.AddNamespace("act", "urn:asc.notify.action.xsd");
     XPathNodeIterator nodes = nav.Select("act:catalog/action", manager);
     while (nodes.MoveNext())
     {
         result.Add(
             new NotifyAction(
                 nodes.Current.GetAttribute("id", ""),
                 nodes.Current.GetAttribute("name", "")));
     }
     _ConstProvider = new ConstActionProvider(result.ToArray());
 }
Example #7
0
        public XPathNodeIterator FindCompileIncludeFile(string includeFile)
        {
            var document = XDocument.Load(projectFile);

            if (document.Root != null)
            {
                var navigator = new XPathDocument(projectFile).CreateNavigator();
                var namespaceManager = new XmlNamespaceManager(navigator.NameTable);
                namespaceManager.AddNamespace("pr", "http://schemas.microsoft.com/developer/msbuild/2003");

                return navigator.Select(
                    @"pr:Project/pr:ItemGroup/pr:Compile[@Include='" + includeFile + "']",
                    namespaceManager);
            }

            return null;
        }
Example #8
0
		public static void Read(string filepath, PropertyManager properties, ReferenceTable references, IdTable ids) {
			var xml = new XPathDocument(filepath).CreateNavigator();
			var pi = xml.Select("/Properties/Property");
			while ( pi.MoveNext() ) {
				var pnode = pi.Current;
				var p = properties.Create();
				ids[p] = new Guid(pnode.GetAttribute("id", ""));
				AssignProperties(pnode, p, references);
				var fi = pnode.Select("Flats/Flat");
				while ( fi.MoveNext() ) {
					var fnode = fi.Current;
					var f = p.CreateFlat();
					ids[f] = new Guid(fnode.GetAttribute("id", ""));
					AssignProperties(fnode, f, references);
				}
			}
		}
        private D900CdrDefinitionProvider(string xmlURI)
        {
            _schemaList = new List<D900CdrDefinitionSchema>();
            _defaultSchema = -1;
            _xmlVersion = String.Empty;

            bool def;

            #if FW35
            XElement cdrXML = XDocument
                .Load(xmlURI, LoadOptions.None)
                .Element("D900Cdr");

            __xmlVersion = cdrXML.Attribute("Version").Value;

            foreach (XElement schXML in cdrXML.Elements("Schema"))
            {
                D900CdrDefinitionSchema sch = new D900CdrDefinitionSchema(schXML.Attribute("Name").Value);
                ReadDefinitions(sch.Definitions, schXML, String.Empty);
                _schemaList.Add(sch);
                Boolean.TryParse(schXML.Attribute("Default").Value, out def);
                if (def) _defaultSchema = _schemaList.Count - 1;
            }
            #else
            XPathNavigator cdrXML = new XPathDocument(xmlURI)
                .CreateNavigator()
                .SelectSingleNode("D900Cdr");

            _xmlVersion = cdrXML.GetAttribute("Version", String.Empty);

            foreach (XPathNavigator schXML in cdrXML.Select("Schema"))
            {
                D900CdrDefinitionSchema sch = new D900CdrDefinitionSchema(schXML.GetAttribute("Name", String.Empty));
                ReadDefinitions(sch.Definitions, schXML, String.Empty);
                _schemaList.Add(sch);
                if (Boolean.TryParse(schXML.GetAttribute("Default", String.Empty), out def) && def)
                {
                    _defaultSchema = _schemaList.Count - 1;
                }
            }
            #endif
            if ((_defaultSchema < 0) && (_schemaList.Count > 0))
                _defaultSchema = 0;
            _currentSchema = _defaultSchema;
        }
        public override IEnumerable<Row> Execute(IEnumerable<Row> rows) {
            foreach (var row in rows) {
                if (ShouldRun(row)) {
                    var target = string.Empty;
                    var reader = new StringReader(row[InKey].ToString());
                    using (var xmlReader = XmlReader.Create(reader, _settings)) {
                        var navigator = new XPathDocument(xmlReader).CreateNavigator();
                        var result = navigator.Select(_xPath);
                        while (result.MoveNext()) {
                            target += result.Current.Value;
                        }
                    }
                    row[OutKey] = Common.ConversionMap[_outType](target);
                } else {
                    Interlocked.Increment(ref SkipCount);
                }

                yield return row;
            }
        }
Example #11
0
        public static void PostProcess(string xsdFile, ref string generatedCode, CodeDomProvider Provider)
        {
            XPathNavigator nav;
            using (FileStream fs = new FileStream(xsdFile, FileMode.Open, FileAccess.Read)) {
                nav = new XPathDocument(fs).CreateNavigator();
            }

            XPathNodeIterator it = nav.Select(PostExts);
            while (it.MoveNext()) {
                Dictionary<string, string> values = ParsePEValue(it.Current.Value);
                Type t = Type.GetType(values["extension-type"], true);
                // Is the type an ICodeExtension?
                Type iface = t.GetInterface(typeof(IPostExtension).Name);
                if (iface == null)
                    throw new ArgumentException(string.Format(Resources.ex_InvalidExtensionType, it.Current.Value));

                IPostExtension ext = (IPostExtension)Activator.CreateInstance(t);
                ext.Initialize(values);
                // Run it!
                ext.PostProcess(ref generatedCode, Provider);
            }
        }
Example #12
0
        /// <summary>
        /// Creates an <see cref="AtomLink" /> instance from XML.
        /// </summary>
        /// <param name="xmlReader">
        /// The <see cref="XmlReader" /> containing the XML representation of
        /// the Atom Link.
        /// </param>
        /// <returns>
        /// A new instance of <see cref="AtomLink" /> containing the data from
        /// the XML representation of the Atom link contained in
        /// <paramref name="xmlReader" />.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        /// The supplied XML reader contains an atom:link element without an href attribute.
        /// or
        /// The supplied XML reader contains an atom:link element without a rel attribute.
        /// </exception>
        public static AtomLink ReadFrom(XmlReader xmlReader)
        {
            var navigator = new XPathDocument(xmlReader).CreateNavigator();

            var resolver = new XmlNamespaceManager(new NameTable());
            resolver.AddNamespace("atom", "http://www.w3.org/2005/Atom");

            var href = navigator
                .Select("/atom:link/@href", resolver)
                .Cast<XPathNavigator>()
                .Select(x => x.Value)
                .SingleOrDefault();
            if (href == null)
                throw new ArgumentException("The supplied XML reader contains an atom:link element without an href attribute. An atom:link element must have an href attribute.", "xmlReader");

            var rel = navigator
                .Select("/atom:link/@rel", resolver)
                .Cast<XPathNavigator>()
                .Select(x => x.Value)
                .SingleOrDefault();
            if (rel == null)
                throw new ArgumentException("The supplied XML reader contains an atom:link element without a rel attribute. An atom:link element must have a rel attribute.", "xmlReader");

            return new AtomLink(rel, new Uri(href, UriKind.RelativeOrAbsolute));
        }
Example #13
0
 internal static ArrayList GetMessageStructure(string inputMsgFile, CommunicationManager.ReceiverType RxType, int mid, int sid, string protocol, string version)
 {
     XPathNavigator navigator = new XPathDocument(inputMsgFile).CreateNavigator();
     int num = 2;
     int num2 = 2;
     int num3 = 0;
     if (RxType == CommunicationManager.ReceiverType.SLC)
     {
         num3 = 1;
     }
     ArrayList list = new ArrayList();
     SLCMsgStructure structure = new SLCMsgStructure();
     int num4 = 0;
     XPathExpression expr = navigator.Compile(string.Concat(new object[] { "/protocols/protocol[@name='", protocol, "'][@version='", version, "']/input/message[@mid='", mid, "'][@subid = '", sid, "']/field" }));
     XPathNodeIterator iterator = navigator.Select(expr);
     if (iterator.Count == 0)
     {
         expr = navigator.Compile(string.Concat(new object[] { "/protocols/protocol[@name='", protocol, "'][@version='", version, "']/input/message[@mid='", mid, "'][@subid = '']/field" }));
         iterator = navigator.Select(expr);
     }
     try
     {
         int num5 = 0;
         int num6 = 0;
         while (iterator.MoveNext())
         {
             XPathNavigator navigator2 = iterator.Current.Clone();
             if (navigator2.GetAttribute("name", "").Contains("LOOP"))
             {
                 num5 = int.Parse(navigator2.GetAttribute("numloops", ""));
                 num6 = int.Parse(navigator2.GetAttribute("numlines", ""));
                 for (int i = 0; i < num5; i++)
                 {
                     for (int j = 0; j < num6; j++)
                     {
                         iterator.MoveNext();
                         navigator2 = iterator.Current.Clone();
                         structure.fieldNumber = iterator.CurrentPosition;
                         structure.fieldName = navigator2.GetAttribute("name", "");
                         structure.bytes = int.Parse(navigator2.GetAttribute("bytes", ""));
                         structure.datatype = navigator2.GetAttribute("datatype", "");
                         structure.units = navigator2.GetAttribute("units", "");
                         if (navigator2.GetAttribute("scale", "") == "")
                         {
                             structure.scale = 1.0;
                         }
                         else
                         {
                             structure.scale = double.Parse(navigator2.GetAttribute("scale", ""));
                         }
                         structure.startByte = (((num + num2) + num3) + 1) + num4;
                         structure.endByte = (structure.startByte + structure.bytes) - 1;
                         structure.defaultValue = navigator2.GetAttribute("default", "");
                         num4 += structure.bytes;
                         list.Add(structure);
                     }
                 }
             }
             else
             {
                 structure.fieldNumber = iterator.CurrentPosition;
                 structure.fieldName = navigator2.GetAttribute("name", "");
                 structure.bytes = int.Parse(navigator2.GetAttribute("bytes", ""));
                 structure.datatype = navigator2.GetAttribute("datatype", "");
                 structure.units = navigator2.GetAttribute("units", "");
                 if (navigator2.GetAttribute("scale", "") == "")
                 {
                     structure.scale = 1.0;
                 }
                 else
                 {
                     structure.scale = double.Parse(navigator2.GetAttribute("scale", ""));
                 }
                 structure.startByte = (((num + num2) + num3) + 1) + num4;
                 structure.endByte = (structure.startByte + structure.bytes) - 1;
                 structure.defaultValue = navigator2.GetAttribute("default", "");
                 num4 += structure.bytes;
                 list.Add(structure);
             }
         }
     }
     catch (Exception exception)
     {
         throw exception;
     }
     return list;
 }
 public override void ProcessFile(string file)
 {
     foreach (Exception ex in initializationErrors)
     {
         AddError(ex.Message);
     }
     using (XmlTextReader reader = new XmlTextReader(file))
     {
         var navigator = new XPathDocument(reader).CreateNavigator();
         foreach (XPathNavigator dvd in navigator.Select("/Collection/DVD|/DVD")) // Allow both collection file and single profile export
         {
             HandleDvd(dvd);
         }
     }
 }
Example #15
0
        // 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;
        }
        private void LoadXml(XmlReader xmlReader)
        {
            var result = new List<TernarAccord>();
            var nav = new XPathDocument(xmlReader).CreateNavigator();
            var manager = new XmlNamespaceManager(nav.NameTable);
            manager.AddNamespace("act", "urn:asc.notify.action_pattern.xsd");
            var nodes = nav.Select("act:accordings/action", manager);
            while (nodes.MoveNext())
            {
                var actNav = nodes.Current;
                var actionID = actNav.GetAttribute("actionID", "");
                var action = _ActionProvider.GetAction(actionID);
                if (action == null)
                {
                    log.Error(String.Format("action with id=\"{0}\" not instanced", actionID));
                    continue;
                }

                var defaultActionPattern = actNav.GetAttribute("defaultPatternID", "");
                if (!String.IsNullOrEmpty(defaultActionPattern))
                {
                    var defaultPattern = _PatternProvider.GetPattern(defaultActionPattern);
                    if (defaultPattern == null)
                    {
                        log.Error(String.Format("pattern with id=\"{0}\" not instanced", defaultActionPattern)); continue;
                    }
                    result.Add(new TernarAccord(action, new Accord(null, defaultPattern)));
                }

                var sendersNodes = actNav.SelectChildren("sender", "");
                while (sendersNodes.MoveNext())
                {
                    var senderName = sendersNodes.Current.GetAttribute("senderName", "");
                    var patternID = sendersNodes.Current.GetAttribute("patternID", "");
                    var pattern = _PatternProvider.GetPattern(patternID);
                    if (pattern == null)
                    {
                        log.Error(String.Format("pattern with id=\"{0}\" not instanced", patternID));
                        continue;
                    }
                    result.Add(new TernarAccord(action, new Accord(senderName, pattern)));
                }
            }
            _ConstProvider = new ConstActionPatternProvider(result.ToArray());
        }
        private void SetupWindowsUsingFanartHandlerVisibility(string SkinDir = (string) null, string ThemeDir = (string) null)
        {
            var path = string.Empty ;

              if (string.IsNullOrEmpty(SkinDir))
              {
            FS.WindowsUsingFanartSelectedMusic = new Hashtable();
            FS.WindowsUsingFanartSelectedScoreCenter = new Hashtable();
            FS.WindowsUsingFanartSelectedMovie = new Hashtable();
            FP.WindowsUsingFanartPlay = new Hashtable();
            FR.WindowsUsingFanartRandom = new Hashtable();

            path = GUIGraphicsContext.Skin + @"\";
            logger.Debug("Scan Skin folder for XML: "+path) ;
              }
              else
              {
            path = ThemeDir;
            logger.Debug("Scan Skin Theme folder for XML: "+path) ;
              }

              var files = new DirectoryInfo(path).GetFiles("*.xml");
              var XMLName = string.Empty;

              foreach (var fileInfo in files)
              {
            try
            {
              XMLName = fileInfo.Name;

              var _flag1Music = false;
              var _flag2Music = false;
              var _flag1ScoreCenter = false;
              var _flag2ScoreCenter = false;
              var _flag1Movie = false;
              var _flag2Movie = false;
              var _flagPlay = false;

              var XMLFolder = fileInfo.FullName.Substring(0, fileInfo.FullName.LastIndexOf("\\"));
              var navigator = new XPathDocument(fileInfo.FullName).CreateNavigator();
              var nodeValue = GetNodeValue(navigator.Select("/window/id"));

              if (!string.IsNullOrEmpty(nodeValue))
              {
            HandleXmlImports(fileInfo.FullName, nodeValue, ref _flag1Music, ref _flag2Music, ref _flag1ScoreCenter, ref _flag2ScoreCenter, ref _flag1Movie, ref _flag2Movie, ref _flagPlay);
            var xpathNodeIterator = navigator.Select("/window/controls/import");
            if (xpathNodeIterator.Count > 0)
            {
              while (xpathNodeIterator.MoveNext())
              {
                var XMLFullName = Path.Combine(XMLFolder, xpathNodeIterator.Current.Value);
                if (File.Exists(XMLFullName))
                  HandleXmlImports(XMLFullName, nodeValue, ref _flag1Music, ref _flag2Music, ref _flag1ScoreCenter, ref _flag2ScoreCenter, ref _flag1Movie, ref _flag2Movie, ref _flagPlay);
                else if ((!string.IsNullOrEmpty(SkinDir)) && (!string.IsNullOrEmpty(ThemeDir)))
                  {
                    XMLFullName = Path.Combine(SkinDir, xpathNodeIterator.Current.Value);
                    if (File.Exists(XMLFullName))
                      HandleXmlImports(XMLFullName, nodeValue, ref _flag1Music, ref _flag2Music, ref _flag1ScoreCenter, ref _flag2ScoreCenter, ref _flag1Movie, ref _flag2Movie, ref _flagPlay);
                  }
              }
            }
            xpathNodeIterator = navigator.Select("/window/controls/include");
            if (xpathNodeIterator.Count > 0)
            {
              while (xpathNodeIterator.MoveNext())
              {
                var XMLFullName = Path.Combine(XMLFolder, xpathNodeIterator.Current.Value);
                if (File.Exists(XMLFullName))
                  HandleXmlImports(XMLFullName, nodeValue, ref _flag1Music, ref _flag2Music, ref _flag1ScoreCenter, ref _flag2ScoreCenter, ref _flag1Movie, ref _flag2Movie, ref _flagPlay);
                else if ((!string.IsNullOrEmpty(SkinDir)) && (!string.IsNullOrEmpty(ThemeDir)))
                  {
                    XMLFullName = Path.Combine(SkinDir, xpathNodeIterator.Current.Value);
                    if (File.Exists(XMLFullName))
                      HandleXmlImports(XMLFullName, nodeValue, ref _flag1Music, ref _flag2Music, ref _flag1ScoreCenter, ref _flag2ScoreCenter, ref _flag1Movie, ref _flag2Movie, ref _flagPlay);
                  }
              }
            }

            if (_flag1Music && _flag2Music && !FS.WindowsUsingFanartSelectedMusic.Contains(nodeValue))
              FS.WindowsUsingFanartSelectedMusic.Add(nodeValue, nodeValue);
            if (_flag1ScoreCenter && _flag2ScoreCenter && !FS.WindowsUsingFanartSelectedScoreCenter.Contains(nodeValue))
              FS.WindowsUsingFanartSelectedScoreCenter.Add(nodeValue, nodeValue);
            if (_flag1Movie && _flag2Movie && !FS.WindowsUsingFanartSelectedMovie.Contains(nodeValue))
              FS.WindowsUsingFanartSelectedMovie.Add(nodeValue, nodeValue);
            if (_flagPlay && !FP.WindowsUsingFanartPlay.Contains(nodeValue))
                FP.WindowsUsingFanartPlay.Add(nodeValue, nodeValue);

            #region Random
            var skinFile = new FanartRandom.SkinFile();
            xpathNodeIterator = navigator.Select("/window/define");
            if (xpathNodeIterator.Count > 0)
            {
              while (xpathNodeIterator.MoveNext())
              {
                var s = xpathNodeIterator.Current.Value;
                if (s.StartsWith("#useRandomGamesUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomGamesFanartUser = ParseNodeValue(s);
                if (s.StartsWith("#useRandomMoviesUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomMoviesFanartUser = ParseNodeValue(s);
                if (s.StartsWith("#useRandomMoviesScraperFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomMoviesFanartScraper = ParseNodeValue(s);
                if (s.StartsWith("#useRandomMovingPicturesFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomMovingPicturesFanart = ParseNodeValue(s);
                if (s.StartsWith("#useRandomMusicUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomMusicFanartUser = ParseNodeValue(s);
                if (s.StartsWith("#useRandomMusicScraperFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomMusicFanartScraper = ParseNodeValue(s);
                if (s.StartsWith("#useRandomPicturesUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomPicturesFanartUser = ParseNodeValue(s);
                if (s.StartsWith("#useRandomScoreCenterUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomScoreCenterFanartUser = ParseNodeValue(s);
                if (s.StartsWith("#useRandomTVSeriesFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomTVSeriesFanart = ParseNodeValue(s);
                if (s.StartsWith("#useRandomTVUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomTVFanartUser = ParseNodeValue(s);
                if (s.StartsWith("#useRandomPluginsUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomPluginsFanartUser = ParseNodeValue(s);
              }
              if (string.IsNullOrEmpty(skinFile.UseRandomGamesFanartUser))
                skinFile.UseRandomGamesFanartUser = "******";
              if (string.IsNullOrEmpty(skinFile.UseRandomMoviesFanartUser))
                skinFile.UseRandomMoviesFanartUser = "******";
              if (string.IsNullOrEmpty(skinFile.UseRandomMoviesFanartScraper))
                skinFile.UseRandomMoviesFanartScraper = "False";
              if (string.IsNullOrEmpty(skinFile.UseRandomMovingPicturesFanart))
                skinFile.UseRandomMovingPicturesFanart = "False";
              if (string.IsNullOrEmpty(skinFile.UseRandomMusicFanartUser))
                skinFile.UseRandomMusicFanartUser = "******";
              if (string.IsNullOrEmpty(skinFile.UseRandomMusicFanartScraper))
                skinFile.UseRandomMusicFanartScraper = "False";
              if (string.IsNullOrEmpty(skinFile.UseRandomPicturesFanartUser))
                skinFile.UseRandomPicturesFanartUser = "******";
              if (string.IsNullOrEmpty(skinFile.UseRandomScoreCenterFanartUser))
                skinFile.UseRandomScoreCenterFanartUser = "******";
              if (string.IsNullOrEmpty(skinFile.UseRandomTVSeriesFanart))
                skinFile.UseRandomTVSeriesFanart = "False";
              if (string.IsNullOrEmpty(skinFile.UseRandomTVFanartUser))
                skinFile.UseRandomTVFanartUser = "******";
              if (string.IsNullOrEmpty(skinFile.UseRandomPluginsFanartUser))
                skinFile.UseRandomPluginsFanartUser = "******";
            }
            try
            {
              if (skinFile.UseRandomGamesFanartUser.Equals("False", StringComparison.CurrentCulture) &&
                  skinFile.UseRandomMoviesFanartUser.Equals("False", StringComparison.CurrentCulture) &&
                  skinFile.UseRandomMoviesFanartScraper.Equals("False", StringComparison.CurrentCulture) &&
                  skinFile.UseRandomMovingPicturesFanart.Equals("False", StringComparison.CurrentCulture) &&
                  skinFile.UseRandomMusicFanartUser.Equals("False", StringComparison.CurrentCulture) &&
                  skinFile.UseRandomMusicFanartScraper.Equals("False", StringComparison.CurrentCulture) &&
                  skinFile.UseRandomPicturesFanartUser.Equals("False", StringComparison.CurrentCulture) &&
                  skinFile.UseRandomScoreCenterFanartUser.Equals("False", StringComparison.CurrentCulture) &&
                  skinFile.UseRandomTVSeriesFanart.Equals("False", StringComparison.CurrentCulture) &&
                  skinFile.UseRandomTVFanartUser.Equals("False", StringComparison.CurrentCulture) &&
                  skinFile.UseRandomPluginsFanartUser.Equals("False", StringComparison.CurrentCulture)
                 )
              {
                continue;
              }
              if (!FR.WindowsUsingFanartRandom.Contains(nodeValue))
                FR.WindowsUsingFanartRandom.Add(nodeValue, skinFile);
              else
                FR.WindowsUsingFanartRandom[nodeValue] = skinFile ;
            }
            catch {  }
            #endregion
              }
            }
            catch (Exception ex)
            {
              logger.Error("SetupWindowsUsingFanartHandlerVisibility: "+(string.IsNullOrEmpty(ThemeDir) ? string.Empty : "Theme: "+ThemeDir+" ")+"Filename:"+ XMLName) ;
              logger.Error(ex) ;
            }
              }

              if (string.IsNullOrEmpty(ThemeDir) && !string.IsNullOrEmpty(GUIGraphicsContext.ThemeName))
              {
            // Include Themes
            var tThemeDir = path+@"Themes\"+GUIGraphicsContext.ThemeName.Trim()+@"\";
            if (Directory.Exists(tThemeDir))
              {
            SetupWindowsUsingFanartHandlerVisibility(path, tThemeDir);
            return;
              }
            tThemeDir = path+GUIGraphicsContext.ThemeName.Trim()+@"\";
            if (Directory.Exists(tThemeDir))
              SetupWindowsUsingFanartHandlerVisibility(path, tThemeDir);
              }
        }
Example #18
0
        public override bool Execute()
        {
            if (string.IsNullOrEmpty(IntermediateDirectory))
            {
                base.Log.LogError("IntermediateDirectory is null or empty");
            }
            string path = null;
            try
            {
                path = Path.Combine(IntermediateDirectory, "ContentPipeline.xml");
            }
            catch (ArgumentException)
            {
                base.Log.LogError("IntermediateDirectory invalid");
            }

            if (base.Log.HasLoggedErrors)
            {
                return false;
            }

            List<ITaskItem> list = new List<ITaskItem>();
            if (File.Exists(path))
            {
                XPathNavigator navigator = null;
                try
                {
                    navigator = new XPathDocument(path).CreateNavigator();
                    if (BuildWasSuccessful(navigator))
                    {
                        XPathNodeIterator outputiterator = navigator.Select("/XnaContent/Asset/Item[not(contains(Options,'IntermediateFile'))]/Output");
                        XPathNodeIterator extraiterator = navigator.Select("/XnaContent/Asset/Item[not(contains(Options,'IntermediateFile'))]/Extra");
                        while (outputiterator.MoveNext())
                        {
                            list.Add(new TaskItem(outputiterator.Current.Value));
                        }
                        while (extraiterator.MoveNext())
                        {
                            list.Add(new TaskItem(extraiterator.Current.Value));
                        }
                    }
                }
                catch (XmlException)
                {
                }
            }
            this.outputContentFiles = list.ToArray();
            return !base.Log.HasLoggedErrors;
        }
Example #19
0
 /// <summary>
 /// Builds the bot set.
 /// </summary>
 /// <returns></returns>
 static SetCollection<int> BuildBotSet()
 {
     SetCollection<int> result = new SetCollection<int>();
     string fileName = BotsDataBaseFile;
     if (File.Exists(fileName))
     {
         using (Stream xmlFile = new FileStream(fileName, FileMode.Open, FileAccess.Read))
         {
             XPathNavigator xml = new XPathDocument(xmlFile).CreateNavigator();
             XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xml.NameTable);
             namespaceManager.AddNamespace("bugx", "http://www.wavenet.be/bugx/web/bots.xsd");
             foreach (XPathNavigator node in xml.Select("/bugx:bots/bugx:bot", namespaceManager))
             {
                 result.Add(node.Value.GetHashCode());
             }
         }
     }
     return result;
 }
        private void SetupWindowsUsingFanartHandlerVisibility(string SkinDir = (string) null, string ThemeDir = (string) null)
        {
            var path = string.Empty;
              var theme = string.Empty;

              if (string.IsNullOrEmpty(SkinDir))
              {
            path = GUIGraphicsContext.Skin + @"\";
            theme = Utils.GetThemeFolder(path);
            logger.Debug("Scan Skin folder for XML: "+path) ;
              }
              else
              {
            path = ThemeDir;
            logger.Debug("Scan Skin Theme folder for XML: "+path) ;
              }

              var files = new DirectoryInfo(path).GetFiles("*.xml");
              var XMLName = string.Empty;

              foreach (var fileInfo in files)
              {
            try
            {
              XMLName = fileInfo.Name;

              var _flag1Music = false;
              var _flag2Music = false;
              var _flag1ScoreCenter = false;
              var _flag2ScoreCenter = false;
              var _flag1Movie = false;
              var _flag2Movie = false;
              var _flag1Picture = false;
              var _flag2Picture = false;
              var _flagPlay = false;

              var _flagGenrePlay = false;
              var _flagGenrePlayAll = false;
              var _flagGenrePlayVertical = false;

              var _flagGenreMusic = false;
              var _flagGenreMusicAll = false;
              var _flagGenreMusicVertical = false;

              var _flagAwardMovie = false;
              var _flagAwardMovieAll = false;
              var _flagAwardMovieVertical = false;
              var _flagGenreMovie = false;
              var _flagGenreMovieAll = false;
              var _flagGenreMovieVertical = false;
              var _flagStudioMovie = false;
              var _flagStudioMovieAll = false;
              var _flagStudioMovieVertical = false;

              var _flagClearArt = false;
              var _flagClearArtPlay = false;

              var XMLFolder = fileInfo.FullName.Substring(0, fileInfo.FullName.LastIndexOf("\\"));
              var navigator = new XPathDocument(fileInfo.FullName).CreateNavigator();
              var nodeValue = GetNodeValue(navigator.Select("/window/id"));

              if (!string.IsNullOrEmpty(nodeValue))
              {
            HandleXmlImports(fileInfo.FullName, nodeValue, ref _flag1Music, ref _flag2Music,
                                                           ref _flag1ScoreCenter, ref _flag2ScoreCenter,
                                                           ref _flag1Movie, ref _flag2Movie,
                                                           ref _flag1Picture, ref _flag2Picture,
                                                           ref _flagPlay,
                                                           ref _flagClearArt, ref _flagClearArtPlay,
                                                           ref _flagGenrePlay, ref _flagGenrePlayAll, ref _flagGenrePlayVertical,
                                                           ref _flagGenreMusic, ref _flagGenreMusicAll, ref _flagGenreMusicVertical,
                                                           ref _flagGenreMovie, ref _flagGenreMovieAll, ref _flagGenreMovieVertical,
                                                           ref _flagStudioMovie, ref _flagStudioMovieAll, ref _flagStudioMovieVertical,
                                                           ref _flagAwardMovie, ref _flagAwardMovieAll, ref _flagAwardMovieVertical
                                                           );
            var xpathNodeIterator = navigator.Select("/window/controls/import");
            if (xpathNodeIterator.Count > 0)
            {
              while (xpathNodeIterator.MoveNext())
              {
                var XMLFullName = Path.Combine(XMLFolder, xpathNodeIterator.Current.Value);
                if (File.Exists(XMLFullName))
                {
                  HandleXmlImports(XMLFullName, nodeValue, ref _flag1Music, ref _flag2Music,
                                                           ref _flag1ScoreCenter, ref _flag2ScoreCenter,
                                                           ref _flag1Movie, ref _flag2Movie,
                                                           ref _flag1Picture, ref _flag2Picture,
                                                           ref _flagPlay,
                                                           ref _flagClearArt, ref _flagClearArtPlay,
                                                           ref _flagGenrePlay, ref _flagGenrePlayAll, ref _flagGenrePlayVertical,
                                                           ref _flagGenreMusic, ref _flagGenreMusicAll, ref _flagGenreMusicVertical,
                                                           ref _flagGenreMovie, ref _flagGenreMovieAll, ref _flagGenreMovieVertical,
                                                           ref _flagStudioMovie, ref _flagStudioMovieAll, ref _flagStudioMovieVertical,
                                                           ref _flagAwardMovie, ref _flagAwardMovieAll, ref _flagAwardMovieVertical
                                                           );
                  if (!string.IsNullOrEmpty(theme))
                  {
                    XMLFullName = Path.Combine(theme, xpathNodeIterator.Current.Value);
                    if (File.Exists(XMLFullName))
                      HandleXmlImports(XMLFullName, nodeValue, ref _flag1Music, ref _flag2Music,
                                                               ref _flag1ScoreCenter, ref _flag2ScoreCenter,
                                                               ref _flag1Movie, ref _flag2Movie,
                                                               ref _flag1Picture, ref _flag2Picture,
                                                               ref _flagPlay,
                                                               ref _flagClearArt, ref _flagClearArtPlay,
                                                               ref _flagGenrePlay, ref _flagGenrePlayAll, ref _flagGenrePlayVertical,
                                                               ref _flagGenreMusic, ref _flagGenreMusicAll, ref _flagGenreMusicVertical,
                                                               ref _flagGenreMovie, ref _flagGenreMovieAll, ref _flagGenreMovieVertical,
                                                               ref _flagStudioMovie, ref _flagStudioMovieAll, ref _flagStudioMovieVertical,
                                                               ref _flagAwardMovie, ref _flagAwardMovieAll, ref _flagAwardMovieVertical
                                                               );
                  }
                }
                else if ((!string.IsNullOrEmpty(SkinDir)) && (!string.IsNullOrEmpty(ThemeDir)))
                {
                  XMLFullName = Path.Combine(SkinDir, xpathNodeIterator.Current.Value);
                  if (File.Exists(XMLFullName))
                    HandleXmlImports(XMLFullName, nodeValue, ref _flag1Music, ref _flag2Music,
                                                             ref _flag1ScoreCenter, ref _flag2ScoreCenter,
                                                             ref _flag1Movie, ref _flag2Movie,
                                                             ref _flag1Picture, ref _flag2Picture,
                                                             ref _flagPlay,
                                                             ref _flagClearArt, ref _flagClearArtPlay,
                                                             ref _flagGenrePlay, ref _flagGenrePlayAll, ref _flagGenrePlayVertical,
                                                             ref _flagGenreMusic, ref _flagGenreMusicAll, ref _flagGenreMusicVertical,
                                                             ref _flagGenreMovie, ref _flagGenreMovieAll, ref _flagGenreMovieVertical,
                                                             ref _flagStudioMovie, ref _flagStudioMovieAll, ref _flagStudioMovieVertical,
                                                             ref _flagAwardMovie, ref _flagAwardMovieAll, ref _flagAwardMovieVertical
                                                             );
                }
              }
            }
            xpathNodeIterator = navigator.Select("/window/controls/include");
            if (xpathNodeIterator.Count > 0)
            {
              while (xpathNodeIterator.MoveNext())
              {
                var XMLFullName = Path.Combine(XMLFolder, xpathNodeIterator.Current.Value);
                if (File.Exists(XMLFullName))
                {
                  HandleXmlImports(XMLFullName, nodeValue, ref _flag1Music, ref _flag2Music,
                                                           ref _flag1ScoreCenter, ref _flag2ScoreCenter,
                                                           ref _flag1Movie, ref _flag2Movie,
                                                           ref _flag1Picture, ref _flag2Picture,
                                                           ref _flagPlay,
                                                           ref _flagClearArt, ref _flagClearArtPlay,
                                                           ref _flagGenrePlay, ref _flagGenrePlayAll, ref _flagGenrePlayVertical,
                                                           ref _flagGenreMusic, ref _flagGenreMusicAll, ref _flagGenreMusicVertical,
                                                           ref _flagGenreMovie, ref _flagGenreMovieAll, ref _flagGenreMovieVertical,
                                                           ref _flagStudioMovie, ref _flagStudioMovieAll, ref _flagStudioMovieVertical,
                                                           ref _flagAwardMovie, ref _flagAwardMovieAll, ref _flagAwardMovieVertical
                                                           );
                  if (!string.IsNullOrEmpty(theme))
                  {
                    XMLFullName = Path.Combine(theme, xpathNodeIterator.Current.Value);
                    if (File.Exists(XMLFullName))
                      HandleXmlImports(XMLFullName, nodeValue, ref _flag1Music, ref _flag2Music,
                                                               ref _flag1ScoreCenter, ref _flag2ScoreCenter,
                                                               ref _flag1Movie, ref _flag2Movie,
                                                               ref _flag1Picture, ref _flag2Picture,
                                                               ref _flagPlay,
                                                               ref _flagClearArt, ref _flagClearArtPlay,
                                                               ref _flagGenrePlay, ref _flagGenrePlayAll, ref _flagGenrePlayVertical,
                                                               ref _flagGenreMusic, ref _flagGenreMusicAll, ref _flagGenreMusicVertical,
                                                               ref _flagGenreMovie, ref _flagGenreMovieAll, ref _flagGenreMovieVertical,
                                                               ref _flagStudioMovie, ref _flagStudioMovieAll, ref _flagStudioMovieVertical,
                                                               ref _flagAwardMovie, ref _flagAwardMovieAll, ref _flagAwardMovieVertical
                                                               );
                  }
                }
                else if ((!string.IsNullOrEmpty(SkinDir)) && (!string.IsNullOrEmpty(ThemeDir)))
                {
                  XMLFullName = Path.Combine(SkinDir, xpathNodeIterator.Current.Value);
                  if (File.Exists(XMLFullName))
                    HandleXmlImports(XMLFullName, nodeValue, ref _flag1Music, ref _flag2Music,
                                                             ref _flag1ScoreCenter, ref _flag2ScoreCenter,
                                                             ref _flag1Movie, ref _flag2Movie,
                                                             ref _flag1Picture, ref _flag2Picture,
                                                             ref _flagPlay,
                                                             ref _flagClearArt, ref _flagClearArtPlay,
                                                             ref _flagGenrePlay, ref _flagGenrePlayAll, ref _flagGenrePlayVertical,
                                                             ref _flagGenreMusic, ref _flagGenreMusicAll, ref _flagGenreMusicVertical,
                                                             ref _flagGenreMovie, ref _flagGenreMovieAll, ref _flagGenreMovieVertical,
                                                             ref _flagStudioMovie, ref _flagStudioMovieAll, ref _flagStudioMovieVertical,
                                                             ref _flagAwardMovie, ref _flagAwardMovieAll, ref _flagAwardMovieVertical
                                                             );
                }
              }
            }

            if (_flag1Music && _flag2Music && !Utils.ContainsID(FSelected.WindowsUsingFanartSelectedMusic, nodeValue))
            {
              FSelected.WindowsUsingFanartSelectedMusic.Add(nodeValue, nodeValue);
            }
            if (_flag1ScoreCenter && _flag2ScoreCenter && !Utils.ContainsID(FSelected.WindowsUsingFanartSelectedScoreCenter, nodeValue))
            {
              FSelected.WindowsUsingFanartSelectedScoreCenter.Add(nodeValue, nodeValue);
            }
            if (_flag1Movie && _flag2Movie && !Utils.ContainsID(FSelected.WindowsUsingFanartSelectedMovie, nodeValue))
            {
              FSelected.WindowsUsingFanartSelectedMovie.Add(nodeValue, nodeValue);
            }
            if (_flag1Picture && _flag2Picture && !Utils.ContainsID(FSelected.WindowsUsingFanartSelectedPictures, nodeValue))
            {
              FSelected.WindowsUsingFanartSelectedPictures.Add(nodeValue, nodeValue);
            }
            if (_flagPlay && !Utils.ContainsID(FPlay.WindowsUsingFanartPlay, nodeValue))
            {
              FPlay.WindowsUsingFanartPlay.Add(nodeValue, nodeValue);
            }

            #region ClearArt
            // Play Music ClearArt
            if (_flagClearArtPlay && !Utils.ContainsID(FPlayOther.WindowsUsingFanartPlayClearArt, nodeValue))
            {
              FPlayOther.WindowsUsingFanartPlayClearArt.Add(nodeValue, nodeValue);
            }
            // Selected Music ClearArt
            if (_flagClearArt && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedClearArtMusic, nodeValue))
            {
              FSelectedOther.WindowsUsingFanartSelectedClearArtMusic.Add(nodeValue, nodeValue);
            }
            #endregion

            #region Genres and Studios
            // Play Music Genre
            if (_flagGenrePlay && !Utils.ContainsID(FPlayOther.WindowsUsingFanartPlayGenre, nodeValue))
            {
              FPlayOther.WindowsUsingFanartPlayGenre.Add(nodeValue, nodeValue);
            }
            if (_flagGenrePlayAll && !Utils.ContainsID(FPlayOther.WindowsUsingFanartPlayGenre, nodeValue + Utils.Logo.Horizontal))
            {
              FPlayOther.WindowsUsingFanartPlayGenre.Add(nodeValue + Utils.Logo.Horizontal, nodeValue + Utils.Logo.Horizontal);
            }
            if (_flagGenrePlayVertical && !Utils.ContainsID(FPlayOther.WindowsUsingFanartPlayGenre, nodeValue + Utils.Logo.Vertical))
            {
              FPlayOther.WindowsUsingFanartPlayGenre.Add(nodeValue + Utils.Logo.Vertical, nodeValue + Utils.Logo.Vertical);
            }
            // Selected Music Genre
            if (_flagGenreMusic && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedGenreMusic, nodeValue))
            {
              FSelectedOther.WindowsUsingFanartSelectedGenreMusic.Add(nodeValue, nodeValue);
            }
            if (_flagGenreMusicAll && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedGenreMusic, nodeValue + Utils.Logo.Horizontal))
            {
              FSelectedOther.WindowsUsingFanartSelectedGenreMusic.Add(nodeValue + Utils.Logo.Horizontal, nodeValue + Utils.Logo.Horizontal);
            }
            if (_flagGenreMusicVertical && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedGenreMusic, nodeValue + Utils.Logo.Vertical))
            {
              FSelectedOther.WindowsUsingFanartSelectedGenreMusic.Add(nodeValue + Utils.Logo.Vertical, nodeValue + Utils.Logo.Vertical);
            }
            // Selected Movie Award
            if (_flagAwardMovie && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedAwardMovie, nodeValue))
            {
              FSelectedOther.WindowsUsingFanartSelectedAwardMovie.Add(nodeValue, nodeValue);
            }
            if (_flagAwardMovieAll && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedAwardMovie, nodeValue + Utils.Logo.Horizontal))
            {
              FSelectedOther.WindowsUsingFanartSelectedAwardMovie.Add(nodeValue + Utils.Logo.Horizontal, nodeValue + Utils.Logo.Horizontal);
            }
            if (_flagAwardMovieVertical && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedAwardMovie, nodeValue + Utils.Logo.Vertical))
            {
              FSelectedOther.WindowsUsingFanartSelectedAwardMovie.Add(nodeValue + Utils.Logo.Vertical, nodeValue + Utils.Logo.Vertical);
            }
            // Selected Movie Genre
            if (_flagGenreMovie && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedGenreMovie, nodeValue))
            {
              FSelectedOther.WindowsUsingFanartSelectedGenreMovie.Add(nodeValue, nodeValue);
            }
            if (_flagGenreMovieAll && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedGenreMovie, nodeValue + Utils.Logo.Horizontal))
            {
              FSelectedOther.WindowsUsingFanartSelectedGenreMovie.Add(nodeValue + Utils.Logo.Horizontal, nodeValue + Utils.Logo.Horizontal);
            }
            if (_flagGenreMovieVertical && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedGenreMovie, nodeValue + Utils.Logo.Vertical))
            {
              FSelectedOther.WindowsUsingFanartSelectedGenreMovie.Add(nodeValue + Utils.Logo.Vertical, nodeValue + Utils.Logo.Vertical);
            }
            // Selected Movie Studio
            if (_flagStudioMovie && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedStudioMovie, nodeValue))
            {
              FSelectedOther.WindowsUsingFanartSelectedStudioMovie.Add(nodeValue, nodeValue);
            }
            if (_flagStudioMovieAll && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedStudioMovie, nodeValue + Utils.Logo.Horizontal))
            {
              FSelectedOther.WindowsUsingFanartSelectedStudioMovie.Add(nodeValue + Utils.Logo.Horizontal, nodeValue + Utils.Logo.Horizontal);
            }
            if (_flagStudioMovieVertical && !Utils.ContainsID(FSelectedOther.WindowsUsingFanartSelectedStudioMovie, nodeValue + Utils.Logo.Vertical))
            {
              FSelectedOther.WindowsUsingFanartSelectedStudioMovie.Add(nodeValue + Utils.Logo.Vertical, nodeValue + Utils.Logo.Vertical);
            }
            #endregion

            #region Random
            var skinFile = new FanartRandom.SkinFile();
            xpathNodeIterator = navigator.Select("/window/define");
            if (xpathNodeIterator.Count > 0)
            {
              while (xpathNodeIterator.MoveNext())
              {
                var s = xpathNodeIterator.Current.Value;
                if (s.StartsWith("#useRandomGamesUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomGamesFanartUser = Utils.GetBool(ParseNodeValue(s));
                if (s.StartsWith("#useRandomMoviesUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomMoviesFanartUser = Utils.GetBool(ParseNodeValue(s));
                if (s.StartsWith("#useRandomMoviesScraperFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomMoviesFanartScraper = Utils.GetBool(ParseNodeValue(s));
                if (s.StartsWith("#useRandomMovingPicturesFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomMovingPicturesFanart = Utils.GetBool(ParseNodeValue(s));
                if (s.StartsWith("#useRandomMusicUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomMusicFanartUser = Utils.GetBool(ParseNodeValue(s));
                if (s.StartsWith("#useRandomMusicScraperFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomMusicFanartScraper = Utils.GetBool(ParseNodeValue(s));
                if (s.StartsWith("#useRandomPicturesUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomPicturesFanartUser = Utils.GetBool(ParseNodeValue(s));
                if (s.StartsWith("#useRandomScoreCenterUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomScoreCenterFanartUser = Utils.GetBool(ParseNodeValue(s));
                if (s.StartsWith("#useRandomTVSeriesFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomTVSeriesFanart = Utils.GetBool(ParseNodeValue(s));
                if (s.StartsWith("#useRandomTVUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomTVFanartUser = Utils.GetBool(ParseNodeValue(s));
                if (s.StartsWith("#useRandomPluginsUserFanart", StringComparison.CurrentCulture))
                  skinFile.UseRandomPluginsFanartUser = Utils.GetBool(ParseNodeValue(s));
                // logger.Debug("*** Random check: " + s + " - " + nodeValue);
              }
            }
            try
            {
              if (skinFile.UseRandomGamesFanartUser ||
                  skinFile.UseRandomMoviesFanartUser ||
                  skinFile.UseRandomMoviesFanartScraper ||
                  skinFile.UseRandomMovingPicturesFanart ||
                  skinFile.UseRandomMusicFanartUser ||
                  skinFile.UseRandomMusicFanartScraper ||
                  skinFile.UseRandomPicturesFanartUser ||
                  skinFile.UseRandomScoreCenterFanartUser ||
                  skinFile.UseRandomTVSeriesFanart ||
                  skinFile.UseRandomTVFanartUser ||
                  skinFile.UseRandomPluginsFanartUser)
              {
                if (Utils.ContainsID(FRandom.WindowsUsingFanartRandom, nodeValue))
                {
                  FRandom.WindowsUsingFanartRandom[nodeValue] = skinFile ;
                  // logger.Debug("*** Random update: " + nodeValue + " - " + (string.IsNullOrEmpty(ThemeDir) ? string.Empty : "Theme: "+ThemeDir+" ")+" Filename:" + XMLName);
                }
                else
                {
                  FRandom.WindowsUsingFanartRandom.Add(nodeValue, skinFile);
                  // logger.Debug("*** Random add: " + nodeValue + " - " + (string.IsNullOrEmpty(ThemeDir) ? string.Empty : "Theme: "+ThemeDir+" ")+" Filename:" + XMLName);
                }
              }
            }
            catch {  }
            #endregion
              }
            }
            catch (Exception ex)
            {
              logger.Error("SetupWindowsUsingFanartHandlerVisibility: " + (string.IsNullOrEmpty(ThemeDir) ? string.Empty : "Theme: "+ThemeDir+" ")+" Filename:" + XMLName);
              logger.Error(ex) ;
            }
              }

              if (string.IsNullOrEmpty(ThemeDir))
              {
            // Include Themes
            if (!string.IsNullOrEmpty(theme))
            {
              SetupWindowsUsingFanartHandlerVisibility(path, theme);
            }
              }
        }
Example #21
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.");
        }
Example #22
0
        /// <summary>
        /// Creates an <see cref="AtomAuthor" /> instance from XML.
        /// </summary>
        /// <param name="xmlReader">
        /// The <see cref="XmlReader" /> containing the XML representation of
        /// the Atom Author.
        /// </param>
        /// <returns>
        /// A new instance of <see cref="AtomAuthor" /> containing the data
        /// from the XML representation of the Atom Author contained in
        /// <paramref name="xmlReader" />.
        /// </returns>
        public static AtomAuthor ReadFrom(XmlReader xmlReader)
        {
            var navigator = new XPathDocument(xmlReader).CreateNavigator();

            var resolver = new XmlNamespaceManager(new NameTable());
            resolver.AddNamespace("atom", "http://www.w3.org/2005/Atom");

            var name = navigator
                .Select("/atom:author/atom:name", resolver).Cast<XPathNavigator>()
                .Single().Value;

            return new AtomAuthor(name);
        }
Example #23
0
		public static void Read(string filepath, LesseeManager lessees, ReferenceTable references, IdTable ids) {
			var xml = new XPathDocument(filepath).CreateNavigator();
			var li = xml.Select("/Lessees/Lessee");
            var list = new List<Lessee>();
			while ( li.MoveNext() ) {
				var lnode = li.Current;
				var l = new Lessee();
				ids[l] = new Guid(lnode.GetAttribute("id", ""));
				AssignProperties(lnode, l, references);
				var pi = lnode.Select("Payments/AdvancePayment");
				while ( pi.MoveNext() ) {
					var pnode = pi.Current;
					var p = new AdvancePayment();
					ids[p] = new Guid(pnode.GetAttribute("id", ""));
					AssignProperties(pnode, p, references);
					l.Payments.Add(p);
				}
                list.Add(l);
			}
            foreach (var i in list.OrderBy(item => item.Name))
                lessees.Add(i);
		}
Example #24
0
        /// <summary>
        /// Processes the schema.
        /// </summary>
        /// <param name="xsdFile">The full path to the WXS file to process.</param>
        /// <param name="targetNamespace">The namespace to put generated classes in.</param>
        /// <returns>The CodeDom tree generated from the schema.</returns>
        public static CodeNamespace Process(string xsdFile, string targetNamespace, CodeDomProvider Provider)
        {
            // Load the XmlSchema and its collection.
            //XmlSchema xsd;
            //using ( FileStream fs = new FileStream( xsdFile, FileMode.Open ) )
            //{
            //    xsd = XmlSchema.Read( fs,  VH1 );
            //    xsd.Compile( VH2  );
            //}
            XmlSchemaSet set = new XmlSchemaSet();
            XmlSchema xsd = set.Add(null, xsdFile);
            set.Compile();

            XmlSchemas schemas = new XmlSchemas();
            schemas.Add(xsd);

            // Create the importer for these schemas.
            XmlSchemaImporter importer = new XmlSchemaImporter(schemas);

            // System.CodeDom namespace for the XmlCodeExporter to put classes in.
            CodeNamespace ns = new CodeNamespace(targetNamespace);
            XmlCodeExporter exporter = new XmlCodeExporter(ns);
            // Iterate schema top-level elements and export code for each.
            foreach (XmlSchemaElement element in set.GlobalElements.Values) {
                // Import the mapping first.
                XmlTypeMapping mapping = importer.ImportTypeMapping(
                    element.QualifiedName);
                // Export the code finally.
                exporter.ExportTypeMapping(mapping);
            }

            #region Execute extensions

            XPathNavigator nav;
            using (FileStream fs = new FileStream(xsdFile, FileMode.Open, FileAccess.Read)) {
                nav = new XPathDocument(fs).CreateNavigator();
            }

            XPathNodeIterator it = nav.Select(Extensions);
            while (it.MoveNext()) {
                Dictionary<string, string> values = ParsePEValue(it.Current.Value);
                Type t = Type.GetType(values["extension-type"], true);
                // Is the type an ICodeExtension?
                Type iface = t.GetInterface(typeof(ICodeExtension).Name);
                if (iface == null)
                    throw new ArgumentException(string.Format(Resources.ex_InvalidExtensionType, it.Current.Value));

                ICodeExtension ext = (ICodeExtension)Activator.CreateInstance(t);
                ext.Initialize(values);
                // Run it!
                ext.Process(ns, xsd, Provider);
            }

            #endregion Execute extensions

            return ns;
        }
Example #25
0
        /// <summary>
        /// Creates an <see cref="AtomFeed" /> instance from XML.
        /// </summary>
        /// <param name="xmlReader">
        /// The <see cref="XmlReader" /> containing the XML representation of
        /// the Atom Feed.
        /// </param>
        /// <param name="serializer">
        /// The <see cref="IContentSerializer" /> used to serialize custom XML
        /// content.
        /// </param>
        /// <returns>
        /// A new instance of <see cref="AtomFeed" /> containing the data from
        /// the XML representation of the Atom Feed contained in
        /// <paramref name="xmlReader" />.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="serializer" /> is <see langword="null" />.
        /// </exception>
        public static AtomFeed ReadFrom(
            XmlReader xmlReader,
            IContentSerializer serializer)
        {
            if (serializer == null)
                throw new ArgumentNullException("serializer");

            var navigator = new XPathDocument(xmlReader).CreateNavigator();

            var resolver = new XmlNamespaceManager(new NameTable());
            resolver.AddNamespace("atom", "http://www.w3.org/2005/Atom");

            var id = navigator
                .Select("/atom:feed/atom:id", resolver).Cast<XPathNavigator>()
                .Single().Value;
            var title = navigator
                .Select("/atom:feed/atom:title[@type = 'text']", resolver).Cast<XPathNavigator>()
                .Single().Value;
            var updated = navigator
                .Select("/atom:feed/atom:updated", resolver).Cast<XPathNavigator>()
                .Single().Value;
            var author = navigator
                .Select("/atom:feed/atom:author", resolver).Cast<XPathNavigator>()
                .Single().ReadSubtree();
            var entries = navigator
                .Select("/atom:feed/atom:entry", resolver).Cast<XPathNavigator>();
            var links = navigator
                .Select("/atom:feed/atom:link", resolver).Cast<XPathNavigator>();

            return new AtomFeed(
                UuidIri.Parse(id),
                title,
                DateTimeOffset.Parse(updated, CultureInfo.InvariantCulture),
                AtomAuthor.ReadFrom(author),
                entries.Select(x => AtomEntry.ReadFrom(x.ReadSubtree(), serializer)),
                links.Select(x => AtomLink.ReadFrom(x.ReadSubtree())));
        }