private string GetContents(string xpath_expr, XPathNavigator nav) { XPathNodeIterator rk_nodes = (XPathNodeIterator) nav.Evaluate(xpath_expr); while (rk_nodes.MoveNext()) { return rk_nodes.Current.ToString(); } return null; }
public static string GetNodeValue(XPathNavigator node) { if (node == null) { return null; } return node.Value.Trim(); }
public static DateTime GetDate(XPathNavigator node) { DateTime date = DateTime.Now; string dateString = node.Value; if (!DateTime.TryParseExact(dateString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { date = DateTime.ParseExact(dateString, "d-MMM-yyyy", CultureInfo.InvariantCulture); } return date; }
public void Init() { doc.LoadXml(testXml); if(!nsTable.ContainsKey("ns")) nsTable.Add("ns", "http://www.sharpvectors.org"); a = doc.SelectSingleNode("//a").CreateNavigator(); b = doc.SelectSingleNode("//b").CreateNavigator(); c = doc.SelectSingleNode("//c").CreateNavigator(); d = doc.SelectSingleNode("//d").CreateNavigator(); e = doc.SelectSingleNode("//e").CreateNavigator(); f = doc.SelectSingleNode("//f").CreateNavigator(); g = doc.SelectSingleNode("//*[local-name()='g']").CreateNavigator(); }
public XRDParser(Stream xrd) { doc_ = new XPathDocument (xrd); result_ = new XRDDocument (); cursor_ = doc_.CreateNavigator(); expires_exp_ = cursor_.Compile ("/XRD/Expires"); subject_exp_ = cursor_.Compile ("/XRD/Subject"); aliases_exp_ = cursor_.Compile ("/XRD/Alias"); types_exp_ = cursor_.Compile ("/XRD/Type"); link_rel_exp_ = cursor_.Compile ("/XRD/Link/Rel"); link_uri_exp_ = cursor_.Compile ("/XRD/Link/URI"); link_mediatype_exp_ = cursor_.Compile ("/XRD/Link/MediaType"); }
public static Author GetAuthor(BookstoreEntities bookstoreContext, XPathNavigator node) { string authorName = Utils.GetNodeValue(node); var author = bookstoreContext.Authors.FirstOrDefault(a => a.AuthorName == authorName); if (author == null) { author = new Author { AuthorName = authorName }; bookstoreContext.Authors.Add(author); bookstoreContext.SaveChanges(); } return author; }
public MediaValues(XPathNavigator xpath) { if (xpath == null) throw new ArgumentNullException("xpath"); Name = xpath.GetAttribute("nodeName", ""); Values = new Dictionary<string, string>(); var result = xpath.SelectChildren(XPathNodeType.Element); while (result.MoveNext()) { if (result.Current != null && !result.Current.HasAttributes) { Values.Add(result.Current.Name, result.Current.Value); } } if (Values.Keys.Contains("error")) { NiceUrl = ""; } else { NiceUrl = Values["umbracoFile"]; } }
public override bool PreserveWhitespace(XPathNavigator node) { return true; }
protected XPathNodeIterator CreateIterator(string xpath, XPathNavigator navigator) { try { if (this.Document == null || xpath == null || xpath.Trim() == "") return null; XPathNavigator nav = ((navigator == null) ? this.Document.CreateNavigator() : navigator); XPathExpression expression = nav.Compile(xpath.Trim()); if (this.Manager != null) expression.SetContext(this.Manager); return nav.Select(expression); } catch { return null; } }
public void OnConstructor(XPathNavigator nav, MethodDefinition method) { MarkMethod(method); }
public string returnString(XPathNavigator nav, string xp) { return nav.Select(xp).ToString(); }
public abstract virtual bool IsSamePosition(XPathNavigator other) { }
public virtual void PrependChild(XPathNavigator newChild) { }
AssemblyNameReference GetAssemblyName(XPathNavigator nav) { return(AssemblyNameReference.Parse(GetFullName(nav))); }
public virtual void DeleteRange(XPathNavigator lastSiblingToDelete) { }
public XPathDescendantIterator(XPathNavigator nav, XPathNodeType type, bool matchSelf) : base(nav, type, matchSelf) { }
public XPathDescendantIterator(XPathNavigator nav, string name, string namespaceURI, bool matchSelf) : base(nav, name, namespaceURI, matchSelf) { }
private IEnumerable <EditorDataItem> GetEditorDataItems(int currentId, int parentId) { XmlDocument xmlDocument; List <EditorDataItem> editorDataItems = new List <EditorDataItem>(); switch (this.XmlData) { case "content": xmlDocument = uQuery.GetPublishedXml(uQuery.UmbracoObjectType.Document); break; case "media": xmlDocument = uQuery.GetPublishedXml(uQuery.UmbracoObjectType.Media); break; case "members": xmlDocument = uQuery.GetPublishedXml(uQuery.UmbracoObjectType.Member); break; case "url": xmlDocument = new XmlDocument(); var url = this.Url.Replace("@contextId", currentId.ToString()); xmlDocument.LoadXml(Helper.GetDataFromUrl(url)); break; default: xmlDocument = null; break; } if (xmlDocument != null) { string xPath = this.XPath; if (xPath.Contains("$ancestorOrSelf")) { // default to 'self-or-parent-or-root' int ancestorOrSelfId = currentId > 0 ? currentId : parentId > 0 ? parentId : -1; // if we have a content id, but it's not published in the xml if (this.XmlData == "content" && ancestorOrSelfId > 0 && xmlDocument.SelectSingleNode("/descendant::*[@id='" + ancestorOrSelfId + "']") == null) { // use Umbraco API to get path of all ids above ancestorOrSelfId to root Queue <int> path = new Queue <int>(ApplicationContext.Current.Services.ContentService.GetById(ancestorOrSelfId).Path.Split(',').Select(x => int.Parse(x)).Reverse().Skip(1)); // find the nearest id in the xml do { ancestorOrSelfId = path.Dequeue(); }while (xmlDocument.SelectSingleNode("/descendant::*[@id='" + ancestorOrSelfId + "']") == null); } xPath = this.XPath.Replace("$ancestorOrSelf", string.Concat("/descendant::*[@id='", ancestorOrSelfId, "']")); } XPathNavigator xPathNavigator = xmlDocument.CreateNavigator(); XPathNodeIterator xPathNodeIterator = xPathNavigator.Select(xPath); List <string> keys = new List <string>(); // used to keep track of keys, so that duplicates aren't added string key; string label; while (xPathNodeIterator.MoveNext()) { // media xml is wrapped in a <Media id="-1" /> node to be valid, exclude this from any results // member xml is wrapped in <Members id="-1" /> node to be valid, exclude this from any results if (xPathNodeIterator.CurrentPosition > 1 || !(xPathNodeIterator.Current.GetAttribute("id", string.Empty) == "-1" && (xPathNodeIterator.Current.Name == "Media" || xPathNodeIterator.Current.Name == "Members"))) { key = xPathNodeIterator.Current.SelectSingleNode(this.KeyXPath).Value; // only add item if it has a unique key - failsafe if (!string.IsNullOrWhiteSpace(key) && !keys.Any(x => x == key)) { // TODO: ensure key doens't contain any commas (keys are converted saved as csv) keys.Add(key); // add key so that it's not reused // set default markup to use the configured label XPath label = xPathNodeIterator.Current.SelectSingleNode(this.LabelXPath).Value; editorDataItems.Add(new EditorDataItem() { Key = key, Label = label }); } } } } return(editorDataItems); }
public void OnQueryResults(IDataObjectInputStream data, SIF_Error error, IZone zone, IMessageInfo info) { SifMessageInfo smi = (SifMessageInfo)info; DateTime start = DateTime.Now; if (smi.Timestamp.HasValue) { start = smi.Timestamp.Value; } Console.WriteLine(); Console.WriteLine( "********************************************* " ); Console.WriteLine( "Received SIF_Response packet from zone" + zone.ZoneId ); Console.WriteLine( "Details... " ); Console.WriteLine( "Request MsgId: " + smi.SIFRequestMsgId ); Console.WriteLine( "Packet Number: " + smi.PacketNumber ); Console.WriteLine(); if( error != null ){ Console.WriteLine( "The publisher returned an error: " ); Console.WriteLine( "Category: " + error.SIF_Category + " Code: " + error.SIF_Code ); Console.WriteLine( "Description " + error.SIF_Desc ); if( error.SIF_ExtendedDesc != null ) { Console.WriteLine( "Details: " + error.SIF_ExtendedDesc ); } return; } try { int objectCount = 0; while( data.Available ){ SifDataObject next = data.ReadDataObject(); objectCount++; Console.WriteLine(); Console.WriteLine( "Text Values for " + next.ElementDef.Name + " " + objectCount + " {" + next.Key + "}" ); SifXPathContext context = SifXPathContext.NewSIFContext(next); // Print out all attributes Console.WriteLine("Attributes:"); XPathNodeIterator textNodes = context.Select("//@*"); while( textNodes.MoveNext() ) { XPathNavigator navigator = textNodes.Current; Element value = (Element)navigator.UnderlyingObject; IElementDef valueDef = value.ElementDef; Console.WriteLine( valueDef.Parent.Tag( SifVersion.LATEST ) + "/@" + valueDef.Tag( SifVersion.LATEST ) + "=" + value.TextValue + ", " ); } Console.WriteLine(); // Print out all elements that have a text value Console.WriteLine("Element:"); textNodes = context.Select("//*"); while( textNodes.MoveNext() ) { XPathNavigator navigator = textNodes.Current; Element value = (Element)navigator.UnderlyingObject; String textValue = value.TextValue; if( textValue != null ){ IElementDef valueDef = value.ElementDef; Console.WriteLine( valueDef.Tag( SifVersion.LATEST ) + "=" + textValue + ", " ); } } } Console.WriteLine(); Console.WriteLine( "Total Objects in Packet: " + objectCount ); } catch( Exception ex ){ Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } if (!smi.MorePackets) { // This is the final packet. Print stats Console.WriteLine( "Final Packet has been received." ); IRequestInfo ri = smi.SIFRequestInfo; if( ri != null ){ Console.WriteLine( "Source Query: " ); Console.WriteLine( ri.UserData ); TimeSpan difference = start.Subtract(ri.RequestTime); Console.WriteLine( "Query execution time: " + difference.Milliseconds + " ms" ); } } else { Console.WriteLine( "This is not the final packet for this SIF_Response" ); } Console.WriteLine( "********************************************* " ); Console.WriteLine( ); PrintPrompt(); }
/// <summary> /// Helper extension method to load string data from XML node values into native types that aren't necessarily serializable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="navRoot"></param> /// <param name="name"></param> /// <returns></returns> internal static T ToValue <T>(this XPathNavigator navRoot, string name) { object item = null; var node = navRoot.SelectSingleNode(name); if (node != null) { item = node.Value; } if (typeof(T).Equals(typeof(string))) { return((T)item); } if (typeof(T).Equals(typeof(int))) { item = Convert.ToInt32(item); return((T)item); } if (typeof(T).Equals(typeof(long))) { item = Convert.ToInt64(item); return((T)item); } if (typeof(T).Equals(typeof(IntPtr))) { // The Convert must be big enough to convert a pointer from a x64 system. item = new IntPtr(Convert.ToInt64(item)); return((T)item); } if (typeof(T).Equals(typeof(double))) { item = Convert.ToDouble(item, CultureInfo.InvariantCulture); return((T)item); } if (typeof(T).Equals(typeof(DateTime))) { item = DateTime.Parse((string)item, null); return((T)item); } if (typeof(T).Equals(typeof(DateTimeOffset))) { item = DateTimeOffset.Parse((string)item, null); return((T)item); } if (typeof(T).Equals(typeof(bool))) { int result; if (Int32.TryParse((string)item, out result)) { item = Convert.ToBoolean(result); } else { item = Convert.ToBoolean((string)item); } return((T)item); } if (typeof(T).Equals(typeof(Guid))) { item = new Guid((string)item); return((T)item); } if (typeof(T).BaseType.Equals(typeof(Enum))) { item = Enum.Parse(typeof(T), (string)item); return((T)item); } if (typeof(T).Equals(typeof(CultureInfo))) { item = CultureInfo.GetCultureInfoByIetfLanguageTag((string)item); return((T)item); } if (typeof(T).Equals(typeof(Point3D))) { item = new Point3D(Convert.ToDouble(node.SelectSingleNode("X").Value, CultureInfo.InvariantCulture), Convert.ToDouble(node.SelectSingleNode("Y").Value, CultureInfo.InvariantCulture), Convert.ToDouble(node.SelectSingleNode("Z").Value, CultureInfo.InvariantCulture)); return((T)item); } //if (typeof(T).Equals(typeof(Rect))) //{ // item = new RectConverter().ConvertFromString((string)item); // return (T)item; //} throw new NotImplementedException(string.Format("The datatype [{0}] has not been catered for.", typeof(T).Name)); ////return (T)item; ////object ret = null; ////return (T)ret; }
public XmlExtractorNode(XPathNavigator node, XmlNamespaceManager nsman) { this.node = node; this.nsman = nsman; }
static string GetSignature(XPathNavigator nav) { return(GetAttribute(nav, "signature")); }
private string GetXNavDescr(XPathNavigator xnav, int level) { string indent = ""; for (int i = 0; i < level; i++) indent += " "; StringBuilder str = new StringBuilder(""); switch (xnav.NodeType) { case XPathNodeType.Root: str.Append("<b>ROOT</b>"); str.Append("<br>"); break; case XPathNodeType.Element: str.Append(indent); str.Append("Element: <b>"); str.Append(xnav.Name); str.Append("</b><br>"); break; case XPathNodeType.Text: str.Append(indent); str.Append(" - Value: <b>"); str.Append(xnav.Value); str.Append("</b><br>"); break; case XPathNodeType.Comment: str.Append(indent); str.Append("Comment: <b>"); str.Append(xnav.Value); str.Append("</b><br>"); break; } if (xnav.HasAttributes) { xnav.MoveToFirstAttribute(); do { str.Append(indent); str.Append(" - Attribute: <b>"); str.Append(xnav.Name); str.Append("</b> Value: <b>"); str.Append(xnav.Value); str.Append("</b><br>"); } while (xnav.MoveToNextAttribute()); // Return to the parent. xnav.MoveToParent(); } if (xnav.HasChildren) { xnav.MoveToFirstChild(); do { str.Append(GetXNavDescr(xnav, level + 1)); } while (xnav.MoveToNext()); // Return to the parent. xnav.MoveToParent(); } return str.ToString(); }
static string GetFullName(XPathNavigator nav) { return(GetAttribute(nav, "fullname")); }
public virtual void InsertBefore(XPathNavigator newSibling) { }
static string GetAttribute(XPathNavigator nav, string attribute) { return(nav.GetAttribute(attribute, string.Empty)); }
public virtual bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end) { }
/// <summary> /// This is overridden to allow use of an ESENT backed MSDN content ID cache /// </summary> /// <param name="configuration">The component configuration</param> /// <returns>An MSDN resolver instance</returns> protected override MsdnResolver CreateMsdnResolver(XPathNavigator configuration) { MsdnResolver resolver; IDictionary <string, string> cache = null; int localCacheSize; if (BuildComponentCore.Data.ContainsKey(SharedMsdnContentIdCacheId)) { cache = BuildComponentCore.Data[SharedMsdnContentIdCacheId] as IDictionary <string, string>; } // If the shared cache already exists, return an instance that uses it. It is assumed that all // subsequent instances will use the same cache. if (cache != null) { return(new MsdnResolver(cache, true)); } XPathNavigator node = configuration.SelectSingleNode("msdnContentIdCache"); // If an <msdnContentIdCache> element is not specified, use the default resolver if (node == null) { resolver = base.CreateMsdnResolver(configuration); } else { string msdnIdCachePath = node.GetAttribute("cachePath", String.Empty); // If a cache path is not defined, use the default resolver if (String.IsNullOrWhiteSpace(msdnIdCachePath)) { resolver = base.CreateMsdnResolver(configuration); } else { msdnIdCachePath = Path.GetFullPath(Environment.ExpandEnvironmentVariables(msdnIdCachePath)); string cacheSize = node.GetAttribute("localCacheSize", String.Empty); if (String.IsNullOrWhiteSpace(cacheSize) || !Int32.TryParse(cacheSize, out localCacheSize)) { localCacheSize = 2500; } // Load or create the cache database and the resolver. The resolver will dispose of the // dictionary when it is disposed of since it implements IDisposable. We won't compress the // columns as they're typically not that big and there aren't usually that many entries. // This gives a slight performance increase. resolver = new MsdnResolver(new PersistentDictionary <string, string>(msdnIdCachePath, false) { LocalCacheSize = localCacheSize }, false); // We own the cache and will report statistics when done ownsResolverCache = true; int cacheCount = resolver.MsdnContentIdCache.Count; if (cacheCount == 0) { // Log a diagnostic message since looking up all IDs can significantly slow the build base.WriteMessage(MessageLevel.Diagnostic, "The ESENT MSDN content ID cache in '" + msdnIdCachePath + "' does not exist yet. All IDs will be looked up in this build " + "which will slow it down."); } else { base.WriteMessage(MessageLevel.Info, "{0} cached MSDN content ID entries exist", cacheCount); } BuildComponentCore.Data[SharedMsdnContentIdCacheId] = resolver.MsdnContentIdCache; } } return(resolver); }
public virtual void ReplaceSelf(XPathNavigator newNode) { }
private ITaskConfiguration CreateTaskConfiguration(IComponentContext context, TaskTypeCatalog taskTypes, XPathNavigator taskNode) { string taskName = taskNode.GetAttribute("taskName", string.Empty); if (taskTypes.TaskNameToConfigType.ContainsKey(taskName)) //has a config class { //make the task configuration class, using the xml we're looking at return(context.ResolveNamed <ITaskConfiguration>(taskName + "Config", // using this service name new Parameter[] { new TypedParameter(typeof(string), taskNode.OuterXml) })); } return(null); }
public void OnField(XPathNavigator nav, FieldDefinition field) { MarkField(field); }
/// <summary> /// Write out property syntax /// </summary> /// <param name="reflection">An XPath navigator containing the member information</param> /// <param name="writer">The syntax writer to which the information is written</param> /// <param name="prefix">The web control prefix to use</param> private static void WritePropertySyntax(XPathNavigator reflection, SyntaxWriter writer, string prefix) { bool set = (bool)reflection.Evaluate(propertyIsSettable); if(!set) return; string name = (string)reflection.Evaluate(nameExpression); string declaringType = (string)reflection.Evaluate(declaringTypeExpression); string propertyType = (string)reflection.Evaluate(propertyTypeExpression); bool isInnerProperty = (bool)reflection.Evaluate(propertyIsInnerProperty); writer.WriteStartBlock(LanguageName, StyleIdName); if(isInnerProperty) { // inner property logic writer.WriteString("<"); writer.WriteString(prefix); writer.WriteString(":"); writer.WriteReferenceLink(declaringType); writer.WriteString(">"); writer.WriteLine(); writer.WriteString("\t"); writer.WriteString("<"); writer.WriteString(name); writer.WriteString(">"); if(String.IsNullOrEmpty(propertyType)) writer.WriteParameter("value"); else if(propertyType == "T:System.Boolean") writer.WriteString("True|False"); else writer.WriteReferenceLink(propertyType); writer.WriteString("</"); writer.WriteString(name); writer.WriteString(">"); writer.WriteLine(); writer.WriteString("</"); writer.WriteString(prefix); writer.WriteString(":"); writer.WriteReferenceLink(declaringType); writer.WriteString(">"); } else { // normal property logic writer.WriteString("<"); writer.WriteString(prefix); writer.WriteString(":"); writer.WriteReferenceLink(declaringType); writer.WriteString(" "); writer.WriteString(name); writer.WriteString("=\""); if(String.IsNullOrEmpty(propertyType)) writer.WriteParameter("value"); else if(propertyType == "T:System.Boolean") writer.WriteString("True|False"); else writer.WriteReferenceLink(propertyType); writer.WriteString("\" />"); } writer.WriteEndBlock(); }
private void UpdateFileFacade(FileFacade file) { var assemblyNameTuples = new Dictionary <string, MsiAssemblyNameTuple>(); foreach (var assemblyTuple in this.Section.Tuples.OfType <MsiAssemblyNameTuple>()) { assemblyNameTuples.Add(assemblyTuple.Component_ + "/" + assemblyTuple.Name, assemblyTuple); } FileInfo fileInfo = null; try { fileInfo = new FileInfo(file.WixFile.Source.Path); } catch (ArgumentException) { this.Messaging.Write(ErrorMessages.InvalidFileName(file.File.SourceLineNumbers, file.WixFile.Source.Path)); return; } catch (PathTooLongException) { this.Messaging.Write(ErrorMessages.InvalidFileName(file.File.SourceLineNumbers, file.WixFile.Source.Path)); return; } catch (NotSupportedException) { this.Messaging.Write(ErrorMessages.InvalidFileName(file.File.SourceLineNumbers, file.WixFile.Source.Path)); return; } if (!fileInfo.Exists) { this.Messaging.Write(ErrorMessages.CannotFindFile(file.File.SourceLineNumbers, file.File.File, file.File.LongFileName, file.WixFile.Source.Path)); return; } using (FileStream fileStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (Int32.MaxValue < fileStream.Length) { throw new WixException(ErrorMessages.FileTooLarge(file.File.SourceLineNumbers, file.WixFile.Source.Path)); } file.File.FileSize = Convert.ToInt32(fileStream.Length, CultureInfo.InvariantCulture); } string version = null; string language = null; try { Installer.GetFileVersion(fileInfo.FullName, out version, out language); } catch (Win32Exception e) { if (0x2 == e.NativeErrorCode) // ERROR_FILE_NOT_FOUND { throw new WixException(ErrorMessages.FileNotFound(file.File.SourceLineNumbers, fileInfo.FullName)); } else { throw new WixException(ErrorMessages.Win32Exception(e.NativeErrorCode, e.Message)); } } // If there is no version, it is assumed there is no language because it won't matter in the versioning of the install. if (String.IsNullOrEmpty(version)) // unversioned files have their hashes added to the MsiFileHash table { if (!this.OverwriteHash) { // not overwriting hash, so don't do the rest of these options. } else if (null != file.File.Version) { // Search all of the file rows available to see if the specified version is actually a companion file. Yes, this looks // very expensive and you're probably thinking it would be better to create an index of some sort to do an O(1) look up. // That's a reasonable thought but companion file usage is usually pretty rare so we'd be doing something expensive (indexing // all the file rows) for a relatively uncommon situation. Let's not do that. // // Also, if we do not find a matching file identifier then the user provided a default version and is providing a version // for unversioned file. That's allowed but generally a dangerous thing to do so let's point that out to the user. if (!this.FileFacades.Any(r => file.File.Version.Equals(r.File.File, StringComparison.Ordinal))) { this.Messaging.Write(WarningMessages.DefaultVersionUsedForUnversionedFile(file.File.SourceLineNumbers, file.File.Version, file.File.File)); } } else { if (null != file.File.Language) { this.Messaging.Write(WarningMessages.DefaultLanguageUsedForUnversionedFile(file.File.SourceLineNumbers, file.File.Language, file.File.File)); } int[] hash; try { Installer.GetFileHash(fileInfo.FullName, 0, out hash); } catch (Win32Exception e) { if (0x2 == e.NativeErrorCode) // ERROR_FILE_NOT_FOUND { throw new WixException(ErrorMessages.FileNotFound(file.File.SourceLineNumbers, fileInfo.FullName)); } else { throw new WixException(ErrorMessages.Win32Exception(e.NativeErrorCode, fileInfo.FullName, e.Message)); } } if (null == file.Hash) { file.Hash = new MsiFileHashTuple(file.File.SourceLineNumbers, file.File.Id); this.Section.Tuples.Add(file.Hash); } file.Hash.File_ = file.File.File; file.Hash.Options = 0; file.Hash.HashPart1 = hash[0]; file.Hash.HashPart2 = hash[1]; file.Hash.HashPart3 = hash[2]; file.Hash.HashPart4 = hash[3]; } } else // update the file row with the version and language information. { // If no version was provided by the user, use the version from the file itself. // This is the most common case. if (String.IsNullOrEmpty(file.File.Version)) { file.File.Version = version; } else if (!this.FileFacades.Any(r => file.File.Version.Equals(r.File.File, StringComparison.Ordinal))) // this looks expensive, but see explanation below. { // The user provided a default version for the file row so we looked for a companion file (a file row with Id matching // the version value). We didn't find it so, we will override the default version they provided with the actual // version from the file itself. Now, I know it looks expensive to search through all the file rows trying to match // on the Id. However, the alternative is to build a big index of all file rows to do look ups. Since this case // where the file version is already present is rare (companion files are pretty uncommon), we'll do the more // CPU intensive search to save on the memory intensive index that wouldn't be used much. // // Also note this case can occur when the file is being updated using the WixBindUpdatedFiles extension mechanism. // That's typically even more rare than companion files so again, no index, just search. file.File.Version = version; } if (!String.IsNullOrEmpty(file.File.Language) && String.IsNullOrEmpty(language)) { this.Messaging.Write(WarningMessages.DefaultLanguageUsedForVersionedFile(file.File.SourceLineNumbers, file.File.Language, file.File.File)); } else // override the default provided by the user (usually nothing) with the actual language from the file itself. { file.File.Language = language; } // Populate the binder variables for this file information if requested. if (null != this.VariableCache) { if (!String.IsNullOrEmpty(file.File.Version)) { var key = String.Format(CultureInfo.InvariantCulture, "fileversion.{0}", file.File.File); this.VariableCache[key] = file.File.Version; } if (!String.IsNullOrEmpty(file.File.Language)) { var key = String.Format(CultureInfo.InvariantCulture, "filelanguage.{0}", file.File.File); this.VariableCache[key] = file.File.Language; } } } // If this is a CLR assembly, load the assembly and get the assembly name information if (FileAssemblyType.DotNetAssembly == file.WixFile.AssemblyType) { bool targetNetfx1 = false; var assemblyNameValues = new Dictionary <string, string>(); Guid referenceIdentityGuid = ClrInterop.ReferenceIdentityGuid; var result = ClrInterop.GetAssemblyIdentityFromFile(fileInfo.FullName, ref referenceIdentityGuid, out var referenceIdentity); if (0 == result && null != referenceIdentity) { var imageRuntimeVersion = referenceIdentity.GetAttribute(null, "ImageRuntimeVersion"); if (null != imageRuntimeVersion) { targetNetfx1 = imageRuntimeVersion.StartsWith("v1", StringComparison.OrdinalIgnoreCase); } string culture = referenceIdentity.GetAttribute(null, "Culture") ?? "neutral"; assemblyNameValues.Add("Culture", culture); string name = referenceIdentity.GetAttribute(null, "Name"); if (null != name) { assemblyNameValues.Add("Name", name); } string processorArchitecture = referenceIdentity.GetAttribute(null, "ProcessorArchitecture"); if (null != processorArchitecture) { assemblyNameValues.Add("ProcessorArchitecture", processorArchitecture); } string publicKeyToken = referenceIdentity.GetAttribute(null, "PublicKeyToken"); if (null != publicKeyToken) { bool publicKeyIsNeutral = (String.Equals(publicKeyToken, "neutral", StringComparison.OrdinalIgnoreCase)); // Managed code expects "null" instead of "neutral", and // this won't be installed to the GAC since it's not signed anyway. assemblyNameValues.Add("publicKeyToken", publicKeyIsNeutral ? "null" : publicKeyToken.ToUpperInvariant()); assemblyNameValues.Add("publicKeyTokenPreservedCase", publicKeyIsNeutral ? "null" : publicKeyToken); } else if (file.WixFile.File_AssemblyApplication == null) { throw new WixException(ErrorMessages.GacAssemblyNoStrongName(file.File.SourceLineNumbers, fileInfo.FullName, file.File.Component_)); } string assemblyVersion = referenceIdentity.GetAttribute(null, "Version"); if (null != version) { assemblyNameValues.Add("Version", assemblyVersion); } } else { this.Messaging.Write(ErrorMessages.InvalidAssemblyFile(file.File.SourceLineNumbers, fileInfo.FullName, String.Format(CultureInfo.InvariantCulture, "HRESULT: 0x{0:x8}", result))); return; } if (assemblyNameValues.TryGetValue("name", out var value)) { this.SetMsiAssemblyName(assemblyNameTuples, file, "name", value); } if (!String.IsNullOrEmpty(version)) { this.SetMsiAssemblyName(assemblyNameTuples, file, "fileVersion", version); } if (assemblyNameValues.ContainsKey("version")) { string assemblyVersion = assemblyNameValues["version"]; if (!targetNetfx1) { // There is a bug in v1 fusion that requires the assembly's "version" attribute // to be equal to or longer than the "fileVersion" in length when its present; // the workaround is to prepend zeroes to the last version number in the assembly // version. if (null != version && version.Length > assemblyVersion.Length) { string padding = new string('0', version.Length - assemblyVersion.Length); string[] assemblyVersionNumbers = assemblyVersion.Split('.'); if (assemblyVersionNumbers.Length > 0) { assemblyVersionNumbers[assemblyVersionNumbers.Length - 1] = String.Concat(padding, assemblyVersionNumbers[assemblyVersionNumbers.Length - 1]); assemblyVersion = String.Join(".", assemblyVersionNumbers); } } } this.SetMsiAssemblyName(assemblyNameTuples, file, "version", assemblyVersion); } if (assemblyNameValues.ContainsKey("culture")) { this.SetMsiAssemblyName(assemblyNameTuples, file, "culture", assemblyNameValues["culture"]); } if (assemblyNameValues.ContainsKey("publicKeyToken")) { this.SetMsiAssemblyName(assemblyNameTuples, file, "publicKeyToken", assemblyNameValues["publicKeyToken"]); } if (!String.IsNullOrEmpty(file.WixFile.ProcessorArchitecture)) { this.SetMsiAssemblyName(assemblyNameTuples, file, "processorArchitecture", file.WixFile.ProcessorArchitecture); } if (assemblyNameValues.ContainsKey("processorArchitecture")) { this.SetMsiAssemblyName(assemblyNameTuples, file, "processorArchitecture", assemblyNameValues["processorArchitecture"]); } // add the assembly name to the information cache if (null != this.VariableCache) { string fileId = file.File.File; string key = String.Concat("assemblyfullname.", fileId); string assemblyName = String.Concat(assemblyNameValues["name"], ", version=", assemblyNameValues["version"], ", culture=", assemblyNameValues["culture"], ", publicKeyToken=", String.IsNullOrEmpty(assemblyNameValues["publicKeyToken"]) ? "null" : assemblyNameValues["publicKeyToken"]); if (assemblyNameValues.ContainsKey("processorArchitecture")) { assemblyName = String.Concat(assemblyName, ", processorArchitecture=", assemblyNameValues["processorArchitecture"]); } this.VariableCache[key] = assemblyName; // Add entries with the preserved case publicKeyToken string pcAssemblyNameKey = String.Concat("assemblyfullnamepreservedcase.", fileId); this.VariableCache[pcAssemblyNameKey] = (assemblyNameValues["publicKeyToken"] == assemblyNameValues["publicKeyTokenPreservedCase"]) ? assemblyName : assemblyName.Replace(assemblyNameValues["publicKeyToken"], assemblyNameValues["publicKeyTokenPreservedCase"]); string pcPublicKeyTokenKey = String.Concat("assemblypublickeytokenpreservedcase.", fileId); this.VariableCache[pcPublicKeyTokenKey] = assemblyNameValues["publicKeyTokenPreservedCase"]; } } else if (FileAssemblyType.Win32Assembly == file.WixFile.AssemblyType) { // TODO: Consider passing in the this.FileFacades as an indexed collection instead of searching through // all files like this. Even though this is a rare case it looks like we might be able to index the // file earlier. FileFacade fileManifest = this.FileFacades.SingleOrDefault(r => r.File.File.Equals(file.WixFile.File_AssemblyManifest, StringComparison.Ordinal)); if (null == fileManifest) { this.Messaging.Write(ErrorMessages.MissingManifestForWin32Assembly(file.File.SourceLineNumbers, file.File.File, file.WixFile.File_AssemblyManifest)); } string win32Type = null; string win32Name = null; string win32Version = null; string win32ProcessorArchitecture = null; string win32PublicKeyToken = null; // loading the dom is expensive we want more performant APIs than the DOM // Navigator is cheaper than dom. Perhaps there is a cheaper API still. try { XPathDocument doc = new XPathDocument(fileManifest.WixFile.Source.Path); XPathNavigator nav = doc.CreateNavigator(); nav.MoveToRoot(); // this assumes a particular schema for a win32 manifest and does not // provide error checking if the file does not conform to schema. // The fallback case here is that nothing is added to the MsiAssemblyName // table for an out of tolerance Win32 manifest. Perhaps warnings needed. if (nav.MoveToFirstChild()) { while (nav.NodeType != XPathNodeType.Element || nav.Name != "assembly") { nav.MoveToNext(); } if (nav.MoveToFirstChild()) { bool hasNextSibling = true; while (nav.NodeType != XPathNodeType.Element || nav.Name != "assemblyIdentity" && hasNextSibling) { hasNextSibling = nav.MoveToNext(); } if (!hasNextSibling) { this.Messaging.Write(ErrorMessages.InvalidManifestContent(file.File.SourceLineNumbers, fileManifest.WixFile.Source.Path)); return; } if (nav.MoveToAttribute("type", String.Empty)) { win32Type = nav.Value; nav.MoveToParent(); } if (nav.MoveToAttribute("name", String.Empty)) { win32Name = nav.Value; nav.MoveToParent(); } if (nav.MoveToAttribute("version", String.Empty)) { win32Version = nav.Value; nav.MoveToParent(); } if (nav.MoveToAttribute("processorArchitecture", String.Empty)) { win32ProcessorArchitecture = nav.Value; nav.MoveToParent(); } if (nav.MoveToAttribute("publicKeyToken", String.Empty)) { win32PublicKeyToken = nav.Value; nav.MoveToParent(); } } } } catch (FileNotFoundException fe) { this.Messaging.Write(ErrorMessages.FileNotFound(new SourceLineNumber(fileManifest.WixFile.Source.Path), fe.FileName, "AssemblyManifest")); } catch (XmlException xe) { this.Messaging.Write(ErrorMessages.InvalidXml(new SourceLineNumber(fileManifest.WixFile.Source.Path), "manifest", xe.Message)); } if (!String.IsNullOrEmpty(win32Name)) { this.SetMsiAssemblyName(assemblyNameTuples, file, "name", win32Name); } if (!String.IsNullOrEmpty(win32Version)) { this.SetMsiAssemblyName(assemblyNameTuples, file, "version", win32Version); } if (!String.IsNullOrEmpty(win32Type)) { this.SetMsiAssemblyName(assemblyNameTuples, file, "type", win32Type); } if (!String.IsNullOrEmpty(win32ProcessorArchitecture)) { this.SetMsiAssemblyName(assemblyNameTuples, file, "processorArchitecture", win32ProcessorArchitecture); } if (!String.IsNullOrEmpty(win32PublicKeyToken)) { this.SetMsiAssemblyName(assemblyNameTuples, file, "publicKeyToken", win32PublicKeyToken); } } }
//===================================================================== /// <summary> /// Initialize the syntax generator /// </summary> /// <param name="configuration">The syntax generator configuration</param> /// <remarks>This component has no configurable elements</remarks> public override void Initialize(XPathNavigator configuration) { }
public abstract bool PreserveWhitespace(XPathNavigator node);
private void SelectSpec_Load(object sender, EventArgs e) { using (new FetchSafelyFromPool <List <ListItem> >(Utils.ListItemListPool, out List <ListItem> lstItems)) { lstItems.Add(new ListItem("Custom", string.Empty)); if (_objCharacter.Created || !_objCharacter.EffectiveBuildMethodUsesPriorityTables) { chkKarma.Checked = true; chkKarma.Visible = false; } XPathNavigator xmlParentSkill; if (Mode == "Knowledge") { xmlParentSkill = _objXmlDocument.SelectSingleNode("/chummer/knowledgeskills/skill[name = " + _objSkill.Name.CleanXPath() + ']') ?? _objXmlDocument.SelectSingleNode( "/chummer/knowledgeskills/skill[translate = " + _objSkill.Name.CleanXPath() + ']'); } else { xmlParentSkill = _objXmlDocument.SelectSingleNode( "/chummer/skills/skill[name = " + _objSkill.Name.CleanXPath() + " and (" + _objCharacter.Settings.BookXPath() + ")]"); } // Populate the Skill's Specializations (if any). XPathNodeIterator xmlSpecList = xmlParentSkill?.SelectAndCacheExpression("specs/spec"); if (xmlSpecList?.Count > 0) { foreach (XPathNavigator objXmlSpecialization in xmlSpecList) { string strInnerText = objXmlSpecialization.Value; lstItems.Add(new ListItem(strInnerText, objXmlSpecialization.SelectSingleNodeAndCacheExpression("@translate") ?.Value ?? strInnerText)); if (_objSkill.SkillCategory != "Combat Active") { continue; } // Look through the Weapons file and grab the names of items that are part of the appropriate Category or use the matching Skill. XPathNavigator objXmlWeaponDocument = _objCharacter.LoadDataXPath("weapons.xml"); //Might need to include skill name or might miss some values? foreach (XPathNavigator objXmlWeapon in objXmlWeaponDocument.Select( "/chummer/weapons/weapon[(spec = " + strInnerText.CleanXPath() + " or spec2 = " + strInnerText.CleanXPath() + ") and (" + _objCharacter.Settings.BookXPath() + ")]")) { string strName = objXmlWeapon.SelectSingleNodeAndCacheExpression("name")?.Value; if (!string.IsNullOrEmpty(strName)) { lstItems.Add(new ListItem( strName, objXmlWeapon.SelectSingleNodeAndCacheExpression("translate")?.Value ?? strName)); } } } } // Populate the lists. cboSpec.BeginUpdate(); cboSpec.PopulateWithListItems(lstItems); // If there's only 1 value in the list, the character doesn't have a choice, so just accept it. if (cboSpec.Items.Count == 1 && cboSpec.DropDownStyle == ComboBoxStyle.DropDownList && AllowAutoSelect) { AcceptForm(); } if (!string.IsNullOrEmpty(_strForceItem)) { cboSpec.SelectedIndex = cboSpec.FindStringExact(_strForceItem); if (cboSpec.SelectedIndex != -1) { AcceptForm(); } else { cboSpec.PopulateWithListItems((new ListItem(_strForceItem, _strForceItem)).Yield()); cboSpec.SelectedIndex = 0; AcceptForm(); } } cboSpec.EndUpdate(); } }
/// <summary> /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class. /// </summary> /// <param name="documentPath">The physical path to XML document.</param> public XmlDocumentationProvider(string documentPath) { if (documentPath == null) { throw new ArgumentNullException("documentPath"); } XPathDocument xpath = new XPathDocument(documentPath); _documentNavigator = xpath.CreateNavigator(); }
public XmlCommentsParameterFilter(XPathDocument xmlDoc) { _xmlNavigator = xmlDoc.CreateNavigator(); }
public XmlCommentDocumentationProvider(string documentPath) { XPathDocument xpath = new XPathDocument(documentPath); _documentNavigator = xpath.CreateNavigator(); }
/// <summary> /// Method from XsltContext. /// </summary> public override bool PreserveWhitespace(XPathNavigator node) { return(true); }
public virtual System.Xml.XmlNodeOrder ComparePosition(XPathNavigator nav) { }
/// <summary> /// This method performs a string comparison. /// </summary> /// <param name="xsltContext">The Xslt context</param> /// <param name="args">The arguments of the function</param> /// <param name="docContext">The document context</param> /// <returns>A boolean value indicating whether the argument strings are identical</returns> public virtual object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return(ResolveNsPrefix(ResolveArgument(args[0]), xsltContext)?.Equals( ResolveNsPrefix(ResolveArgument(args[1]), xsltContext), StringComparison.Ordinal) ?? false); }
public virtual void InsertAfter(XPathNavigator newSibling) { }
/// <summary> /// This method performs a string comparison. /// </summary> /// <param name="xsltContext">The Xslt context</param> /// <param name="args">The arguments of the function</param> /// <param name="docContext">The document context</param> /// <returns>A boolean value indicating whether the argument strings are identical</returns> public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return((((string)args[1] + ResolveArgument(args[2]))).Equals( resolveNsPrefix(ResolveArgument(args[0]), (string)args[1], docContext), StringComparison.Ordinal)); }
public virtual bool IsDescendant(XPathNavigator nav) { }
public XmlCommentDocumentationProvider(string documentPath) { XPathDocument xpath = new XPathDocument(documentPath); _documentNavigator = xpath.CreateNavigator(); }
public abstract virtual bool MoveTo(XPathNavigator other) { }
public string GetDocumentation(Type type) { XPathNavigator typeNode = GetTypeNode(type); return GetTagValue(typeNode, "summary"); }
public virtual bool MoveToFollowing(XPathNodeType type, XPathNavigator end) { }
public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return(GetTagValue(methodNode, "summary")); }
public virtual System.Xml.XmlWriter ReplaceRange(XPathNavigator lastSiblingToReplace) { }
public void OnInterface(XPathNavigator nav, TypeDefinition type) { MarkType(type); }
/// <summary> /// Do work on the data /// </summary> /// <param name="table">The datatable to read and edit</param> /// <param name="nav">XPathNavigator for column info</param> /// <returns>true if the edit was successful</returns> public Boolean EditShowInfo(ref DataTable table, XPathNavigator nav) { Int32 updatedRowCount = 0; Boolean DEBUG = false; // Progress box progressForm = new Form(); progressForm.Size = new System.Drawing.Size(400, 100); progressForm.Text = "IMDb Movie Tagger"; progressForm.StartPosition = FormStartPosition.CenterScreen; Label progressLabel = new Label(); progressLabel.Size = new System.Drawing.Size(300, 50); progressForm.Controls.Add(progressLabel); progressForm.Show(); // HTTP vars HttpWebRequest webreq; HttpWebResponse webres; Stream resStream; string response; string indexToFind; int startindex; int endindex; Regex yearRegex; Match yearMatch; int count = 1; foreach (DataRow row in table.Rows) { // Movie variable names string imdbID = ""; string movieTitle = ""; string moviePlot = ""; string movieGenre = ""; string movieYear = ""; string movieDate = ""; string movieActors = ""; int discNum = 1; bool multidisc = false; bool isIMDB = false; Thread.Sleep(500); // Get the search URI for IMDb string name = row["Name"].ToString(); // Remove the extension name = name.Remove(name.LastIndexOf('.')).Trim(); // Remove some special characters for spacing name = name.Replace("_", " "); // See if it is a multi-part movie if (name.IndexOf("-Disc") > 0) { discNum = int.Parse(name.Substring(name.IndexOf("-Disc") + 5)); name = name.Remove(name.IndexOf("-Disc")).Trim(); multidisc = true; } else { discNum = 1; multidisc = false; } name = name.Replace(" ", "+"); string searchURI = ""; // Find out if the movie used the imdb ID or a title if (name.StartsWith("tt")) { isIMDB = true; imdbID = name; } else searchURI = "http://www.imdb.com/find?s=all&q=" + name + "&x=0&y=0"; if (DEBUG) { MessageBox.Show("Tagging: " + name); } progressLabel.Text = "Tagging " + count + "/" + table.Rows.Count + ": " + row["Name"].ToString(); // Get the IMDB ID using the title if (!isIMDB) { if (DEBUG) MessageBox.Show("Finding IMDb ID by Title"); try { int popResults = 0; int exactResults = 0; int partialResults = 0; int totalResults = 0; webres = null; try { webreq = (HttpWebRequest)WebRequest.Create(searchURI); webreq.Timeout = 10000; webreq.AllowAutoRedirect = true; webres = (HttpWebResponse)webreq.GetResponse(); } catch (Exception e) { MessageBox.Show(e.Message); continue; } resStream = webres.GetResponseStream(); response = new StreamReader(resStream).ReadToEnd(); // Is it a direct hit? string directHitLookup = "<link rel=\"canonical\" href=\"http://www.imdb.com/title/"; if (response.IndexOf(directHitLookup) != -1) { if (DEBUG) MessageBox.Show("Direct Hit"); startindex = response.IndexOf("imdb.com/title/") + 15; if (startindex < 1) { throw new Exception("Error Parsing for IMDb ID"); } imdbID = response.Substring(startindex, 9).Trim(); goto gotIMDBid; } // Find Popular Titles indexToFind = "<p><b>Popular Titles</b> (Displaying "; startindex = response.IndexOf(indexToFind) + indexToFind.Length; endindex = response.IndexOf("Result", startindex); if ((endindex - startindex > 20) || endindex - startindex < 1) { popResults = 0; } else popResults = int.Parse(response.Substring(startindex, endindex - startindex).Trim()); // Find Exact Title Matches indexToFind = "<p><b>Titles (Exact Matches)</b> (Displaying "; startindex = response.IndexOf(indexToFind) + indexToFind.Length; endindex = response.IndexOf("Result", startindex); if ((endindex - startindex > 20) || endindex - startindex < 1) { exactResults = 0; } else exactResults = int.Parse(response.Substring(startindex, endindex - startindex).Trim()); // Find Partial Title Matches indexToFind = "<p><b>Titles (Partial Matches)</b> (Displaying "; startindex = response.IndexOf(indexToFind) + indexToFind.Length; endindex = response.IndexOf("Result", startindex); if ((endindex - startindex > 20) || endindex - startindex < 1) { partialResults = 0; } else partialResults = int.Parse(response.Substring(startindex, endindex - startindex).Trim()); // Sum all the results totalResults = popResults + exactResults + partialResults; // Check if any items were found if (totalResults == 0) { // Ask user if they want to manually search for show name or skip DialogResult retval = MessageBox.Show("Nothing found. Search for show manually?", row["Name"].ToString(), MessageBoxButtons.YesNo); // If yes, get the new name if (retval == DialogResult.Yes) { Boolean searchError = false; Boolean tryAgain = true; // While the user wants to try, keep searching while (tryAgain) { // Get the new movie name and save name = Interaction.InputBox("Enter Movie Name or IMDb ID", row["Name"].ToString(), name, 0, 0); // Find out if the movie used the imdb ID or a title if (name.StartsWith("tt")) { isIMDB = true; imdbID = name; tryAgain = false; break; } else searchURI = "http://www.imdb.com/find?s=all&q=" + name + "&x=0&y=0"; webres = null; try { webreq = (HttpWebRequest)WebRequest.Create(searchURI); webreq.Timeout = 10000; webreq.AllowAutoRedirect = true; webres = (HttpWebResponse)webreq.GetResponse(); } catch (Exception e) { MessageBox.Show(e.Message); continue; } resStream = webres.GetResponseStream(); response = new StreamReader(resStream).ReadToEnd(); // Is it a direct hit? directHitLookup = "<link rel=\"canonical\" href=\"http://www.imdb.com/title/"; if (response.IndexOf(directHitLookup) != -1) { if (DEBUG) MessageBox.Show("Direct Hit"); startindex = response.IndexOf("imdb.com/title/") + 15; if (startindex < 1) { throw new Exception("Error Parsing for IMDb ID"); } imdbID = response.Substring(startindex, 9).Trim(); goto gotIMDBid; } // Find Popular Titles indexToFind = "<p><b>Popular Titles</b> (Displaying "; startindex = response.IndexOf(indexToFind) + indexToFind.Length; endindex = response.IndexOf("Result", startindex); if ((endindex - startindex > 20) || endindex - startindex < 1) { popResults = 0; } else popResults = int.Parse(response.Substring(startindex, endindex - startindex).Trim()); // Find Exact Title Matches indexToFind = "<p><b>Titles (Exact Matches)</b> (Displaying "; startindex = response.IndexOf(indexToFind) + indexToFind.Length; endindex = response.IndexOf("Result", startindex); if ((endindex - startindex > 20) || endindex - startindex < 1) { exactResults = 0; } else exactResults = int.Parse(response.Substring(startindex, endindex - startindex).Trim()); // Find Partial Title Matches indexToFind = "<p><b>Titles (Partial Matches)</b> (Displaying "; startindex = response.IndexOf(indexToFind) + indexToFind.Length; endindex = response.IndexOf("Result", startindex); if ((endindex - startindex > 20) || endindex - startindex < 1) { partialResults = 0; } else partialResults = int.Parse(response.Substring(startindex, endindex - startindex).Trim()); // Sum all the results totalResults = popResults + exactResults + partialResults; if (totalResults == 0) { // Nothing found, try again? retval = MessageBox.Show("Nothing found. Try again?", row["Name"].ToString(), MessageBoxButtons.YesNo); if (retval == DialogResult.No) { searchError = true; break; } } else if (totalResults >= 1) { if (DEBUG) MessageBox.Show("Found Results"); string[] titles = new string[totalResults + 1]; string[] years = new string[totalResults + 1]; string[] imdbIDs = new string[totalResults + 1]; // Get all popular results, getting ID and title if (popResults > 0) { // Start at the proper section string popResponse = response.Substring(response.IndexOf("<p><b>Popular Titles</b> (Displaying ")); for (int i = 1; i <= popResults; i++) { string nextTitle = i.ToString() + ".</td>"; int titleindex = popResponse.IndexOf(nextTitle); string responseFromTitle = popResponse.Substring(titleindex); int imdbIDstartindex = responseFromTitle.IndexOf("title/") + 6; int imdbIDendindex = responseFromTitle.IndexOf("/\" onclick"); if (imdbIDendindex - imdbIDstartindex < 1) { throw new Exception("Error Parsing for IMDb ID"); } imdbIDs[i] = responseFromTitle.Substring(imdbIDstartindex, imdbIDendindex - imdbIDstartindex).Trim(); string titleStart = imdbIDs[i] + "/';\">"; int titlestartindex = responseFromTitle.IndexOf(titleStart) + titleStart.Length; int titleendindex = responseFromTitle.IndexOf("</a>"); if (titleendindex - titlestartindex < 1) { throw new Exception("Error Parsing Title"); } titles[i] = responseFromTitle.Substring(titlestartindex, titleendindex - titlestartindex).Trim(); titles[i] = replaceSpecialChars(titles[i]); // Find the year yearRegex = new Regex("[0-9]{4}", RegexOptions.IgnoreCase); yearMatch = yearRegex.Match(responseFromTitle.Substring(titlestartindex, 200)); // Check if this search worked if (yearMatch.Success) years[i] = yearMatch.ToString().Trim(); else years[i] = ""; if (DEBUG) MessageBox.Show("Search Result: " + titles[i]); } } // Get all exact title results, getting ID and title if (exactResults > 0) { // Start at the proper section string exactResponse = response.Substring(response.IndexOf("<p><b>Titles (Exact Matches)</b> (Displaying ")); for (int i = 1; i <= exactResults; i++) { string nextTitle = i.ToString() + ".</td>"; int titleindex = exactResponse.IndexOf(nextTitle); string responseFromTitle = exactResponse.Substring(titleindex); int imdbIDstartindex = responseFromTitle.IndexOf("title/") + 6; int imdbIDendindex = responseFromTitle.IndexOf("/\" onclick"); if (imdbIDendindex - imdbIDstartindex < 1) { throw new Exception("Error Parsing for IMDb ID"); } imdbIDs[i + popResults] = responseFromTitle.Substring(imdbIDstartindex, imdbIDendindex - imdbIDstartindex).Trim(); string titleStart = imdbIDs[i + popResults] + "/';\">"; int titlestartindex = responseFromTitle.IndexOf(titleStart) + titleStart.Length; int titleendindex = responseFromTitle.IndexOf("</a>"); if (titleendindex - titlestartindex < 1) { throw new Exception("Error Parsing Title"); } titles[i + popResults] = responseFromTitle.Substring(titlestartindex, titleendindex - titlestartindex).Trim(); titles[i + popResults] = replaceSpecialChars(titles[i + popResults]); // Find the year yearRegex = new Regex("[0-9]{4}", RegexOptions.IgnoreCase); yearMatch = yearRegex.Match(responseFromTitle.Substring(titlestartindex, 200)); // Check if this search worked if (yearMatch.Success) years[i + popResults] = yearMatch.ToString().Trim(); else years[i + popResults] = ""; if (DEBUG) MessageBox.Show("Search Result: " + titles[i + popResults]); } } // Get all partial title results, getting ID and title if (partialResults > 0) { // Start at the proper section string partialResponse = response.Substring(response.IndexOf("<p><b>Titles (Partial Matches)</b> (Displaying ")); for (int i = 1; i <= partialResults; i++) { string nextTitle = i.ToString() + ".</td>"; int titleindex = partialResponse.IndexOf(nextTitle); string responseFromTitle = partialResponse.Substring(titleindex); int imdbIDstartindex = responseFromTitle.IndexOf("title/") + 6; int imdbIDendindex = responseFromTitle.IndexOf("/\" onclick"); if (imdbIDendindex - imdbIDstartindex < 1) { throw new Exception("Error Parsing for IMDb ID"); } imdbIDs[i + popResults + exactResults] = responseFromTitle.Substring(imdbIDstartindex, imdbIDendindex - imdbIDstartindex).Trim(); string titleStart = imdbIDs[i + popResults + exactResults] + "/';\">"; int titlestartindex = responseFromTitle.IndexOf(titleStart) + titleStart.Length; int titleendindex = responseFromTitle.IndexOf("</a>"); if (titleendindex - titlestartindex < 1) { throw new Exception("Error Parsing Title"); } titles[i + popResults + exactResults] = responseFromTitle.Substring(titlestartindex, titleendindex - titlestartindex).Trim(); titles[i + popResults + exactResults] = replaceSpecialChars(titles[i + popResults + exactResults]); // Find the year yearRegex = new Regex("[0-9]{4}", RegexOptions.IgnoreCase); yearMatch = yearRegex.Match(responseFromTitle.Substring(titlestartindex, 200)); // Check if this search worked if (yearMatch.Success) years[i + popResults + exactResults] = yearMatch.ToString().Trim(); else years[i + popResults + exactResults] = ""; if (DEBUG) MessageBox.Show("Search Result: " + titles[i + popResults + exactResults]); } } if (totalResults > 1) { // Found multiple shows, ask the user which one it is if (DEBUG) MessageBox.Show("Found " + totalResults.ToString() + " result(s)"); // Show a form with a combo box with the series available ComboBox comboBox = new ComboBox(); comboBox.Location = new System.Drawing.Point(10, 40); comboBox.Size = new System.Drawing.Size(180, 150); for (int i = 1; i < titles.Length; i++) { string comboLabel = titles[i].ToString() + " (" + years[i].ToString() + ")"; comboBox.Items.Add(comboLabel); } comboBox.SelectedIndex = 0; multipleListingsForm = new Form(); multipleListingsForm.Text = "Select Movie Name"; multipleListingsForm.Size = new System.Drawing.Size(200, 140); multipleListingsForm.Controls.Add(comboBox); Button selectButton = new Button(); Button skipButton = new Button(); selectButton.Text = "Select"; selectButton.Click += new System.EventHandler(this.selectButton_Click); selectButton.Location = new System.Drawing.Point(10, 70); selectButton.Size = new System.Drawing.Size(80, 30); skipButton.Text = "Skip"; skipButton.Click += new System.EventHandler(this.skipButton_Click); skipButton.Location = new System.Drawing.Point(80, 70); skipButton.Size = new System.Drawing.Size(80, 30); Label label = new Label(); label.Text = row["Name"].ToString(); label.Location = new System.Drawing.Point(10, 10); label.Size = new System.Drawing.Size(180, 30); multipleListingsForm.Controls.Add(label); multipleListingsForm.Controls.Add(selectButton); multipleListingsForm.Controls.Add(skipButton); multipleListingsForm.StartPosition = FormStartPosition.CenterScreen; multipleListingsForm.ShowDialog(); multipleListingsForm.Dispose(); // Check if a movie was selected or skipped if (DEBUG) MessageBox.Show("Selected item: " + comboBox.SelectedIndex); int movieIndex = comboBox.SelectedIndex + 1; if (!isSkip) { // Set the series name to the selected item movieTitle = titles[movieIndex]; imdbID = imdbIDs[movieIndex]; tryAgain = false; break; } else { tryAgain = false; searchError = true; continue; } } else { if (DEBUG) MessageBox.Show("Found Only One Result"); imdbID = imdbIDs[1]; movieTitle = titles[1]; tryAgain = false; break; } } else { searchError = false; } } // If there was an error in the manual search, skip if (searchError) continue; } else { continue; } } // Results found else if (totalResults >= 1) { if (DEBUG) MessageBox.Show("Found Results"); string[] titles = new string[totalResults + 1]; string[] years = new string[totalResults + 1]; string[] imdbIDs = new string[totalResults + 1]; // Get all popular results, getting ID and title if (popResults > 0) { // Start at the proper section string popResponse = response.Substring(response.IndexOf("<p><b>Popular Titles</b> (Displaying ")); for (int i = 1; i <= popResults; i++) { string nextTitle = i.ToString() + ".</td>"; int titleindex = popResponse.IndexOf(nextTitle); string responseFromTitle = popResponse.Substring(titleindex); int imdbIDstartindex = responseFromTitle.IndexOf("title/") + 6; int imdbIDendindex = responseFromTitle.IndexOf("/\" onclick"); if (imdbIDendindex - imdbIDstartindex < 1) { throw new Exception("Error Parsing for IMDb ID"); } imdbIDs[i] = responseFromTitle.Substring(imdbIDstartindex, imdbIDendindex - imdbIDstartindex).Trim(); string titleStart = imdbIDs[i] + "/';\">"; int titlestartindex = responseFromTitle.IndexOf(titleStart) + titleStart.Length; int titleendindex = responseFromTitle.IndexOf("</a>"); if (titleendindex - titlestartindex < 1) { throw new Exception("Error Parsing Title"); } titles[i] = responseFromTitle.Substring(titlestartindex, titleendindex - titlestartindex).Trim(); titles[i] = replaceSpecialChars(titles[i]); // Find the year yearRegex = new Regex("[0-9]{4}", RegexOptions.IgnoreCase); yearMatch = yearRegex.Match(responseFromTitle.Substring(titlestartindex, 200)); // Check if this search worked if (yearMatch.Success) years[i] = yearMatch.ToString().Trim(); else years[i] = ""; if (DEBUG) MessageBox.Show("Search Result: " + titles[i]); } } // Get all exact title results, getting ID and title if (exactResults > 0) { // Start at the proper section string exactResponse = response.Substring(response.IndexOf("<p><b>Titles (Exact Matches)</b> (Displaying ")); for (int i = 1; i <= exactResults; i++) { string nextTitle = i.ToString() + ".</td>"; int titleindex = exactResponse.IndexOf(nextTitle); string responseFromTitle = exactResponse.Substring(titleindex); int imdbIDstartindex = responseFromTitle.IndexOf("title/") + 6; int imdbIDendindex = responseFromTitle.IndexOf("/\" onclick"); if (imdbIDendindex - imdbIDstartindex < 1) { throw new Exception("Error Parsing for IMDb ID"); } imdbIDs[i + popResults] = responseFromTitle.Substring(imdbIDstartindex, imdbIDendindex - imdbIDstartindex).Trim(); string titleStart = imdbIDs[i + popResults] + "/';\">"; int titlestartindex = responseFromTitle.IndexOf(titleStart) + titleStart.Length; int titleendindex = responseFromTitle.IndexOf("</a>"); if (titleendindex - titlestartindex < 1) { throw new Exception("Error Parsing Title"); } titles[i + popResults] = responseFromTitle.Substring(titlestartindex, titleendindex - titlestartindex).Trim(); titles[i + popResults] = replaceSpecialChars(titles[i + popResults]); // Find the year yearRegex = new Regex("[0-9]{4}", RegexOptions.IgnoreCase); yearMatch = yearRegex.Match(responseFromTitle.Substring(titlestartindex, 200)); // Check if this search worked if (yearMatch.Success) years[i + popResults] = yearMatch.ToString().Trim(); else years[i + popResults] = ""; if (DEBUG) MessageBox.Show("Search Result: " + titles[i + popResults]); } } // Get all partial title results, getting ID and title if (partialResults > 0) { // Start at the proper section string partialResponse = response.Substring(response.IndexOf("<p><b>Titles (Partial Matches)</b> (Displaying ")); for (int i = 1; i <= partialResults; i++) { string nextTitle = i.ToString() + ".</td>"; int titleindex = partialResponse.IndexOf(nextTitle); string responseFromTitle = partialResponse.Substring(titleindex); int imdbIDstartindex = responseFromTitle.IndexOf("title/") + 6; int imdbIDendindex = responseFromTitle.IndexOf("/\" onclick"); if (imdbIDendindex - imdbIDstartindex < 1) { throw new Exception("Error Parsing for IMDb ID"); } imdbIDs[i + popResults + exactResults] = responseFromTitle.Substring(imdbIDstartindex, imdbIDendindex - imdbIDstartindex).Trim(); string titleStart = imdbIDs[i + popResults + exactResults] + "/';\">"; int titlestartindex = responseFromTitle.IndexOf(titleStart) + titleStart.Length; int titleendindex = responseFromTitle.IndexOf("</a>"); if (titleendindex - titlestartindex < 1) { throw new Exception("Error Parsing Title"); } titles[i + popResults + exactResults] = responseFromTitle.Substring(titlestartindex, titleendindex - titlestartindex).Trim(); titles[i + popResults + exactResults] = replaceSpecialChars(titles[i + popResults + exactResults]); // Find the year yearRegex = new Regex("[0-9]{4}", RegexOptions.IgnoreCase); yearMatch = yearRegex.Match(responseFromTitle.Substring(titlestartindex, 200)); // Check if this search worked if (yearMatch.Success) years[i + popResults + exactResults] = yearMatch.ToString().Trim(); else years[i + popResults + exactResults] = ""; if (DEBUG) MessageBox.Show("Search Result: " + titles[i + popResults + exactResults]); } } if (totalResults > 1) { // Found multiple shows, ask the user which one it is if (DEBUG) MessageBox.Show("Found " + totalResults.ToString() + " result(s)"); // Show a form with a combo box with the series available ComboBox comboBox = new ComboBox(); comboBox.Location = new System.Drawing.Point(10, 40); comboBox.Size = new System.Drawing.Size(180, 150); for (int i = 1; i < titles.Length; i++) { string comboLabel = titles[i].ToString() + " (" + years[i].ToString() + ")"; comboBox.Items.Add(comboLabel); } comboBox.SelectedIndex = 0; multipleListingsForm = new Form(); multipleListingsForm.Text = "Select Movie Name"; multipleListingsForm.Size = new System.Drawing.Size(200, 140); multipleListingsForm.Controls.Add(comboBox); Button selectButton = new Button(); Button skipButton = new Button(); selectButton.Text = "Select"; selectButton.Click += new System.EventHandler(this.selectButton_Click); selectButton.Location = new System.Drawing.Point(10, 70); selectButton.Size = new System.Drawing.Size(80, 30); skipButton.Text = "Skip"; skipButton.Click += new System.EventHandler(this.skipButton_Click); skipButton.Location = new System.Drawing.Point(80, 70); skipButton.Size = new System.Drawing.Size(80, 30); Label label = new Label(); label.Text = row["Name"].ToString(); label.Location = new System.Drawing.Point(10, 10); label.Size = new System.Drawing.Size(180, 30); multipleListingsForm.Controls.Add(label); multipleListingsForm.Controls.Add(selectButton); multipleListingsForm.Controls.Add(skipButton); multipleListingsForm.StartPosition = FormStartPosition.CenterScreen; multipleListingsForm.ShowDialog(); multipleListingsForm.Dispose(); // Check if a movie was selected or skipped if (DEBUG) MessageBox.Show("Selected item: " + comboBox.SelectedIndex); int movieIndex = comboBox.SelectedIndex + 1; if (!isSkip) { // Set the series name to the selected item movieTitle = titles[movieIndex]; imdbID = imdbIDs[movieIndex]; } else continue; } else { if (DEBUG) MessageBox.Show("Found Only One Result"); imdbID = imdbIDs[1]; movieTitle = titles[1]; } if (DEBUG) MessageBox.Show("Found: " + movieTitle + " with ID: " + imdbID); } else { throw new Exception("Unknown Error"); } } catch (Exception e) { MessageBox.Show("Error: " + e.Message); continue; } gotIMDBid: if (imdbID == "") continue; } // At this point, we have the IMDb ID if (DEBUG) MessageBox.Show("Using IMDb ID: " + imdbID); // Now get movie info searchURI = "http://www.imdb.com/title/" + imdbID + "/"; webres = null; try { webreq = (HttpWebRequest)WebRequest.Create(searchURI); webreq.Timeout = 10000; webreq.AllowAutoRedirect = true; webres = (HttpWebResponse)webreq.GetResponse(); } catch (Exception e) { MessageBox.Show(e.Message); continue; } resStream = webres.GetResponseStream(); response = new StreamReader(resStream).ReadToEnd(); // Find the title indexToFind = "<title>"; startindex = response.IndexOf(indexToFind) + indexToFind.Length; endindex = response.IndexOf("(", startindex); if (endindex - startindex < 1) { throw new Exception("Error Parsing Title"); } movieTitle = replaceSpecialChars(response.Substring(startindex, endindex - startindex)); // Find the year yearRegex = new Regex("[0-9]{4}", RegexOptions.IgnoreCase); yearMatch = yearRegex.Match(response.Substring(startindex, 200)); // Check if this search worked if (yearMatch.Success) { movieYear = yearMatch.ToString().Trim(); } else { //throw new Exception("Error Parsing Year"); // Get the year from the user movieYear = Interaction.InputBox("No Year Found. Enter Movie Year", movieTitle, null, 0, 0); } // Find the plot indexToFind = "Plot:</h5>"; startindex = response.IndexOf(indexToFind) + indexToFind.Length + 1 + 27; endindex = response.IndexOf("<a", startindex); if (endindex - startindex < 1 || endindex - startindex > 2000) { //throw new Exception("Error Parsing Plot"); // Get the plot from the user moviePlot = Interaction.InputBox("No Plot Found. Enter Movie Plot", movieTitle, null, 0, 0); } else { moviePlot = replaceSpecialChars(response.Substring(startindex, endindex - startindex)); } if (multidisc) moviePlot = "Disc " + discNum + ": " + moviePlot; // Find the genre indexToFind = "Genre:</h5>"; startindex = response.IndexOf(indexToFind) + 27; string subresp = response.Substring(startindex, 1000); startindex = subresp.IndexOf("/\">") + 3; endindex = subresp.IndexOf("</a>", startindex); if (endindex - startindex < 1 || endindex - startindex > 50) { //throw new Exception("Error Parsing Genre"); // Get the genre from the user movieGenre = Interaction.InputBox("No Genre Found. Enter Movie Genre", movieTitle, null, 0, 0); } else movieGenre = subresp.Substring(startindex, endindex - startindex); // Find the actors indexToFind = "Cast</h3>"; startindex = response.IndexOf(indexToFind); if (startindex != -1) { subresp = response.Substring(startindex, 10000); movieActors = ""; int loops = 0; while (loops <= 80) { // Get next name startindex = subresp.IndexOf("link=/name"); if (DEBUG) MessageBox.Show("sIndex: " + startindex); // Found nothing, enter manually if (startindex == -1) { if (loops == 0) movieActors = Interaction.InputBox("No Actors Found. Enter Movie Actors", movieTitle, null, 0, 0); break; } else { subresp = subresp.Substring(startindex + 10); endindex = subresp.IndexOf("</a>"); if (endindex == -1) break; // Find an actor, not the link if (endindex < 75) { // Found Character Name if (DEBUG) MessageBox.Show("Found a name"); movieActors = movieActors + subresp.Substring(15, endindex - 15) + ", "; } } loops++; } // Trim off the last comma if (movieActors.LastIndexOf(',') != -1) movieActors = movieActors.Remove(movieActors.LastIndexOf(',')).Trim(); //MessageBox.Show(movieActors); } else movieActors = ""; // Find the date indexToFind = "Date:</h5>"; startindex = response.IndexOf(indexToFind) + indexToFind.Length + 1 + 27; endindex = response.IndexOf("(", startindex); if (endindex - startindex < 1 || endindex - startindex > 50) { //throw new Exception("Error Parsing Date"); movieDate = movieYear + "-01-01"; } else { string date = response.Substring(startindex, endindex - startindex); string[] dateParts = date.Split(' '); string month = "January"; string day = "01"; if (dateParts.Length == 2) { // Only Year movieDate = movieYear; } else if (dateParts.Length == 3) { // Month and Year month = dateParts[0].Trim(); } else if (dateParts.Length == 4) { // Day Month Year // Adjust length of day if (dateParts[0].Trim().Length == 1) day = "0" + dateParts[0].Trim(); month = dateParts[1].Trim(); } else { throw new Exception("Error Forming Date"); } movieDate = movieYear; // Lookup Month if (month.Equals("January")) movieDate = movieDate + "-01-" + day; else if (month.Equals("February")) movieDate = movieDate + "-02-" + day; else if (month.Equals("March")) movieDate = movieDate + "-03-" + day; else if (month.Equals("April")) movieDate = movieDate + "-04-" + day; else if (month.Equals("May")) movieDate = movieDate + "-05-" + day; else if (month.Equals("June")) movieDate = movieDate + "-06-" + day; else if (month.Equals("July")) movieDate = movieDate + "-07-" + day; else if (month.Equals("August")) movieDate = movieDate + "-08-" + day; else if (month.Equals("September")) movieDate = movieDate + "-09-" + day; else if (month.Equals("October")) movieDate = movieDate + "-10-" + day; else if (month.Equals("November")) movieDate = movieDate + "-11-" + day; else if (month.Equals("December")) movieDate = movieDate + "-12-" + day; else throw new Exception("Error Forming Date"); } // Set title as Movies for now. This needs to be fixed so DisplayTitle gets set // to "Movies" and Title get set to the movie name. row["Title"] = "Movies"; // Set Episode Name as the movie if (movieTitle.IndexOf("The") == 0) movieTitle = movieTitle.Substring(4).Trim() + ", The"; if (movieTitle.IndexOf("A ") == 0) movieTitle = movieTitle.Substring(2).Trim() + ", A"; if (movieTitle.IndexOf("An ") == 0) movieTitle = movieTitle.Substring(3).Trim() + ", An"; row["EpisodeTitle"] = movieTitle; // Set the Description row["EpisodeDescription"] = moviePlot; // Set the Genre row["Genre"] = movieGenre; // Set the Actors row["Actors"] = movieActors; // Set the Date //string firstAired = "2099-01-01"; row["ActualStart"] = movieDate; row["OriginalAirDate"] = movieDate.Replace("-", ""); row["MovieYear"] = movieYear; updatedRowCount++; count++; Thread.Sleep(500); progressForm.Update(); } progressForm.Close(); return (updatedRowCount > 0); }
public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); return(GetTagValue(typeNode, "summary")); }
public void OnMethod(XPathNavigator nav, MethodDefinition method) { MarkMethod(method); }
/// <summary> /// Do work on the data /// </summary> /// <param name="table">The datatable to read and edit</param> /// <param name="nav">XPathNavigator for column info</param> /// <returns>true if the edit was successful</returns> public Boolean EditShowInfo( ref DataTable table, XPathNavigator nav ) { Int32 updatedRowCount = 0; Boolean DEBUG = false; // List to save the Series names and ID List<string> seriesNameList = new List<string>(); List<string> formalNameList = new List<string>(); List<string> seriesIDList = new List<string>(); XmlTextReader reader; XmlDocument doc; string URLString; Boolean isTagged; progressForm = new Form(); progressForm.Size = new System.Drawing.Size(400, 100); progressForm.Text = "TheTVDb.com Tagger"; progressForm.StartPosition = FormStartPosition.CenterScreen; Label progressLabel = new Label(); progressLabel.Size = new System.Drawing.Size(300, 50); progressForm.Controls.Add(progressLabel); progressForm.Show(); int count = 0; foreach ( DataRow row in table.Rows ) { count++; Thread.Sleep(500); // Parse filename to get Series name Tagger tagger = new Tagger(); // Set variables string seriesID; string formalName; bool isBTVshow = false; if (DEBUG) MessageBox.Show("Tagging: " + row["Name"].ToString()); // See if it is a native BTV Recording double num; bool isNum = double.TryParse(row["Channel"].ToString().Trim(), out num); if (isNum) { if (DEBUG) MessageBox.Show("BTV Native Recording"); isBTVshow = true; tagger.seriesName = row["Title"].ToString(); tagger.originalAirDate = row["OriginalAirDate"].ToString().Insert(6, "-").Insert(4, "-"); tagger.seasonNumber = "0"; tagger.episodeNumber = "0"; isTagged = true; } else { if (DEBUG) MessageBox.Show("Not a BTV Native Recording"); // Parse the filename isTagged = tagger.tagFilename(row["Name"].ToString()); } // Check if the tagging worked, otherwise, continue to the next item if (!isTagged) { // Could not parse filename // Ask user if they want to manually enter the show info DialogResult retval = MessageBox.Show("Could not parse " + row["Name"].ToString() + "\nManually enter show info?", row["Name"].ToString(), MessageBoxButtons.YesNo); if (retval == DialogResult.Yes) { // Get the info manually tagger.seriesName = Interaction.InputBox("Enter Series Name", row["Name"].ToString(), null, 0, 0); tagger.seasonNumber = Interaction.InputBox("Enter Season Number", row["Name"].ToString(), null, 0, 0); tagger.episodeNumber = Interaction.InputBox("Enter Episode Number", row["Name"].ToString(), null, 0, 0); // Check if the cancel button was hit or if it was empty if (tagger.seriesName.Length == 0 || tagger.seasonNumber.Length == 0 || tagger.episodeNumber.Length == 0) continue; } else { continue; } } progressLabel.Text = "Tagging " + count + "/" + table.Rows.Count + ": " + row["Name"].ToString(); if (DEBUG) { MessageBox.Show("Title: " + tagger.seriesName); MessageBox.Show("Season: " + tagger.seasonNumber); MessageBox.Show("Episode: " + tagger.episodeNumber); } // Check array first int indexOfShowInArray = seriesNameList.IndexOf(tagger.seriesName); if (indexOfShowInArray != -1) { if (DEBUG) MessageBox.Show(tagger.seriesName + " exists in memory"); formalName = formalNameList[indexOfShowInArray]; seriesID = seriesIDList[indexOfShowInArray]; } else { // Search theTVDB.com API for the series ID URLString = "http://www.thetvdb.com/api/GetSeries.php?seriesname=" + tagger.seriesName + "&language=en"; reader = new XmlTextReader(URLString); doc = new XmlDocument(); try { doc.Load(reader); } catch (Exception e) { MessageBox.Show("Bad URL: " + URLString + "\nSkipping.", row["Name"].ToString()); continue; } reader.Close(); // Get the series name and the index in the XML if there are multiple XmlNodeList seriesNamesList = doc.GetElementsByTagName("SeriesName"); int seriesCount = seriesNamesList.Count; int seriesIndex = 0; // Check if any items were found if (seriesCount == 0) { formalName = ""; // Nothing found // Ask user if they want to manually search for show name or skip DialogResult retval = MessageBox.Show("Nothing found. Search for show manually?", row["Name"].ToString(), MessageBoxButtons.YesNo); if (retval == DialogResult.Yes) { Boolean searchError = false; Boolean tryAgain = true; // While the user wants to try, keep searching while (tryAgain) { // Get the new series name and save string newSeriesName = Interaction.InputBox("Enter Series Name", row["Name"].ToString(), null, 0, 0); // Search theTVDB.com API for the series ID URLString = "http://www.thetvdb.com/api/GetSeries.php?seriesname=" + newSeriesName + "&language=en"; reader = new XmlTextReader(URLString); doc = new XmlDocument(); try { doc.Load(reader); } catch (Exception e) { MessageBox.Show("Bad URL: " + URLString + "\nSkipping.", row["Name"].ToString()); searchError = true; break; } reader.Close(); // Get the series name and the index in the XML if there are multiple seriesNamesList = doc.GetElementsByTagName("SeriesName"); seriesCount = seriesNamesList.Count; seriesIndex = 0; // Check if any items were found this time if (seriesCount == 0) { // Nothing found, try again? retval = MessageBox.Show("Nothing found. Try again?", row["Name"].ToString(), MessageBoxButtons.YesNo); if (retval == DialogResult.No) { searchError = true; break; } } else if (seriesCount == 1) { // Only one show found, so assume this is it if (DEBUG) MessageBox.Show("Found: " + seriesNamesList.Item(0).InnerText); formalName = seriesNamesList.Item(0).InnerText; tryAgain = false; } else { // Found multiple shows, ask the user which one it is if (DEBUG) MessageBox.Show("Found multiple results"); // Show a form with a combo box with the series available ComboBox comboBox = new ComboBox(); comboBox.Location = new System.Drawing.Point(10, 40); comboBox.Size = new System.Drawing.Size(180, 150); for (int i = 0; i < seriesNamesList.Count; i++) { //Console.WriteLine((i + 1).ToString() + " :" + seriesNamesList.Item(i).InnerText); comboBox.Items.Add(seriesNamesList.Item(i).InnerText); } comboBox.SelectedIndex = 0; multipleListingsForm = new Form(); multipleListingsForm.Text = "Select Series Name"; multipleListingsForm.Size = new System.Drawing.Size(200, 140); multipleListingsForm.Controls.Add(comboBox); Button selectButton = new Button(); Button skipButton = new Button(); selectButton.Text = "Select"; selectButton.Click += new System.EventHandler(this.selectButton_Click); selectButton.Location = new System.Drawing.Point(10, 70); selectButton.Size = new System.Drawing.Size(80, 30); skipButton.Text = "Skip"; skipButton.Click += new System.EventHandler(this.skipButton_Click); skipButton.Location = new System.Drawing.Point(80, 70); skipButton.Size = new System.Drawing.Size(80, 30); Label label = new Label(); label.Text = row["Name"].ToString(); label.Location = new System.Drawing.Point(10, 10); label.Size = new System.Drawing.Size(180, 30); multipleListingsForm.Controls.Add(label); multipleListingsForm.Controls.Add(selectButton); multipleListingsForm.Controls.Add(skipButton); multipleListingsForm.StartPosition = FormStartPosition.CenterScreen; multipleListingsForm.ShowDialog(); multipleListingsForm.Dispose(); // Check if a series was selected or skipped seriesIndex = comboBox.SelectedIndex; if (!isSkip) { // Set the series name to the selected item formalName = seriesNamesList.Item(seriesIndex).InnerText; tryAgain = false; } else // Skip search searchError = true; break; } } // If there was an error in the manual search, skip if (searchError) continue; } else { continue; } } else if (seriesCount == 1) { // Only one show found, so assume this is it if (DEBUG) MessageBox.Show("Found: " + seriesNamesList.Item(0).InnerText); formalName = seriesNamesList.Item(0).InnerText; } else { // Found multiple shows, ask the user which one it is if (DEBUG) MessageBox.Show("Found multiple results"); // Show a form with a combo box with the series available ComboBox comboBox = new ComboBox(); comboBox.Location = new System.Drawing.Point(10, 40); comboBox.Size = new System.Drawing.Size(180, 150); for (int i = 0; i < seriesNamesList.Count; i++) { //Console.WriteLine((i + 1).ToString() + " :" + seriesNamesList.Item(i).InnerText); comboBox.Items.Add(seriesNamesList.Item(i).InnerText); } comboBox.SelectedIndex = 0; multipleListingsForm = new Form(); multipleListingsForm.Text = "Select Series Name"; multipleListingsForm.Size = new System.Drawing.Size(200, 140); multipleListingsForm.Controls.Add(comboBox); Button selectButton = new Button(); Button skipButton = new Button(); selectButton.Text = "Select"; selectButton.Click += new System.EventHandler(this.selectButton_Click); selectButton.Location = new System.Drawing.Point(10, 70); selectButton.Size = new System.Drawing.Size(80, 30); skipButton.Text = "Skip"; skipButton.Click += new System.EventHandler(this.skipButton_Click); skipButton.Location = new System.Drawing.Point(80, 70); skipButton.Size = new System.Drawing.Size(80, 30); Label label = new Label(); label.Text = row["Name"].ToString(); label.Location = new System.Drawing.Point(10, 10); label.Size = new System.Drawing.Size(180, 30); multipleListingsForm.Controls.Add(label); multipleListingsForm.Controls.Add(selectButton); multipleListingsForm.Controls.Add(skipButton); multipleListingsForm.StartPosition = FormStartPosition.CenterScreen; multipleListingsForm.ShowDialog(); multipleListingsForm.Dispose(); // Check if a series was selected or skipped seriesIndex = comboBox.SelectedIndex; if (!isSkip) { // Set the series name to the selected item formalName = seriesNamesList.Item(seriesIndex).InnerText; } else // Skip search continue; } // Get series ID from the XML XmlNodeList seriesIDXMLList = doc.GetElementsByTagName("seriesid"); seriesID = seriesIDXMLList.Item(seriesIndex).InnerText; if (DEBUG) MessageBox.Show("Using " + tagger.seriesName + " with TVDB_ID: " + seriesID); // Store tagged name and series ID seriesNameList.Add(tagger.seriesName); formalNameList.Add(formalName); seriesIDList.Add(seriesID); } // Should have the Series name at this point // // First check if BTV Recorded Show and get the details if (isBTVshow) { URLString = "http://www.thetvdb.com/api/8DB53EF83E7E8308/series/" + seriesID + "/all/en.xml"; if (DEBUG) MessageBox.Show("URL: " + URLString); reader = new XmlTextReader(URLString); doc = new XmlDocument(); try { doc.Load(reader); } catch (Exception e) { MessageBox.Show("Bad URL: " + URLString + "\nSkipping.", row["Name"].ToString()); continue; } reader.Close(); // Get the episode list XmlNodeList episodeList = doc.GetElementsByTagName("Episode"); int episodeCount = episodeList.Count; if (DEBUG) MessageBox.Show("Found " + episodeCount.ToString() + " episode(s)"); // Go through each episode and find if the original air date exists string[] seasonSearch = new string[10]; string[] episodeSearch = new string[10]; string[] episodeNameSearch = new string[10]; int dateMatches = 0; for (int i = 0; i < episodeCount; i++) { string dateSearch = episodeList.Item(i).SelectSingleNode("FirstAired").InnerText.ToString(); if (dateSearch == tagger.originalAirDate) { seasonSearch[dateMatches] = episodeList.Item(i).SelectSingleNode("SeasonNumber").InnerText.ToString(); episodeSearch[dateMatches] = episodeList.Item(i).SelectSingleNode("EpisodeNumber").InnerText.ToString(); episodeNameSearch[dateMatches] = episodeList.Item(i).SelectSingleNode("EpisodeName").InnerText.ToString(); if (DEBUG) { MessageBox.Show("Found match to original air date: " + episodeNameSearch[dateMatches] + " S" + seasonSearch[dateMatches] + "E" + episodeSearch[dateMatches]); } dateMatches++; } } if (DEBUG) MessageBox.Show("Found " + dateMatches.ToString() + " matches"); // Found no matches if (dateMatches <= 0) { DialogResult retval = MessageBox.Show("No match found for " + row["Name"].ToString() + " on " + tagger.originalAirDate + "\nManually enter show season and episode info?", row["Name"].ToString(), MessageBoxButtons.YesNo); if (retval == DialogResult.Yes) { // Get the info manually tagger.seasonNumber = Interaction.InputBox("Enter Season Number", row["Name"].ToString(), null, 0, 0); tagger.episodeNumber = Interaction.InputBox("Enter Episode Number", row["Name"].ToString(), null, 0, 0); // Check if the cancel button was hit or if it was empty if (tagger.seasonNumber.Length == 0 || tagger.episodeNumber.Length == 0) continue; } else { continue; } } // Found one match else if (dateMatches == 1) { tagger.seasonNumber = seasonSearch[0]; tagger.episodeNumber = episodeSearch[0]; } // Found multiple matches, ask user else { // Show a form with a combo box with the episodes available ComboBox comboBox = new ComboBox(); comboBox.Location = new System.Drawing.Point(10, 40); comboBox.Size = new System.Drawing.Size(180, 150); for (int i = 0; i < dateMatches; i++) { comboBox.Items.Add("Season: " + seasonSearch[i] + ", Episode: " + episodeSearch[i] + ", " + episodeNameSearch[i]); } comboBox.SelectedIndex = 0; multipleListingsForm = new Form(); multipleListingsForm.Text = "Select Episode"; multipleListingsForm.Size = new System.Drawing.Size(200, 140); multipleListingsForm.Controls.Add(comboBox); Button selectButton = new Button(); Button skipButton = new Button(); selectButton.Text = "Select"; selectButton.Click += new System.EventHandler(this.selectButton_Click); selectButton.Location = new System.Drawing.Point(10, 70); selectButton.Size = new System.Drawing.Size(80, 30); skipButton.Text = "Skip"; skipButton.Click += new System.EventHandler(this.skipButton_Click); skipButton.Location = new System.Drawing.Point(80, 70); skipButton.Size = new System.Drawing.Size(80, 30); Label label = new Label(); label.Text = row["Name"].ToString(); label.Location = new System.Drawing.Point(10, 10); label.Size = new System.Drawing.Size(180, 30); multipleListingsForm.Controls.Add(label); multipleListingsForm.Controls.Add(selectButton); multipleListingsForm.Controls.Add(skipButton); multipleListingsForm.StartPosition = FormStartPosition.CenterScreen; multipleListingsForm.ShowDialog(); multipleListingsForm.Dispose(); // Check if a series was selected or skipped int episodeIndex = comboBox.SelectedIndex; if (!isSkip) { // Set the series name to the selected item tagger.seasonNumber = seasonSearch[episodeIndex]; tagger.episodeNumber = episodeSearch[episodeIndex]; } else // Skip search continue; } } // Get episode info from TheTVDB.com API URLString = "http://www.thetvdb.com/api/8DB53EF83E7E8308/series/" + seriesID + "/default/" + tagger.seasonNumber + "/" + tagger.episodeNumber + "/en.xml"; if (DEBUG) MessageBox.Show("URL: " + URLString); reader = new XmlTextReader(URLString); doc = new XmlDocument(); try { doc.Load(reader); } catch (Exception e) { MessageBox.Show("Bad URL: " + URLString + "\nSkipping.", row["Name"].ToString()); continue; } reader.Close(); // Set series name row["Title"] = formalName; // Set Episode Name string episodeName = doc.GetElementsByTagName("EpisodeName").Item(0).InnerText; row["EpisodeTitle"] = episodeName; if (DEBUG) MessageBox.Show("Episode Name: " + episodeName); // Set Episode Date string firstAired = doc.GetElementsByTagName("FirstAired").Item(0).InnerText; row["ActualStart"] = firstAired; row["OriginalAirDate"] = firstAired.Replace("-", ""); if (DEBUG) MessageBox.Show("Episode Aired: " + firstAired); // Set Episode Overview string overview = doc.GetElementsByTagName("Overview").Item(0).InnerText; if (DEBUG) MessageBox.Show("Overview: " + overview); // Append Series and Episode number to the beginning if (tagger.seasonNumber.Length == 1 && tagger.episodeNumber.Length == 1) overview = "S0" + tagger.seasonNumber + "E0" + tagger.episodeNumber + " - " + overview; else if (tagger.seasonNumber.Length == 1 && tagger.episodeNumber.Length == 2) overview = "S0" + tagger.seasonNumber + "E" + tagger.episodeNumber + " - " + overview; else if (tagger.seasonNumber.Length == 2 && tagger.episodeNumber.Length == 1) overview = "S" + tagger.seasonNumber + "E0" + tagger.episodeNumber + " - " + overview; else overview = "S" + tagger.seasonNumber + "E" + tagger.episodeNumber + " - " + overview; row["EpisodeDescription"] = overview; updatedRowCount++; Thread.Sleep(500); progressForm.Update(); } progressForm.Close(); return ( updatedRowCount > 0 ); }
public static XmlNamespaceManager GetXmlNameSpaceManager(XPathNavigator xpn) { xpn.MoveToFollowing(XPathNodeType.Element); XmlNamespaceManager xmlnsm = new XmlNamespaceManager(xpn.NameTable); xmlnsm.AddNamespace("x", xpn.NamespaceURI); foreach (KeyValuePair<string, string> xns in xpn.GetNamespacesInScope(XmlNamespaceScope.All)) xmlnsm.AddNamespace(xns.Key, xns.Value); return xmlnsm; }
public void OnProperty(XPathNavigator nav, PropertyDefinition property) { }
public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return(GetTagValue(methodNode, "returns")); }
public static BundleInfo ParseBundleFromStream(Stream stream) { XPathDocument manifest = new XPathDocument(stream); XPathNavigator root = manifest.CreateNavigator(); return ParseBundleFromXml(root); }