XML-Fehlermeldung „Hexadezimaler Wert ist ein ungültiges Zeichen“

Fehlerbeschreibung

Beim Lesen von XML-Dokumenten in .NET mit dem XmlDocument oder dem XmlReader oder XmlTextReader kommt eine Fehlermeldung in der Form:

System.Xml.XmlException

—————-

‚‘, hexidezimaler Wert 0x1F, ist ein ungültiges Zeichen. Zeile 10, Position 13.

—————-

bei System.Xml.XmlTextReaderImpl.Throw(Exception e)
bei System.Xml.XmlTextReaderImpl.Throw(String res, String[] args)
bei System.Xml.XmlTextReaderImpl.Throw(Int32 pos, String res, String[] args)
bei System.Xml.XmlTextReaderImpl.ThrowInvalidChar(Int32 pos, Char invChar)
bei System.Xml.XmlTextReaderImpl.ParseCDataOrComment(XmlNodeType type, Int32& outStartPos, Int32& outEndPos)
bei System.Xml.XmlTextReaderImpl.ParseCDataOrComment(XmlNodeType type)
bei System.Xml.XmlTextReaderImpl.ParseElementContent()
bei System.Xml.XmlTextReaderImpl.Read()
bei System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
bei System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
bei System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
bei System.Xml.XmlDocument.Load(XmlReader reader)
bei System.Xml.XmlDocument.LoadXml(String xml)

Bzw. in Englisch:

System.Xml.XmlException

—————–

“, hexadecimal value 0x02, is an invalid character. Line 19, position 5.

—————–

at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args)
at System.Xml.XmlTextReaderImpl.ThrowInvalidChar(Int32 pos, Char invChar)
at System.Xml.XmlTextReaderImpl.ParseCDataOrComment(XmlNodeType type, Int32& outStartPos, Int32& outEndPos)
at System.Xml.XmlTextReaderImpl.ParseCDataOrComment(XmlNodeType type)
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.LoadXml(String xml)

Ursache

Es ist wohl tatsächlich ein für den XML-Parser ungültiges Zeichen enthalten.

Wie das Zeichen jeweils herein kam ist mir unbekannt. Da ich den XML-Text jeweils selbst auch wegschreibe (basierend auf einem gehosteten Internet Explorer im Design-Modus), gehe ich davon aus, dass aus dem Internet Explorer ungültige Zeichen „durchrutschen“.

Eigentlich hätte ich erwartet dass beim Generieren des XML-Dokuments die .NET-XML-Routinen ungültige Zeichen bereits herausfiltern bzw. korrekt escapen.

Lösung

Auf dieser Website wird als Lösung beschrieben, die ungültigen Zeichen zu entfernen.

Mithilfe eines Regulären Ausdrucks habe ich das dann gemacht. Hier ist ein Code-Ausschnitt:

private static Regex _rx;

public static string CleanInvalidXmlCharacters(
string xml)
{
if (string.IsNullOrEmpty(xml))
{
return xml;
}
else
{
if (_rx == null)
{
//
http://www.discogs.com/help/forums/topic/189304
//
http://meinews.niuz.biz/regex-t248608.html?s=3e8c40fe6d48a1a36e66437f3a3ec944&
_rx = new Regex(@“[\x01-\x08\x0B\x0C\x0E-\x1F]“, RegexOptions.Compiled);
}

return _rx.Replace(xml, string.Empty);
}
}

Diese Funktion rufe ich jeweils auf, bevor ich eine Zeichenfolge an die XmlDocument.Load( string xml )-Methode übergebe.

Ich bin mir unsicher ob das die perfekte Lösung ist; sie funktioniert (übrigens in dem Programm hier) und scheint keine Seiteneffekte zu haben.

Andere Meinungen dazu?

System.Security.SecurityException für System.Web.AspNetHostingPermission

Fehlermeldung

Heute habe ich nach dem Aktualisieren einer ASP.NET-3.5-Anwendung auf einem IIS7-Server folgende Fehlermeldung im Browser erhalten:

Serverfehler in der Anwendung /MyApplication.

Sicherheitsausnahme

Beschreibung: Die Anwendung hat versucht, einen Vorgang auszuführen, der von der Sicherheitsrichtlinie nicht zugelassen ist. Um der Anwendung die erforderliche Berechtigung zu erteilen, wenden Sie sich an den Systemadministrator oder ändern Sie die Vertrauensebene für die Anwendung in der Konfigurationsdatei.

