internal static XmlReaderSettings CreateDefaultXmlReaderSettings() { var nameTable = new NameTable(); // load predifined namespace to nametable for (int i = 1; i < NamespaceIdMap.Count; i++) { nameTable.Add(NamespaceIdMap.GetNamespaceUri((byte)i)); } nameTable.Add(xmlnsUri); return(new XmlReaderSettings { #if FEATURE_XML_PROHIBIT_DTD ProhibitDtd = true, #else DtdProcessing = DtdProcessing.Prohibit, #endif NameTable = new NameTable(), // Set IgnoreWhitespace to false for the SDK to handle the whitespace node type. We have to do this because // PPT does not use the preserve attribute (xml:space="preserve") for non-ignorable whitespaces. IgnoreWhitespace = false }); }
/// <summary> /// Initializes a new instance of the <see cref="DynamicContext"/> class. /// </summary> /// <param name="context">A previously filled context with the namespaces to use.</param> /// <param name="table">The NameTable to use.</param> public DynamicContext(XmlNamespaceManager context, NameTable table) : base(table) { object xml = table.Add(XmlNamespaces.Xml); object xmlns = table.Add(XmlNamespaces.XmlNs); if (context == null) { return; } foreach (string prefix in context) { var uri = context.LookupNamespace(prefix); // Use fast object reference comparison to omit forbidden namespace declarations. if (Equals(uri, xml) || Equals(uri, xmlns)) { continue; } if (uri == null) { continue; } base.AddNamespace(prefix, uri); } }
public static void Main() { //<snippet1> NameTable nt = new NameTable(); object book = nt.Add("book"); object price = nt.Add("price"); // Create the reader. XmlReaderSettings settings = new XmlReaderSettings(); settings.NameTable = nt; XmlReader reader = XmlReader.Create("books.xml", settings); reader.MoveToContent(); reader.ReadToDescendant("book"); if (System.Object.ReferenceEquals(book, reader.Name)) { // Do additional processing. } //</snippet1> //Close the reader. reader.Close(); }
private static XmlNameTable CreateNameTable() { XmlNameTable nameTable = new NameTable(); nameTable.Add(string.Empty); nameTable.Add(xmlnsPrefixNamespace); nameTable.Add(xmlPrefixNamespace); return(nameTable); }
static XmlNameTable CreateNameTable() { var nameTable = new NameTable(); nameTable.Add(String.Empty); nameTable.Add("http://www.w3.org/2000/xmlns/"); nameTable.Add("http://www.w3.org/XML/1998/namespace"); return(nameTable); }
private void ReadSimulationFile(string FileName) { XmlDocument XMLDoc = new XmlDocument(); NameTable nt = new NameTable(); object DiagramFile = nt.Add("DiagramFileName"); object ParameterFile = nt.Add("ParameterFileName"); object InputDirectory = nt.Add("InputDirectoryPath"); object OutputDirectory = nt.Add("OutputDirectoryPath"); object FrameCount = nt.Add("FrameCount"); // Create a reader that uses the NameTable. XmlReaderSettings settings = new XmlReaderSettings(); settings.NameTable = nt; settings.ConformanceLevel = ConformanceLevel.Fragment; using (StreamReader StreamReader = new StreamReader(FileName)) { // Create the XmlParserContext. XmlParserContext context = new XmlParserContext(nt, null, null, XmlSpace.None); XmlReader reader = XmlReader.Create(StreamReader, settings, context); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { // Cache the local name to prevent multiple calls to the LocalName property. object localname = reader.LocalName; if (DiagramFile == localname) { this.DiagramFile = reader.ReadString(); } if (ParameterFile == localname) { this.ParameterFile = reader.ReadString(); } if (InputDirectory == localname) { this.InputDirectory = reader.ReadString(); } if (OutputDirectory == localname) { this.OutputDirectory = reader.ReadString(); } if (FrameCount == localname) { this.FrameCount = int.Parse(reader.ReadString()); } } } // End While // Close the reader. reader.Close(); } // end Using }
public JsonXPathNavigator(JsonReader reader) { reader.DateParseHandling = DateParseHandling.None; reader.FloatParseHandling = FloatParseHandling.Decimal; try { var docChild = (JObject)JObject.Load(reader); // Add symbolic 'root' child, so initially, we are at a virtual "root" element, just like in the DOM model var root = new JProperty(ROOT_PROP_NAME, docChild); _state.Push(new NavigatorState(root)); } catch (Exception e) { throw new FormatException("Cannot parse json: " + e.Message); } _nameTable.Add(XmlNs.FHIR); _nameTable.Add(XmlNs.XHTML); _nameTable.Add(XmlNs.NAMESPACE); _nameTable.Add(String.Empty); _nameTable.Add(FHIR_PREFIX); _nameTable.Add(XML_PREFIX); _nameTable.Add(XHTML_PREFIX); _nameTable.Add(SPEC_CHILD_VALUE); }
} //SetCredentials /// <summary> /// Parses XML namespace declaration. /// </summary> /// <param name="arg">Namespace declaration</param> private void ParseNamespaceDeclaration(string arg) { if (arg.EndsWith("=")) { throw new NXsltCommandLineParsingException(NXsltStrings.ErrorMissingURI, arg.Remove(arg.Length - 1, 1)); } int eqIndex = arg.IndexOf('='); //Lazy XmlNamespaceManager if (namespaceManager == null) { nameTable = new NameTable(); namespaceManager = new XmlNamespaceManager(nameTable); } //qname is xmlns:prefix or xmlns string qname = arg.Substring(0, eqIndex); int colonIndex = qname.IndexOf(':'); if (colonIndex != -1) { //xmlns:prefix="value" case namespaceManager.AddNamespace(nameTable.Add(qname.Substring(colonIndex + 1)), arg.Substring(eqIndex + 1)); } else { //xmlns="value" case - default namespace namespaceManager.AddNamespace(String.Empty, arg.Substring(eqIndex + 1)); } }// ParseNamespaceDeclaration
private void Init() { _nsManager = reader.NamespaceManager !; if (_nsManager == null) { _nsManager = new XmlNamespaceManager(NameTable); _bManageNamespaces = true; } _validationStack = new HWStack(STACK_INCREMENT); textValue = new StringBuilder(); _attPresence = new Hashtable(); schemaInfo = new SchemaInfo(); checkDatatype = false; _processContents = XmlSchemaContentProcessing.Strict; Push(XmlQualifiedName.Empty); //Add common strings to be compared to NameTable _nsXmlNs = NameTable.Add(XmlReservedNs.NsXmlNs); _nsXs = NameTable.Add(XmlReservedNs.NsXs); _nsXsi = NameTable.Add(XmlReservedNs.NsXsi); _xsiType = NameTable.Add("type"); _xsiNil = NameTable.Add("nil"); _xsiSchemaLocation = NameTable.Add("schemaLocation"); _xsiNoNamespaceSchemaLocation = NameTable.Add("noNamespaceSchemaLocation"); _xsdSchema = NameTable.Add("schema"); }
private string MakeFirstUpper(string name) { // Don't process empty strings. if (name.Length == 0) { return(name); } // If the first is already upper, don't process. if (char.IsUpper(name[0])) { return(name); } // If there's just one char, make it lower directly. if (name.Length == 1) { return(name.ToUpper(System.Globalization.CultureInfo.CurrentCulture)); } // Finally, modify and create a string. char[] letters = name.ToCharArray(); letters[0] = char.ToUpper(letters[0], System.Globalization.CultureInfo.CurrentUICulture); return(NameTable.Add(new string(letters))); }
static void SplitXmlDocumentUsingXmlReader(string xmlFilename) { using (StreamReader fileStream = new StreamReader(xmlFilename)) { XmlReaderSettings xmlSettings = new XmlReaderSettings(); xmlSettings.ConformanceLevel = ConformanceLevel.Fragment; xmlSettings.DtdProcessing = DtdProcessing.Parse; xmlSettings.IgnoreWhitespace = true; xmlSettings.IgnoreComments = false; NameTable nameTableReader = new NameTable(); nameTableReader.Add(_defaultNamespace); xmlSettings.NameTable = nameTableReader; using (XmlReader xmlReader = XmlReader.Create(fileStream, xmlSettings)) { XmlDocument xmlDocument = new XmlDocument(); try { xmlReader.MoveToContent(); // xmlReader.MoveToElement(); xmlReader.Read(); xmlDocument.Load(xmlReader); } catch (Exception ex) { Console.WriteLine("SplitXmlDocumentUsingXmlReader({0}) : Exception \"{1}\" = {2}", xmlFilename, ex.Message, ex.ToString()); } } // using XmlReader } // using StreamReader } // SplitXmlDocumentUsingXmlReader
public void main() { string[] results = new string[6]; int resultCount = 0; XmlReaderSettings settings = new XmlReaderSettings(); NameTable nt = new NameTable(); object value = nt.Add("value"); settings.NameTable = nt; settings.IgnoreWhitespace = true; settings.IgnoreComments = true; string file = @"C:\Documents and Settings\dg014133\Desktop\desktop\respirations\RespirationsComment\RespirationsComment\bin\Release\normalSeveritrDiag.xml"; using (XmlReader reader = XmlReader.Create(file, settings)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && value.Equals(reader.LocalName)) { results[resultCount] = (string)reader.ReadElementContentAsString(); resultCount++; } } foreach (string str in results) { System.Console.WriteLine(str); } } }
private XmlSchema Add(string ns, SchemaInfo schemaInfo, XmlSchema schema, bool compile, XmlResolver resolver) { int errorCount = 0; if (schema != null) { if (schema.ErrorCount == 0 && compile) { if (!schema.CompileSchema(this, resolver, schemaInfo, ns, _validationEventHandler, _nameTable, true)) { errorCount = 1; } ns = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace; } errorCount += schema.ErrorCount; } else { errorCount += schemaInfo.ErrorCount; //ns = ns == null? string.Empty : NameTable.Add(ns); ns = NameTable.Add(ns); //Added without checking for ns == null, since XDR cannot have null namespace } if (errorCount == 0) { XmlSchemaCollectionNode node = new XmlSchemaCollectionNode(); node.NamespaceURI = ns; node.SchemaInfo = schemaInfo; node.Schema = schema; Add(ns, node); return(schema); } return(null); }
private static void GeometryGmlWriterTest(Action <GeometryPipeline> pipelineCalls, params string[] expectedXPaths) { var ms = new MemoryStream(); var w = XmlWriter.Create(ms, new XmlWriterSettings { Indent = false }); DrawBoth gw = new GmlWriter(w); gw.GeometryPipeline.SetCoordinateSystem(CoordinateSystem.DefaultGeometry); pipelineCalls(gw.GeometryPipeline); w.Flush(); w.Close(); // use XElement to validate basic XML integrity ms.Seek(0, SeekOrigin.Begin); XmlNameTable nt = new NameTable(); nt.Add(GmlConstants.GmlPrefix); // XPath or string contains var xnm = new XmlNamespaceManager(nt); xnm.AddNamespace(GmlConstants.GmlPrefix, GmlConstants.GmlNamespace); var xDoc = new XmlDocument(nt); xDoc.Load(ms); var nav = xDoc.CreateNavigator(); SpatialTestUtils.VerifyXPaths(nav, xnm, "/node()[@gml:srsName = '" + GmlConstants.SrsPrefix + CoordinateSystem.DefaultGeometry.EpsgId + "']"); SpatialTestUtils.VerifyXPaths(nav, xnm, expectedXPaths); }
private async Task readNameTable(Action <DomainLoadProgress> progress) { DomainLoadProgress message = new DomainLoadProgress { Text = "Reading Name Table...", Current = 0, Total = NameTableCount }; reader.Seek(NameTableOffset); for (int i = 0; i < NameTableCount; ++i) { DomainNameTableEntry name = new DomainNameTableEntry { TableIndex = i }; await name.ReadNameTableEntry(reader); NameTable.Add(name); message.IncrementCurrent(); if (NameTableCount > 100) { progress?.Invoke(message); } } }
internal XmlSchema Add(string ns, SchemaInfo schemaInfo, XmlSchema schema, bool compile) { int errorCount = 0; if (schema != null) { if (schema.ErrorCount == 0 && compile) { schema.Compile(this, nameTable, schemaNames, validationEventHandler, ns, schemaInfo, true); ns = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace; } errorCount += schema.ErrorCount; } else { errorCount += schemaInfo.ErrorCount; ns = NameTable.Add(ns); } if (errorCount == 0) { XmlSchemaCollectionNode node = new XmlSchemaCollectionNode(); node.NamespaceURI = ns; node.SchemaInfo = schemaInfo; node.Schema = schema; Add(ns, node); return(schema); } return(null); }
/// <summary> /// Сериализация объекта /// </summary> /// <param name="person"> /// Объект пакета /// </param> /// <param name="tableName"> /// Корневой тег /// </param> /// <param name="settings"> /// Настройки записи xml /// </param> /// /// /// <returns> /// The <see cref="FileStream"/>. /// </returns> public static MemoryStream SerializeToMemoryStream( object person, string tableName, XmlWriterSettings settings = null) { var nt = new NameTable(); nt.Add(tableName); var nameres = GetNamespaces(nt); var stream = new MemoryStream(); { using (var writer = new XmlTextWriter(stream, Encoding.Default)) { var serializer = GetSerializer(person); var namespaces = XmlHelper.ResolveNamespacesForSerializer(nameres); if (namespaces != null) { writer.Formatting = Formatting.Indented; serializer.Serialize(settings != null ? XmlWriter.Create(writer, settings) : writer, person, namespaces); } else { serializer.Serialize(settings != null ? XmlWriter.Create(writer, settings) : writer, person); } } } return(stream); }
private static T Deserialize <T>(string path) where T : class { XmlNameTable table = new NameTable(); table.Add(" http://www.opengis.net/kml/2.2"); table.Add("urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"); table.Add("http://www.w3.org/2005/Atom"); XmlSerializer serializer = new XmlSerializer(typeof(T)); T obj; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { obj = serializer.Deserialize(new XmlTextReader(fs, table)) as T; } return(obj); }
public FeatureEntry(string id, string status_id, string name_enu, string status_enu, string comments_enu, string name_fra, string status_fra, string comments_fra) { int.TryParse(id, out int IdInt); Id = IdInt; int.TryParse(status_id, out int StatusInt); StatusId = StatusInt; string EnglishName = Language.ReplaceHtml(name_enu); NameTable.Add(LanguageStates.English, EnglishName); string EnglishStatus = Language.ReplaceHtml(status_enu); StatusTable.Add(LanguageStates.English, EnglishStatus); string EnglishComments = Language.ReplaceHtml(comments_enu); CommentsTable.Add(LanguageStates.English, EnglishComments); string FrenchName = Language.ReplaceHtml(name_fra); NameTable.Add(LanguageStates.French, FrenchName); string FrenchStatus = Language.ReplaceHtml(status_fra); StatusTable.Add(LanguageStates.French, FrenchStatus); string FrenchComments = Language.ReplaceHtml(comments_fra); CommentsTable.Add(LanguageStates.French, FrenchComments); }
/// <summary> /// Analyze attribute constructor. /// </summary> private void AnalyzeAttributeCtor(QilBinary ndAttr, XmlILConstructInfo info) { if (ndAttr.Left.NodeType == QilNodeType.LiteralQName) { QilName?ndName = ndAttr.Left as QilName; Debug.Assert(ndName != null); XmlQualifiedName qname; int idx; // This attribute might be constructed on the parent element this.parentInfo !.MightHaveAttributes = true; // Check to see whether this attribute is a duplicate of a previous attribute if (!this.parentInfo.MightHaveDuplicateAttributes) { qname = new XmlQualifiedName(_attrNames.Add(ndName.LocalName), _attrNames.Add(ndName.NamespaceUri)); for (idx = 0; idx < _dupAttrs.Count; idx++) { XmlQualifiedName qnameDup = (XmlQualifiedName)_dupAttrs[idx] !; if ((object)qnameDup.Name == (object)qname.Name && (object)qnameDup.Namespace == (object)qname.Namespace) { // A duplicate attribute has been encountered this.parentInfo.MightHaveDuplicateAttributes = true; } } if (idx >= _dupAttrs.Count) { // This is not a duplicate attribute, so add it to the set _dupAttrs.Add(qname); } } // The attribute's namespace might need to be declared if (!info.IsNamespaceInScope) { this.parentInfo.MightHaveNamespaces = true; } } else { // Attribute prefix and namespace are not known at compile-time CheckAttributeNamespaceConstruct(ndAttr.XmlType !); } }
/// <summary>See <see cref="XmlReader.this[string, string]"/></summary> public override string this[string name, string namespaceURI] { get { return(base[ NameTable.Add(XmlFirstLowerWriter.MakeFirstLower(name)), namespaceURI]); } }
public static void FixReferralSpam(string path) { string bad = ConfigurationManager.AppSettings["badWords"]; long badWordsCount = 0; long totalBadWordsCount = 0; DirectoryInfo info = new DirectoryInfo("../../"); ReferralBlackListFactory.AddBlacklist(new MovableTypeBlacklist(), Path.Combine(info.FullName, "blacklist.txt")); if (bad != null && bad.Length > 0) { ReferralBlackListFactory.AddBlacklist(new ReferralUrlBlacklist(), bad); } string ourNamespace = "urn:newtelligence-com:dasblog:runtime:data"; foreach (string file in Directory.GetFiles(path, "*.dayfeedback.xml")) { badWordsCount = 0; NameTable nt = new NameTable(); object permaLink = nt.Add("PermaLink"); XmlNamespaceManager ns = new XmlNamespaceManager(nt); ns.AddNamespace("def", ourNamespace); XmlDocument x = new XmlDocument(nt); try { x.Load(file); } catch (XmlException ex) { WriteLine(String.Format("ERROR: Malformed Xml in file: {0}", file)); WriteLine(ex.ToString()); Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); } XmlNodeList nodes = x.SelectNodes("/def:DayExtra/def:Trackings/def:Tracking", ns); Console.WriteLine("Found {0} trackings/referrals in {1}", nodes.Count, file); for (int i = 0; i < nodes.Count; i++) { XmlNode node = nodes[i]; XmlNode permaLinkNode = node[(string)permaLink]; if (permaLinkNode != null && IsBadNode(permaLinkNode.InnerText)) { badWordsCount++; totalBadWordsCount++; node.ParentNode.RemoveChild(node); } } if (badWordsCount > 0) { x.Save(file); } WriteLine(String.Format("Found {0} bad words in {1}...", badWordsCount, Path.GetFileName(file))); } }
static Schema() { NameTable nt = new NameTable(); nt.Add(Namespace.Xs.NamespaceName); NamespaceManager = new XmlNamespaceManager(nt); Swidtag = XDocument.Load(XmlReader.Create(new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("FearTheCowboy.Iso19770.Properties.Swidtag.xsd.xml")), new XmlReaderSettings())); NamespaceManager.AddNamespace("xs", Namespace.Xs.NamespaceName); }
public XmlJsonReader(Stream source, Encoding encoding) { TkDebug.AssertArgumentNull(source, "source", null); TkDebug.AssertArgumentNull(encoding, "encoding", null); fSource = source; fReader = new JsonTextReader(new StreamReader(source, encoding)); fRoot = NameTable.Add(ToolkitConst.ROOT_NODE_NAME); }
protected void Page_Load(object sender, EventArgs e) { int bookcount = 0; decimal booktotal = 0; XmlReaderSettings settings = new XmlReaderSettings(); NameTable nt = new NameTable(); object book = nt.Add("book"); object price = nt.Add("price"); settings.NameTable = nt; string booksSchemaFile = Path.Combine(Request.PhysicalApplicationPath, "books.xsd"); settings.Schemas.Add(null, XmlReader.Create(booksSchemaFile)); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler); settings.IgnoreWhitespace = true; settings.IgnoreComments = true; string booksFile = Path.Combine(Request.PhysicalApplicationPath, "books.xml"); using (XmlReader reader = XmlReader.Create(booksFile, settings)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && book.Equals(reader.LocalName)) //A subtle, but significant change! { bookcount++; } if (reader.NodeType == XmlNodeType.Element && price.Equals(reader.LocalName)) { booktotal += reader.ReadElementContentAsDecimal(); } } } Response.Write(String.Format("Found {0} books that total {1:C}!", bookcount, booktotal)); }
protected void Page_Load(object sender, EventArgs e) { //Create factory early XmlSerializerFactory factory = new XmlSerializerFactory(); XmlReaderSettings settings = new XmlReaderSettings(); NameTable nt = new NameTable(); object book = nt.Add("book"); object price = nt.Add("price"); object author = nt.Add("author"); settings.NameTable = nt; string booksSchemaFile = Path.Combine(Request.PhysicalApplicationPath, "books.xsd"); settings.Schemas.Add(null, XmlReader.Create(booksSchemaFile)); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler); settings.IgnoreWhitespace = true; settings.IgnoreComments = true; string booksFile = Path.Combine(Request.PhysicalApplicationPath, "books.xml"); using (XmlReader reader = XmlReader.Create(booksFile, settings)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && author.Equals(reader.LocalName)) { //Then use the factory to create and cache serializers XmlSerializer xs = factory.CreateSerializer(typeof(Author)); Author a = (Author)xs.Deserialize(reader.ReadSubtree()); Response.Write(String.Format("Author: {1}, {0}<BR/>", a.FirstName, a.LastName)); } } } }
public XmlDataSetReader(DataSet dataSet, bool closeInput) { TkDebug.AssertArgumentNull(dataSet, "dataSet", null); DataSet = dataSet; fRoot = NameTable.Add(dataSet.DataSetName); fTableCount = dataSet.Tables.Count; fCloseInput = closeInput; fIgnoreEmptyField = true; }
internal static NameTable CloneNameTable() { NameTable nameTable = new NameTable(); for (int i = 1; i < 27; i++) { nameTable.Add((string)PackageXmlStringTable._xmlstringtable[i].Name); } return(nameTable); }
/// <summary> /// Populates the ContextMenu from an XML file. /// </summary> private void PopulateContextMenu() { XmlReaderSettings settings = new XmlReaderSettings(); string contextmenuxml = Path.Combine(Request.PhysicalApplicationPath, "contextmenu.xml"); NameTable nameTable = new NameTable(); object contextMenuItem = nameTable.Add("contextmenuitem"); settings.NameTable = nameTable; using (XmlReader reader = XmlReader.Create(contextmenuxml, settings)) { while (reader.Read()) { // Read a single ContextMenuItem if ((reader.NodeType == XmlNodeType.Element) && (contextMenuItem.Equals(reader.LocalName))) { XmlReader subTree = reader.ReadSubtree(); ContextMenuItem menuItem = new ContextMenuItem(); // Get contents of a single ContextMenuItem while (subTree.Read()) { if ((subTree.NodeType == XmlNodeType.Element) && (subTree.LocalName.Equals("text"))) { menuItem.Text = subTree.ReadString(); } if ((subTree.NodeType == XmlNodeType.Element) && (subTree.LocalName.Equals("commandname"))) { menuItem.CommandName = subTree.ReadString(); } if ((subTree.NodeType == XmlNodeType.Element) && (subTree.LocalName.Equals("tooltip"))) { menuItem.Tooltip = subTree.ReadString(); } if ((subTree.NodeType == XmlNodeType.Element) && (subTree.LocalName.Equals("onclientclick"))) { menuItem.OnClientClick = subTree.ReadString(); } } // Add item to ContextMenu this.ContextMenu1.ContextMenuItems.Add(menuItem); } } } }
public static IEnumerable <Bigram> AsBigrams(this IEnumerable <string> words) { var nt = new NameTable(); string previous; var enumerator = words.Where(w => w[0] != '|') .Select(w => w.TrimEnd(',', '.', ';', '?', '!', ':').ToLowerInvariant()) .GetEnumerator(); if (enumerator.MoveNext()) { previous = nt.Add(enumerator.Current); while (enumerator.MoveNext()) { string current = nt.Add(enumerator.Current); yield return(new Bigram(previous, current)); previous = current; } } }
private static XmlReader CreateXmlReader <T>(string xmlData, string rootnodeName) { var nt = new NameTable(); var ns = new XmlNamespaceManager(nt); var context = new XmlParserContext(nt, ns, string.Empty, XmlSpace.Default); rootnodeName = nt.Add(rootnodeName); var Contractdocument = nt.Add("Contractdocument"); var AL = nt.Add("AL"); var PP = nt.Add("PP"); var XG = nt.Add("XG"); var emptyNs = string.Empty; var tr = new TranslatingXmlReader(xmlData, XmlNodeType.Document, context) .AddNameAndNsTranslation(emptyNs, Contractdocument, emptyNs, rootnodeName) .AddNameAndNsTranslation(emptyNs, AL, nsOperation, AL) .AddNameAndNsTranslation(emptyNs, PP, nsOperation, PP) .AddNameAndNsTranslation(emptyNs, XG, nsOperation, XG) .AddNamespaceUriTranslation(emptyNs, nsDatamodel); return(tr); }
public static void Main() { //<snippet1> // Add the element names to the NameTable. NameTable nt = new NameTable(); object book = nt.Add("book"); object title = nt.Add("title"); // Create a reader that uses the NameTable. XmlReaderSettings settings = new XmlReaderSettings(); settings.NameTable = nt; XmlReader reader = XmlReader.Create("books.xml", settings); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { // Cache the local name to prevent multiple calls to the LocalName property. object localname = reader.LocalName; // Do a comparison between the object references. This just compares pointers. if (book == localname) { // Add additional processing here. } // Do a comparison between the object references. This just compares pointers. if (title == localname) { // Add additional processing here. } } } // End While // Close the reader. reader.Close(); //</snippet1> }
public static IEnumerator<object> FromFile(string filename, IProgressListener progress) { progress.Status = "Loading diff..."; Future<string> fText; // We could stream the lines in from the IO thread while we parse them, but this // part of the load is usually pretty quick even on a regular hard disk, and // loading the whole diff at once eliminates some context switches using (var fda = new FileDataAdapter( filename, FileMode.Open, FileAccess.Read, FileShare.Read, 1024 * 128 )) { var fBytes = fda.ReadToEnd(); yield return fBytes; fText = Future.RunInThread( () => Encoding.ASCII.GetString(fBytes.Result) ); yield return fText; } yield return fText; var lr = new LineReader(fText.Result); LineReader.Line line; progress.Status = "Parsing diff..."; var frames = new List<TracebackFrame>(); var moduleNames = new NameTable(StringComparer.Ordinal); var symbolTypes = new NameTable(StringComparer.Ordinal); var functionNames = new NameTable(StringComparer.Ordinal); var deltas = new List<DeltaInfo>(); var tracebacks = new Dictionary<UInt32, TracebackInfo>(); var regexes = new Regexes(); // Regex.Groups[string] does an inefficient lookup, so we do that lookup once here int groupModule = regexes.DiffModule.GroupNumberFromName("module"); int groupSymbolType = regexes.DiffModule.GroupNumberFromName("symbol_type"); int groupTraceId = regexes.BytesDelta.GroupNumberFromName("trace_id"); int groupType = regexes.BytesDelta.GroupNumberFromName("type"); int groupDeltaBytes = regexes.BytesDelta.GroupNumberFromName("delta_bytes"); int groupNewBytes = regexes.BytesDelta.GroupNumberFromName("new_bytes"); int groupOldBytes = regexes.BytesDelta.GroupNumberFromName("old_bytes"); int groupNewCount = regexes.BytesDelta.GroupNumberFromName("new_count"); int groupOldCount = regexes.CountDelta.GroupNumberFromName("old_count"); int groupCountDelta = regexes.CountDelta.GroupNumberFromName("delta_count"); int groupTracebackModule = regexes.TracebackFrame.GroupNumberFromName("module"); int groupTracebackFunction = regexes.TracebackFrame.GroupNumberFromName("function"); int groupTracebackOffset = regexes.TracebackFrame.GroupNumberFromName("offset"); int groupTracebackOffset2 = regexes.TracebackFrame.GroupNumberFromName("offset2"); int groupTracebackPath = regexes.TracebackFrame.GroupNumberFromName("path"); int groupTracebackLine = regexes.TracebackFrame.GroupNumberFromName("line"); int i = 0; while (lr.ReadLine(out line)) { if (i % ProgressInterval == 0) { progress.Maximum = lr.Length; progress.Progress = lr.Position; // Suspend processing until any messages in the windows message queue have been processed yield return new Yield(); } retryFromHere: Match m; if (regexes.DiffModule.TryMatch(ref line, out m)) { moduleNames.Add(m.Groups[groupModule].Value); } else if (regexes.BytesDelta.TryMatch(ref line, out m)) { var traceId = UInt32.Parse(m.Groups[groupTraceId].Value, NumberStyles.HexNumber); var info = new DeltaInfo { Added = (m.Groups[groupType].Value == "+"), BytesDelta = int.Parse(m.Groups[groupDeltaBytes].Value, NumberStyles.HexNumber), NewBytes = int.Parse(m.Groups[groupNewBytes].Value, NumberStyles.HexNumber), OldBytes = int.Parse(m.Groups[groupOldBytes].Value, NumberStyles.HexNumber), NewCount = int.Parse(m.Groups[groupNewCount].Value, NumberStyles.HexNumber), }; if (lr.ReadLine(out line)) { if (regexes.CountDelta.TryMatch(ref line, out m)) { info.OldCount = int.Parse(m.Groups[groupOldCount].Value, NumberStyles.HexNumber); info.CountDelta = int.Parse(m.Groups[groupCountDelta].Value, NumberStyles.HexNumber); } } bool readingLeadingWhitespace = true, doRetry = false; frames.Clear(); var itemModules = new NameTable(StringComparer.Ordinal); var itemFunctions = new NameTable(StringComparer.Ordinal); while (lr.ReadLine(out line)) { if (line.ToString().Trim().Length == 0) { if (readingLeadingWhitespace) continue; else break; } else if (regexes.TracebackFrame.TryMatch(ref line, out m)) { readingLeadingWhitespace = false; var moduleName = moduleNames[m.Groups[groupTracebackModule].Value]; itemModules.Add(moduleName); var functionName = functionNames[m.Groups[groupTracebackFunction].Value]; itemFunctions.Add(functionName); var frame = new TracebackFrame { Module = moduleName, Function = functionName, Offset = UInt32.Parse(m.Groups[groupTracebackOffset].Value, NumberStyles.HexNumber) }; if (m.Groups[groupTracebackOffset2].Success) frame.Offset2 = UInt32.Parse(m.Groups[groupTracebackOffset2].Value, NumberStyles.HexNumber); if (m.Groups[groupTracebackPath].Success) frame.SourceFile = m.Groups[groupTracebackPath].Value; if (m.Groups[groupTracebackLine].Success) frame.SourceLine = int.Parse(m.Groups[groupTracebackLine].Value); frames.Add(frame); } else { // We hit the beginning of a new allocation, so make sure it gets parsed doRetry = true; break; } } if (tracebacks.ContainsKey(traceId)) { info.Traceback = tracebacks[traceId]; Console.WriteLine("Duplicate traceback for id {0}!", traceId); } else { var frameArray = ImmutableArrayPool<TracebackFrame>.Allocate(frames.Count); frames.CopyTo(frameArray.Array, frameArray.Offset); info.Traceback = tracebacks[traceId] = new TracebackInfo { TraceId = traceId, Frames = frameArray, Modules = itemModules, Functions = itemFunctions }; } deltas.Add(info); if (doRetry) goto retryFromHere; } else if (line.StartsWith("//")) { // Comment, ignore it } else if (line.StartsWith("Total increase") || line.StartsWith("Total decrease")) { // Ignore this too } else if (line.StartsWith(" ") && (line.EndsWith(".pdb"))) { // Symbol path for a module, ignore it } else { Console.WriteLine("Unrecognized diff content: {0}", line.ToString()); } } var result = new HeapDiff( filename, moduleNames, functionNames, deltas, tracebacks ); yield return new Result(result); }
public IEnumerator<object> DiffSnapshots(HeapSnapshotInfo first, HeapSnapshotInfo last) { var moduleNames = new NameTable(StringComparer.Ordinal); var heapIds = new HashSet<UInt32>(); var functionNames = new NameTable(); var deltas = new List<DeltaInfo>(); var tracebacks = new Dictionary<UInt32, TracebackInfo>(); { var fModulesFirst = Database.SnapshotModules.Get(first.Index); var fModulesLast = Database.SnapshotModules.Get(last.Index); var fHeapsFirst = Database.SnapshotHeaps.Get(first.Index); var fHeapsLast = Database.SnapshotHeaps.Get(last.Index); yield return fModulesFirst; foreach (var moduleName in fModulesFirst.Result) moduleNames.Add(Path.GetFileNameWithoutExtension(moduleName)); yield return fHeapsFirst; heapIds.UnionWith(from heap in fHeapsFirst.Result select heap.HeapID); yield return fModulesLast; foreach (var moduleName in fModulesLast.Result) moduleNames.Add(Path.GetFileNameWithoutExtension(moduleName)); yield return fHeapsLast; heapIds.UnionWith(from heap in fHeapsLast.Result select heap.HeapID); } var allocationIds = new HashSet<UInt32>(); { var fAllocations = Database.HeapAllocations.Select(heapIds); using (fAllocations) yield return fAllocations; yield return Future.RunInThread(() => { foreach (var ids in fAllocations.Result) allocationIds.UnionWith(ids); }); } { var tracebackIds = new HashSet<UInt32>(); var deallocs = new Dictionary<UInt32, DeltaInfo>(); var allocs = new Dictionary<UInt32, DeltaInfo>(); var fAllocationRanges = Database.Allocations.Select(allocationIds); using (fAllocationRanges) yield return fAllocationRanges; yield return Future.RunInThread(() => { DeltaInfo delta; foreach (var item in fAllocationRanges.Result) { var ranges = item.Ranges.Array; for (int i = 0, c = item.Ranges.Count, o = item.Ranges.Offset; i < c; i++) { var range = ranges[i + o]; if ((range.First <= first.Index) && (range.Last >= first.Index) && (range.Last < last.Index) ) { // deallocation if (deallocs.TryGetValue(range.TracebackID, out delta)) { delta.CountDelta += 1; delta.BytesDelta += (int)(range.Size + range.Overhead); delta.OldCount += 1; delta.OldBytes += (int)(range.Size + range.Overhead); } else { deallocs.Add(range.TracebackID, new DeltaInfo { Added = false, BytesDelta = (int)(range.Size + range.Overhead), CountDelta = 1, NewBytes = 0, NewCount = 0, OldBytes = (int)(range.Size + range.Overhead), OldCount = 1, TracebackID = range.TracebackID, Traceback = null }); } tracebackIds.Add(range.TracebackID); } else if ( (range.First <= last.Index) && (range.First > first.Index) && (range.Last >= last.Index) ) { // allocation if (allocs.TryGetValue(range.TracebackID, out delta)) { delta.CountDelta += 1; delta.BytesDelta += (int)(range.Size + range.Overhead); delta.NewCount += 1; delta.NewBytes += (int)(range.Size + range.Overhead); } else { allocs.Add(range.TracebackID, new DeltaInfo { Added = true, BytesDelta = (int)(range.Size + range.Overhead), CountDelta = 1, NewBytes = (int)(range.Size + range.Overhead), NewCount = 1, OldBytes = 0, OldCount = 0, TracebackID = range.TracebackID, Traceback = null }); } tracebackIds.Add(range.TracebackID); } } } foreach (var tracebackId in tracebackIds) { if (allocs.TryGetValue(tracebackId, out delta)) { DeltaInfo dealloc; if (deallocs.TryGetValue(tracebackId, out dealloc)) { delta.OldBytes = dealloc.OldBytes; delta.OldCount = dealloc.OldCount; delta.BytesDelta = Math.Abs(delta.NewBytes - delta.OldBytes); delta.CountDelta = Math.Abs(delta.NewCount - delta.OldCount.Value); if (delta.NewBytes < delta.OldBytes) delta.Added = false; } if (delta.BytesDelta != 0) deltas.Add(delta); } else if (deallocs.TryGetValue(tracebackId, out delta)) { if (delta.BytesDelta != 0) deltas.Add(delta); } } }); var fTracebacks = Database.Tracebacks.Select(tracebackIds); using (fTracebacks) yield return fTracebacks; Dictionary<UInt32, TracebackFrame> frameSymbols; { var rawFrames = new HashSet<UInt32>(); yield return Future.RunInThread(() => { foreach (var traceback in fTracebacks.Result) foreach (var rawFrame in traceback) rawFrames.Add(rawFrame); }); var fSymbols = Database.SymbolCache.Select(rawFrames); using (fSymbols) yield return fSymbols; var fSymbolDict = Future.RunInThread(() => SequenceUtils.ToDictionary(rawFrames, fSymbols.Result) ); yield return fSymbolDict; frameSymbols = fSymbolDict.Result; } yield return Future.RunInThread(() => { foreach (var tf in frameSymbols.Values) { if (tf.Function != null) functionNames.Add(tf.Function); } foreach (var traceback in fTracebacks.Result) { tracebacks[traceback.ID] = ConstructTracebackInfo( traceback.ID, traceback.Frames, frameSymbols ); } foreach (var d in deltas) d.Traceback = tracebacks[d.TracebackID]; }); } yield return Future.RunInThread(() => deltas.Sort((lhs, rhs) => { var lhsBytes = (lhs.Added ? 1 : -1) * lhs.BytesDelta; var rhsBytes = (rhs.Added ? 1 : -1) * rhs.BytesDelta; return rhsBytes.CompareTo(lhsBytes); }) ); yield return Result.New(new HeapDiff( null, moduleNames, functionNames, deltas, tracebacks )); }
// Test the exceptions that may be thrown by various methods. public void TestNameTableExceptions() { NameTable table = new NameTable(); char[] array = new char [10]; try { table.Add(null); Fail("Add(null) should throw an exception"); } catch(ArgumentNullException) { // Success } try { table.Get(null); Fail("Get(null) should throw an exception"); } catch(ArgumentNullException) { // Success } try { table.Add(null, 0, 0); Fail("Add(null, 0, 0) should throw an exception"); } catch(ArgumentNullException) { // Success } try { table.Get(null, 0, 0); Fail("Get(null, 0, 0) should throw an exception"); } catch(ArgumentNullException) { // Success } try { table.Add(array, 0, -1); Fail("Add(array, 0, -1) should throw an exception"); } catch(ArgumentOutOfRangeException) { // Success } try { table.Get(array, 0, -1); Fail("Get(array, 0, -1) should throw an exception"); } catch(ArgumentOutOfRangeException) { // Success } try { table.Add(array, -1, 3); Fail("Add(array, -1, 3) should throw an exception"); } catch(IndexOutOfRangeException) { // Success } try { table.Get(array, -1, 3); Fail("Get(array, -1, 3) should throw an exception"); } catch(IndexOutOfRangeException) { // Success } try { table.Add(array, 0, 11); Fail("Add(array, 0, 11) should throw an exception"); } catch(IndexOutOfRangeException) { // Success } try { table.Get(array, 0, 11); Fail("Get(array, 0, 11) should throw an exception"); } catch(IndexOutOfRangeException) { // Success } }
// Test adding strings and checking that object equality // works as string equality on the results. public void TestNameTableAdd() { NameTable table = new NameTable(); String value, value2, result; // Add an initial string, which should be added directly. value = "Hello"; result = table.Add(value); if(!ReferenceEquals(value, result)) { Fail("initial add"); } // Create a string that has the same contents as "value", // but which will not have the same object reference. value2 = String.Concat("Hel", "lo"); if(ReferenceEquals(value, value2)) { Fail("concat construction failed - runtime engine error"); } // Look up the initial string and validate it. if(!ReferenceEquals(value, table.Get(value))) { Fail("lookup initial did not give the initial string"); } if(!ReferenceEquals(value, table.Get(value2))) { Fail("lookup initial on same contents gave wrong result"); } // Add another string and validate against the first. value2 = table.Add("Goodbye"); if(ReferenceEquals(value2, value)) { Fail("Hello == Goodbye!"); } if(!ReferenceEquals(value, table.Get(value))) { Fail("initial string changed after adding another string"); } if(!ReferenceEquals(value2, table.Get("Goodbye"))) { Fail("second string could not be found on lookup"); } // Check that the empty string is added as "String.Empty". if(!ReferenceEquals(String.Empty, table.Add(""))) { Fail("empty string not added as String.Empty"); } // Add and get strings using an array. char[] array = new char [10]; array[3] = 'H'; array[4] = 'i'; value2 = table.Add(array, 3, 2); if(!ReferenceEquals(value2, table.Get("Hi"))) { Fail("array add on Hi failed"); } if(!ReferenceEquals(value2, table.Get(array, 3, 2))) { Fail("array get on Hi failed"); } array[3] = 'H'; array[4] = 'e'; array[5] = 'l'; array[6] = 'l'; array[7] = 'o'; value2 = table.Add(array, 3, 5); if(!ReferenceEquals(value, value2)) { Fail("array add on Hello gave incorrect value"); } if(!ReferenceEquals(value, table.Get(array, 3, 5))) { Fail("array add on Hello gave incorrect value"); } if(!ReferenceEquals(String.Empty, table.Add(array, 10, 0))) { Fail("array add on \"\" gave incorrect value"); } }
static XmlNameTable CreateNameTable() { XmlNameTable nameTable = new NameTable(); nameTable.Add(string.Empty); nameTable.Add(XNamespace.xmlnsPrefixNamespace); nameTable.Add(XNamespace.xmlPrefixNamespace); return nameTable; }
public IEnumerator<object> ResolveTracebackSymbols( IEnumerable<HeapSnapshot.Traceback> unresolvedTracebacks, Dictionary<UInt32, TracebackInfo> resolvedTracebacks, NameTable functionNames ) { Dictionary<UInt32, TracebackFrame> frameSymbols; { var rawFrames = new HashSet<UInt32>(); yield return Future.RunInThread(() => { foreach (var traceback in unresolvedTracebacks) foreach (var rawFrame in traceback) rawFrames.Add(rawFrame); }); var fSymbols = Database.SymbolCache.Select(rawFrames); using (fSymbols) yield return fSymbols; var fSymbolDict = Future.RunInThread(() => SequenceUtils.ToDictionary(rawFrames, fSymbols.Result) ); yield return fSymbolDict; frameSymbols = fSymbolDict.Result; } yield return Future.RunInThread(() => { if (functionNames != null) foreach (var tf in frameSymbols.Values) { if (tf.Function != null) functionNames.Add(tf.Function); } foreach (var traceback in unresolvedTracebacks) { resolvedTracebacks[traceback.ID] = ConstructTracebackInfo( traceback.ID, traceback.Frames, frameSymbols ); } }); }
public IEnumerator<object> DiffSnapshots(HeapSnapshotInfo first, HeapSnapshotInfo last) { var moduleNames = new NameTable(StringComparer.Ordinal); var heapIds = new HashSet<UInt32>(); var functionNames = new NameTable(); var deltas = new List<DeltaInfo>(); var tracebacks = new Dictionary<UInt32, TracebackInfo>(); { var fModulesFirst = Database.SnapshotModules.Get(first.Index); var fModulesLast = Database.SnapshotModules.Get(last.Index); var fHeapsFirst = Database.SnapshotHeaps.Get(first.Index); var fHeapsLast = Database.SnapshotHeaps.Get(last.Index); yield return fModulesFirst; foreach (var moduleName in fModulesFirst.Result) moduleNames.Add(Path.GetFileNameWithoutExtension(moduleName)); yield return fHeapsFirst; heapIds.UnionWith(from heap in fHeapsFirst.Result select heap.HeapID); yield return fModulesLast; foreach (var moduleName in fModulesLast.Result) moduleNames.Add(Path.GetFileNameWithoutExtension(moduleName)); yield return fHeapsLast; heapIds.UnionWith(from heap in fHeapsLast.Result select heap.HeapID); } var allocationIds = new HashSet<UInt32>(); { var fAllocations = Database.HeapAllocations.Select(heapIds); using (fAllocations) yield return fAllocations; yield return Future.RunInThread(() => { foreach (var ids in fAllocations.Result) allocationIds.UnionWith(ids); }); } { var tracebackIds = new HashSet<UInt32>(); var oldCounts = new Dictionary<UInt32, int>(); var oldBytes = new Dictionary<UInt32, int>(); var newCounts = new Dictionary<UInt32, int>(); var newBytes = new Dictionary<UInt32, int>(); var deallocs = new Dictionary<UInt32, DeltaInfo>(); var allocs = new Dictionary<UInt32, DeltaInfo>(); var fAllocationRanges = Database.Allocations.Select(allocationIds); using (fAllocationRanges) yield return fAllocationRanges; yield return Future.RunInThread(() => { DeltaInfo delta; foreach (var item in fAllocationRanges.Result) { var ranges = item.Ranges.Array; for (int i = 0, c = item.Ranges.Count, o = item.Ranges.Offset; i < c; i++) { var range = ranges[i + o]; bool aliveAtStart = (range.First <= first.Index) && (range.Last > first.Index); bool aliveAtEnd = (range.First <= last.Index) && (range.Last > last.Index); bool allocatedInWindow = (range.First >= first.Index) && (range.First <= last.Index); bool deallocatedInWindow = (range.Last >= first.Index) && (range.Last <= last.Index); if (!aliveAtStart && !aliveAtEnd && !allocatedInWindow && !deallocatedInWindow) continue; if (aliveAtStart) { int value; if (!oldCounts.TryGetValue(range.TracebackID, out value)) value = 0; oldCounts[range.TracebackID] = value + 1; if (!oldBytes.TryGetValue(range.TracebackID, out value)) value = 0; oldBytes[range.TracebackID] = (int)(value + range.Size); } if (aliveAtEnd) { int value; if (!newCounts.TryGetValue(range.TracebackID, out value)) value = 0; newCounts[range.TracebackID] = value + 1; if (!newBytes.TryGetValue(range.TracebackID, out value)) value = 0; newBytes[range.TracebackID] = (int)(value + range.Size); } if (allocatedInWindow) { // allocation if (allocs.TryGetValue(range.TracebackID, out delta)) { delta.CountDelta += 1; delta.BytesDelta += (int)(range.Size); } else { allocs.Add(range.TracebackID, new DeltaInfo { BytesDelta = (int)(range.Size), CountDelta = 1, TracebackID = range.TracebackID, Traceback = null }); } tracebackIds.Add(range.TracebackID); } if (deallocatedInWindow) { // deallocation if (deallocs.TryGetValue(range.TracebackID, out delta)) { delta.CountDelta -= 1; delta.BytesDelta -= (int)(range.Size); } else { deallocs.Add(range.TracebackID, new DeltaInfo { BytesDelta = -(int)(range.Size), CountDelta = -1, TracebackID = range.TracebackID, Traceback = null }); } tracebackIds.Add(range.TracebackID); } } } foreach (var tracebackId in tracebackIds) { DeltaInfo alloc = null, dealloc = null; if (allocs.TryGetValue(tracebackId, out alloc) | deallocs.TryGetValue(tracebackId, out dealloc)) { int currentOldBytes, currentOldCount; int currentNewBytes, currentNewCount; oldBytes.TryGetValue(tracebackId, out currentOldBytes); oldCounts.TryGetValue(tracebackId, out currentOldCount); newBytes.TryGetValue(tracebackId, out currentNewBytes); newCounts.TryGetValue(tracebackId, out currentNewCount); if (alloc != null) { alloc.OldBytes = currentOldBytes; alloc.OldCount = currentOldCount; alloc.NewBytes = currentNewBytes; alloc.NewCount = currentNewCount; deltas.Add(alloc); } if (dealloc != null) { dealloc.OldBytes = currentOldBytes; dealloc.OldCount = currentOldCount; dealloc.NewBytes = currentNewBytes; dealloc.NewCount = currentNewCount; deltas.Add(dealloc); } } } }); var fTracebacks = Database.FilteredTracebacks.CascadingSelect( new [] { Database.Tracebacks }, tracebackIds ); using (fTracebacks) yield return fTracebacks; yield return ResolveTracebackSymbols( fTracebacks.Result, tracebacks, functionNames ); yield return Future.RunInThread(() => { foreach (var d in deltas) d.Traceback = tracebacks[d.TracebackID]; }); } yield return Future.RunInThread(() => deltas.Sort((lhs, rhs) => { var lhsBytes = lhs.BytesDelta; var rhsBytes = rhs.BytesDelta; return rhsBytes.CompareTo(lhsBytes); }) ); yield return Result.New(new HeapDiff( null, moduleNames, functionNames, deltas, tracebacks )); }
public static TracebackInfo ConstructTracebackInfo(UInt32 tracebackID, ArraySegment<UInt32> rawFrames, IDictionary<UInt32, TracebackFrame> symbols) { var tracebackFunctions = new NameTable(StringComparer.Ordinal); var tracebackModules = new NameTable(StringComparer.Ordinal); var tracebackFrames = ImmutableArrayPool<TracebackFrame>.Allocate(rawFrames.Count); for (int i = 0, o = tracebackFrames.Offset, c = tracebackFrames.Count; i < c; i++) { var rawFrame = rawFrames.Array[rawFrames.Offset + i]; var symbol = symbols[rawFrame]; if ((symbol.Offset == 0) && (!symbol.Offset2.HasValue)) tracebackFrames.Array[i + o] = new TracebackFrame(rawFrame); else tracebackFrames.Array[i + o] = symbol; if (symbol.Function != null) tracebackFunctions.Add(symbol.Function); if (symbol.Module != null) tracebackModules.Add(symbol.Module); } return new TracebackInfo { Frames = tracebackFrames, Functions = tracebackFunctions, Modules = tracebackModules, TraceId = tracebackID }; }
public static void FixReferralSpam (string path) { string bad = ConfigurationManager.AppSettings["badWords"]; long badWordsCount = 0; long totalBadWordsCount = 0; DirectoryInfo info = new DirectoryInfo("../../"); ReferralBlackListFactory.AddBlacklist(new MovableTypeBlacklist(), Path.Combine(info.FullName, "blacklist.txt")); if (bad != null && bad.Length > 0) ReferralBlackListFactory.AddBlacklist(new ReferralUrlBlacklist(), bad); string ourNamespace = "urn:newtelligence-com:dasblog:runtime:data"; foreach (string file in Directory.GetFiles(path,"*.dayfeedback.xml")) { badWordsCount = 0; NameTable nt = new NameTable(); object permaLink = nt.Add("PermaLink"); XmlNamespaceManager ns = new XmlNamespaceManager(nt); ns.AddNamespace("def", ourNamespace); XmlDocument x = new XmlDocument(nt); try { x.Load(file); } catch (XmlException ex) { WriteLine(String.Format("ERROR: Malformed Xml in file: {0}",file)); WriteLine(ex.ToString()); Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); } XmlNodeList nodes = x.SelectNodes("/def:DayExtra/def:Trackings/def:Tracking", ns); Console.WriteLine("Found {0} trackings/referrals in {1}",nodes.Count,file); for (int i = 0; i < nodes.Count; i++) { XmlNode node = nodes[i]; XmlNode permaLinkNode = node[(string)permaLink]; if (permaLinkNode != null && IsBadNode(permaLinkNode.InnerText)) { badWordsCount++; totalBadWordsCount++; node.ParentNode.RemoveChild(node); } } if (badWordsCount > 0) { x.Save(file); } WriteLine(String.Format("Found {0} bad words in {1}...", badWordsCount, Path.GetFileName(file))); } }
public static void YankReferrals (string path) { string ourNamespace = "urn:newtelligence-com:dasblog:runtime:data"; foreach (string file in Directory.GetFiles(path,"*.dayfeedback.xml")) { NameTable nt = new NameTable(); object permaLink = nt.Add("PermaLink"); XmlNamespaceManager ns = new XmlNamespaceManager(nt); ns.AddNamespace("def", ourNamespace); XmlDocument x = new XmlDocument(nt); try { x.Load(file); } catch (XmlException ex) { WriteLine(String.Format("ERROR: Malformed Xml in file: {0}",file)); WriteLine(ex.ToString()); Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); } XmlNodeList nodes = x.SelectNodes("/def:DayExtra/def:Trackings/def:Tracking[def:TrackingType = \"Referral\"]", ns); for (int i = 0; i < nodes.Count; i++) { XmlNode node = nodes[i]; node.ParentNode.RemoveChild(node); } if (nodes.Count > 0) { x.Save(file); } WriteLine(String.Format("Removed {0} referrals in {1}",nodes.Count,file)); } }