Ausnahmedetails: System.Security.SecurityException: Fehler bei der Anforderung des Berechtigungstyps „System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089“.

Quellfehler:

Beim Ausführen der aktuellen Webanforderung wurde einen unbehandelte Ausnahme generiert. Informationen über den Ursprung und die Position der Ausnahme können mit der Ausnahmestapelüberwachung angezeigt werden.

Stapelüberwachung:

[SecurityException: Fehler bei der Anforderung des Berechtigungstyps „System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″.]
System.Reflection.Assembly._GetExportedTypes() +0
System.Reflection.Assembly.GetExportedTypes() +16
System.Web.Compilation.BuildResultMainCodeAssembly.FindAppInitializeMethod() +26
System.Web.Compilation.CodeDirectoryCompiler.GetCodeDirectoryAssembly(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories, Boolean isDirectoryAllowed) +882
System.Web.Compilation.BuildManager.CompileCodeDirectory(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories) +125
System.Web.Compilation.BuildManager.CompileCodeDirectories() +265
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +320

Versionsinformationen: Microsoft .NET Framework-Version:2.0.50727.4927; ASP.NET-Version:2.0.50727.4927

Das war ein Schock!

Und auch noch auf einem Produktivserver eines Kunden. Fuck!

Workaround

Also gleich die zuvor gemachte Sicherheitskopie zurückgespielt, dann lief alles wieder.

Damit erst mal genug, während der Hauptnutzungszeit der Kunden keine weitere Experimente.

Analyse und Lösung

Heute Abend habe ich dann nach Gesprächen mit einem Kollegen eine Idee gehabt:

Es könnte ja sein, dass es beim Entpacken der neuen Dateien aus dem ZIP-Archiv mit dem ich diese auf den Server übertragen habe, ggf. die NTFS-Berechtigungen zerschossen/verbogen wurden.

Also habe ich nochmals die neuen Dateien in den Zielordner des Webserver kopiert und via Rechtsklick auf den Ordner, alle Sicherheitsberechtigungen auf die neu hineinkopierten Dateien und Ordner vererben lassen, besehende Berechtigungen ersetzen lassen.

Und siehe da: Die Anwendung funktioniert wieder wie gewünscht!

CodeProject Most Valuable Professional

Heute ein wenig Eigenlob:

Ich freue mich, soeben meine Urkunde erhalten zu haben:

Da ich viele kostenlose Artikel auf CodeProject.com, meiner Lieblings-Entwickler-Website, veröffentlicht habe, haben sie mir den MVP-Status für 2010 gegeben.

Neben der Urkunde habe ich damit auch auf der Website ein paar zusätzliche Berechtigungen.

Ich freue mich sehr 🙂

Add Syntax Highlighting for new file extensions in Notepad++

Using Notepad++ to edit a „Web.config“ ASP.NET configuration file, I was missing the XML syntax coloring.

Since I found no way to do it through the Notepad++ GUI, I searched for a manual way that luckily exists.

Here is how:

  1. Open the „stylers.xml“ Notepad++ configuration file by:
    1. Click „Start“.
    2. Click „Run“.
    3. Enter „%appdata%\Notepad++“ (without the quotes) and click „OK“. The folder „C:\Users\YourUserName\AppData\Roaming\Notepad++“ will be opened.
    4. Open the file „stylers.xml“ in a text editor, e.g. Notepad++ itself.
  2. Search for the line „<LexerType name=“xml“ desc=“XML“ ext=““>„.
  3. Replace it with „<LexerType name=“xml“ desc=“XML“ ext=“config“>„. (For multiple entries separate them by spaces, write the extensions without leading periods)
  4. Save the file „stylers.xml“.
  5. (Re-)start Notepad++.

Now you have associated the extension „.config“ with the XML syntax coloring.

Please note that in case you had an unassociated file open in Notepad++ before associating with a lexer and restart Notepad++ with the file automatically being opened again, this file still is shown without syntax coloring. You first have to close and reopen that file to have the new syntax coloring being applied.

Update 2013-03-01

I just found out that you can also do it via the GUI like the following.

1.) Click the menu:

Notepad++ menu

2.) Configure your extension:

Notepad++ style dialog

Using UrlRewriter.NET in IIS7

When migrating an IIS6 website to IIS7 you probably want to keep an existing UrlRewriter.NET configuration and migrate to the official Microsoft URL Rewriter Module for IIS 7 later on.

Here is the important excerpt from „Web.config“:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
        <add name="UrlRewriter"
            type="Intelligencia.UrlRewriter.RewriterHttpModule" />
    </modules>
</system.webServer>

Thanks to Rainer who figured this out from this posting.

Another good discussion can be found in the article „Wildcard script mapping and IIS 7 integrated pipeline“ on the IIS website and the article „Use a Single Web.Config for IIS6 and IIS7„.

Command Routing in Windows Forms .NET

When developing a real-world application in Windows Forms .NET, you usually have multiple menus, tool bars, ribbons, context menus, etc.

The challenge here is to provide central handlers to perform actions (e.g. an action to open a file) that came from various sources (e.g. the user clicks a menu item, or a tool bar item).


(Screenshot from my article on CodeProject about the same topic)

MFC

In the pre-.NET days there were the Microsoft Foundation Classes (MFC) that came with what they call „Command Routing„.

In MFC’s command routing the framework was responsible of correctly dispatching to the correct handler. In the handler you could specify (among other things):

  • Whether the command’s visual representation (a button, a menu item, …) is displayed in enabled or disabled state.
  • The action to perform when the command is being executed.

The dispatching took place automatically, depending on the current focused window.

.NET Windows Forms

Now when Windows Forms appeared, they completely lacked this command routing framework.

Therefore I developed my own minimal version that is nearly-bug-free for some projects. You can download an example project here.

Since there are more approaches by other developers to solve the lack of command routing in Windows Forms, I want to use this article to list the good ones I found:

I’m looking forward to read your resources, feel free to post them here in the comments section below.

Windows Presentation Foundation (WPF)

To be honest, I do have no practical experiences in WPF. Luckily my co-worker Dennis has a Microsoft certification on WPF.

From what I do understand, WPF does have very decent command routing. Maybe some reader can comment on whether it would be possible to extract parts of the WPF command routing and use it in Windows Forms? (Here is a German discussion about that topic)

I hope that I will soon be able to try WPF in my own projects. 🙂

(Keyword: event routing event bubbling bubble event tree hierarchy)

Under the desk

Der geneigte Webcam-Besucher mag sich ggf. schon gefragt haben, wie die untere Hälfte zur Webcam aussieht.

Die liebe Jana ist dieser brennenden Frage nun investigativ nachgegangen und konnte mit folgender Aufnahme aufwarten:

Ich bitte um Beachtung, dass normalerweise deutlich elegantere orange Crocs meine edlen Füße zieren.

„RIGHT“-Funktion in Oracle

Um die letzten n Zeichen einer Zeichenfolge zu ermitteln gibt es in Basic z.B. die Right-Funktion.

Große Dateien sendenHomepage erstellenSharepoint StuttgartTest Management Software

In Oracle gibt es dazu SUBSTR-Funktion. Wird diese mit einer negativen Zahl aufgerufen, so wird vom Ende der Zeichenfolge gezählt, was einer Right-Funktion entspricht.

Beispiele:

substr(‚This is a test‘, 6, 2)Liefert ‚is‘ als Ergebnis
substr(‚This is a test‘, 6)Liefert ‚is a test‘ als Ergebnis
substr(‚TechOnTheNet‘, 1, 4)Liefert ‚Tech‘ als Ergebnis
substr(‚TechOnTheNet‘, -3, 3)Liefert ‚Net‘ als Ergebnis
substr(‚TechOnTheNet‘, -3)Liefert ebenfalls ‚Net‘ als Ergebnis
substr(‚TechOnTheNet‘, -6, 3)Liefert ‚The‘ als Ergebnis
substr(‚TechOnTheNet‘, -8, 2)Liefert ‚On‘ als Ergebnis

(Via Tech on the Net)

Result codes for GetLastError()

Just for reference purposes, all System Error Codes are listed on MSDN:

To actually translate numeric error codes to user-readable error codes, use the FormatMessage function.

In .NET, use the following code snippet as a replacement for the FormatMessage function:

var errorMessage = 
    new Win32Exception(Marshal.GetLastWin32Error()).Message;

(Tip via pinvoke.net)