Меню

Шестнадцатеричное значение 0x00 является недопустимым знаком строка 1 позиция как исправить ошибку

I am generating an XML document from a StringBuilder, basically something like:

string.Format("<text><row>{0}</row><col>{1}</col><textHeight>{2}</textHeight><textWidth>{3}</textWidth><data>{4}</data><rotation>{5}</rotation></text>

Later, something like:

XmlDocument document = new XmlDocument();
document.LoadXml(xml);
XmlNodeList labelSetNodes = document.GetElementsByTagName("labels");
for (int index = 0; index < labelSetNodes.Count; index++)
{
    //do something
}

All the data comes from a database.
Recently I’ve had a few issues with the error:

Hexadecimal value 0x00 is a invalid character, line 1, position nnnnn

But its not consistent.
Sometimes some ‘blank’ data will work.
The ‘faulty’ data works on some PCs, but not others.

In the database, the data is always a blank string. It is never ‘null’
and in the XML file, it comes out as < data>< /data>, i.e. no character between opening and closing. (but not sure if this can be relied on as I am pulling it from the ‘immediate’ window is vis studio and pasting it into textpad).

There is possibly differences in the versions of sql server (2008 is where it would fail, 2005 would work) and collation too.
Not sure if any of these are likely causes?

But exactly the same code and data will sometimes fail. Any ideas where the problem lies?

abatishchev's user avatar

abatishchev

96.9k84 gold badges296 silver badges432 bronze badges

asked Jun 14, 2012 at 15:50

jb.'s user avatar

2

Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:

  • Unicode NUL (0x00) is illegal in all versions of XML and validating parsers must reject input that contains it.
  • Despite the above; real-world non-validated XML can contain any kind of garbage ill-formed bytes imaginable.
  • XML 1.1 allows zero-width and nonprinting control characters (except NUL), so you cannot look at an XML 1.1 file in a text editor and tell what characters it contains.

Given what you wrote, I suspect whatever converts the database data to XML is broken; it’s propagating non-XML characters.

Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.

If the converter output looks good, the problem is in your XML consumer; it’s inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.

Check file encoding (for UTF-16)

Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn’t, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.

CJBS's user avatar

CJBS

14.9k5 gold badges85 silver badges135 bronze badges

answered Jun 14, 2012 at 18:27

Dour High Arch's user avatar

Dour High ArchDour High Arch

21.3k29 gold badges75 silver badges90 bronze badges

3

In my case, it took some digging, but found it.

My Context

I’m looking at exception/error logs from the website using Elmah. Elmah returns the state of the server at the of time the exception, in the form of a large XML document. For our reporting engine I pretty-print the XML with XmlWriter.

During a website attack, I noticed that some xmls weren’t parsing and was receiving this '.', hexadecimal value 0x00, is an invalid character. exception.

NON-RESOLUTION: I converted the document to a byte[] and sanitized it of 0x00, but it found none.

When I scanned the xml document, I found the following:

...
<form>
...
<item name="SomeField">
   <value
     string="C:boot.ini.htm" />
 </item>
...

There was the nul byte encoded as an html entity !!!

RESOLUTION: To fix the encoding, I replaced the value before loading it into my XmlDocument, because loading it will create the nul byte and it will be difficult to sanitize it from the object. Here’s my entire process:

XmlDocument xml = new XmlDocument();
details.Xml = details.Xml.Replace("", "[0x00]");  // in my case I want to see it, otherwise just replace with ""
xml.LoadXml(details.Xml);

string formattedXml = null;

// I have this in a helper function, but for this example I have put it in-line
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
    OmitXmlDeclaration = true,
    Indent = true,
    IndentChars = "t",
    NewLineHandling = NewLineHandling.None,
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
    xml.Save(writer);
    formattedXml = sb.ToString();
}

LESSON LEARNED: sanitize for illegal bytes using the associated html entity, if your incoming data is html encoded on entry.

answered Oct 24, 2013 at 17:24

sonjz's user avatar

sonjzsonjz

4,7623 gold badges40 silver badges60 bronze badges

To add to Sonz’s answer above, following worked for us.

//Instead of 
XmlString.Replace("", "[0x00]");
// use this
XmlString.Replace("x00", "[0x00]");

answered Jul 17, 2015 at 16:26

Mike-Monkey's user avatar

3

I also get the same error in an ASP.NET application when I saved some unicode data (Hindi) in the Web.config file and saved it with «Unicode» encoding.

It fixed the error for me when I saved the Web.config file with «UTF-8» encoding.

answered Apr 17, 2013 at 5:24

DEEPAK SHARMA's user avatar

As kind of a late answer:

I’ve had this problem with SSRS ReportService2005.asmx when uploading a report.

    Public Shared Sub CreateReport(ByVal strFileNameAndPath As String, ByVal strReportName As String, ByVal strReportingPath As String, Optional ByVal bOverwrite As Boolean = True)
        Dim rs As SSRS_2005_Administration_WithFOA = New SSRS_2005_Administration_WithFOA
        rs.Credentials = ReportingServiceInterface.GetMyCredentials(strCredentialsURL)
        rs.Timeout = ReportingServiceInterface.iTimeout
        rs.Url = ReportingServiceInterface.strReportingServiceURL
        rs.UnsafeAuthenticatedConnectionSharing = True

        Dim btBuffer As Byte() = Nothing

        Dim rsWarnings As Warning() = Nothing
        Try
            Dim fstrStream As System.IO.FileStream = System.IO.File.OpenRead(strFileNameAndPath)
            btBuffer = New Byte(fstrStream.Length - 1) {}
            fstrStream.Read(btBuffer, 0, CInt(fstrStream.Length))
            fstrStream.Close()
        Catch ex As System.IO.IOException
            Throw New Exception(ex.Message)
        End Try

        Try
            rsWarnings = rs.CreateReport(strReportName, strReportingPath, bOverwrite, btBuffer, Nothing)

            If Not (rsWarnings Is Nothing) Then
                Dim warning As Warning
                For Each warning In rsWarnings
                    Log(warning.Message)
                Next warning
            Else
                Log("Report: {0} created successfully with no warnings", strReportName)
            End If

        Catch ex As System.Web.Services.Protocols.SoapException
            Log(ex.Detail.InnerXml.ToString())
        Catch ex As Exception
            Log("Error at creating report. Invalid server name/timeout?" + vbCrLf + vbCrLf + "Error Description: " + vbCrLf + ex.Message)
            Console.ReadKey()
            System.Environment.Exit(1)
        End Try
    End Sub ' End Function CreateThisReport

The problem occurs when you allocate a byte array that is at least 1 byte larger than the RDL (XML) file.

Specifically, I used a C# to vb.net converter, that converted

  btBuffer = new byte[fstrStream.Length];

into

  btBuffer = New Byte(fstrStream.Length) {}

But because in C# the number denotes the NUMBER OF ELEMENTS in the array, and in VB.NET, that number denotes the UPPER BOUND of the array, I had an excess byte, causing this error.

So the problem’s solution is simply:

  btBuffer = New Byte(fstrStream.Length - 1) {}

answered Nov 15, 2013 at 8:37

Stefan Steiger's user avatar

Stefan SteigerStefan Steiger

76.5k65 gold badges374 silver badges437 bronze badges

I’m using IronPython here (same as .NET API) and reading the file as UTF-8 in order to properly handle the BOM fixed the problem for me:

xmlFile = Path.Combine(directory_str, 'file.xml')
doc = XPathDocument(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))

It would work as well with the XmlDocument:

doc = XmlDocument()
doc.Load(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))

answered May 30, 2017 at 3:50

B Medeiros's user avatar

B MedeirosB Medeiros

2,22421 silver badges34 bronze badges

I haved the same issue, when I tried to save the file, whole code is perfect but in the last procedure, the follow error message appears:
«‘.’, Hexadecimal value 0x00 is a invalid character.»

1.Looking in the develop tool, I found in the name assigned to sheets collection {Hoja1}, {Cartera}, {JennyG, {MariaD, …

2.Then I saw last character ‘}’ in the name of sheets should be lost to the any time in the algorithm process to assign names of the sheet from a DataTable Object.

3.On the Name property the real Name of the sheet is «MariaD», the hidden character in property name is not supported «».

4.Finally, the solution is replace current character with «» empty string in the all sheets name.

answered May 25, 2021 at 18:23

Jesus Isidro Zamudio Cárdenas's user avatar

I am generating an XML document from a StringBuilder, basically something like:

string.Format("<text><row>{0}</row><col>{1}</col><textHeight>{2}</textHeight><textWidth>{3}</textWidth><data>{4}</data><rotation>{5}</rotation></text>

Later, something like:

XmlDocument document = new XmlDocument();
document.LoadXml(xml);
XmlNodeList labelSetNodes = document.GetElementsByTagName("labels");
for (int index = 0; index < labelSetNodes.Count; index++)
{
    //do something
}

All the data comes from a database.
Recently I’ve had a few issues with the error:

Hexadecimal value 0x00 is a invalid character, line 1, position nnnnn

But its not consistent.
Sometimes some ‘blank’ data will work.
The ‘faulty’ data works on some PCs, but not others.

In the database, the data is always a blank string. It is never ‘null’
and in the XML file, it comes out as < data>< /data>, i.e. no character between opening and closing. (but not sure if this can be relied on as I am pulling it from the ‘immediate’ window is vis studio and pasting it into textpad).

There is possibly differences in the versions of sql server (2008 is where it would fail, 2005 would work) and collation too.
Not sure if any of these are likely causes?

But exactly the same code and data will sometimes fail. Any ideas where the problem lies?

abatishchev's user avatar

abatishchev

96.9k84 gold badges296 silver badges432 bronze badges

asked Jun 14, 2012 at 15:50

jb.'s user avatar

2

Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:

  • Unicode NUL (0x00) is illegal in all versions of XML and validating parsers must reject input that contains it.
  • Despite the above; real-world non-validated XML can contain any kind of garbage ill-formed bytes imaginable.
  • XML 1.1 allows zero-width and nonprinting control characters (except NUL), so you cannot look at an XML 1.1 file in a text editor and tell what characters it contains.

Given what you wrote, I suspect whatever converts the database data to XML is broken; it’s propagating non-XML characters.

Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.

If the converter output looks good, the problem is in your XML consumer; it’s inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.

Check file encoding (for UTF-16)

Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn’t, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.

CJBS's user avatar

CJBS

14.9k5 gold badges85 silver badges135 bronze badges

answered Jun 14, 2012 at 18:27

Dour High Arch's user avatar

Dour High ArchDour High Arch

21.3k29 gold badges75 silver badges90 bronze badges

3

In my case, it took some digging, but found it.

My Context

I’m looking at exception/error logs from the website using Elmah. Elmah returns the state of the server at the of time the exception, in the form of a large XML document. For our reporting engine I pretty-print the XML with XmlWriter.

During a website attack, I noticed that some xmls weren’t parsing and was receiving this '.', hexadecimal value 0x00, is an invalid character. exception.

NON-RESOLUTION: I converted the document to a byte[] and sanitized it of 0x00, but it found none.

When I scanned the xml document, I found the following:

...
<form>
...
<item name="SomeField">
   <value
     string="C:boot.ini.htm" />
 </item>
...

There was the nul byte encoded as an html entity !!!

RESOLUTION: To fix the encoding, I replaced the value before loading it into my XmlDocument, because loading it will create the nul byte and it will be difficult to sanitize it from the object. Here’s my entire process:

XmlDocument xml = new XmlDocument();
details.Xml = details.Xml.Replace("", "[0x00]");  // in my case I want to see it, otherwise just replace with ""
xml.LoadXml(details.Xml);

string formattedXml = null;

// I have this in a helper function, but for this example I have put it in-line
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
    OmitXmlDeclaration = true,
    Indent = true,
    IndentChars = "t",
    NewLineHandling = NewLineHandling.None,
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
    xml.Save(writer);
    formattedXml = sb.ToString();
}

LESSON LEARNED: sanitize for illegal bytes using the associated html entity, if your incoming data is html encoded on entry.

answered Oct 24, 2013 at 17:24

sonjz's user avatar

sonjzsonjz

4,7623 gold badges40 silver badges60 bronze badges

To add to Sonz’s answer above, following worked for us.

//Instead of 
XmlString.Replace("", "[0x00]");
// use this
XmlString.Replace("x00", "[0x00]");

answered Jul 17, 2015 at 16:26

Mike-Monkey's user avatar

3

I also get the same error in an ASP.NET application when I saved some unicode data (Hindi) in the Web.config file and saved it with «Unicode» encoding.

It fixed the error for me when I saved the Web.config file with «UTF-8» encoding.

answered Apr 17, 2013 at 5:24

DEEPAK SHARMA's user avatar

As kind of a late answer:

I’ve had this problem with SSRS ReportService2005.asmx when uploading a report.

    Public Shared Sub CreateReport(ByVal strFileNameAndPath As String, ByVal strReportName As String, ByVal strReportingPath As String, Optional ByVal bOverwrite As Boolean = True)
        Dim rs As SSRS_2005_Administration_WithFOA = New SSRS_2005_Administration_WithFOA
        rs.Credentials = ReportingServiceInterface.GetMyCredentials(strCredentialsURL)
        rs.Timeout = ReportingServiceInterface.iTimeout
        rs.Url = ReportingServiceInterface.strReportingServiceURL
        rs.UnsafeAuthenticatedConnectionSharing = True

        Dim btBuffer As Byte() = Nothing

        Dim rsWarnings As Warning() = Nothing
        Try
            Dim fstrStream As System.IO.FileStream = System.IO.File.OpenRead(strFileNameAndPath)
            btBuffer = New Byte(fstrStream.Length - 1) {}
            fstrStream.Read(btBuffer, 0, CInt(fstrStream.Length))
            fstrStream.Close()
        Catch ex As System.IO.IOException
            Throw New Exception(ex.Message)
        End Try

        Try
            rsWarnings = rs.CreateReport(strReportName, strReportingPath, bOverwrite, btBuffer, Nothing)

            If Not (rsWarnings Is Nothing) Then
                Dim warning As Warning
                For Each warning In rsWarnings
                    Log(warning.Message)
                Next warning
            Else
                Log("Report: {0} created successfully with no warnings", strReportName)
            End If

        Catch ex As System.Web.Services.Protocols.SoapException
            Log(ex.Detail.InnerXml.ToString())
        Catch ex As Exception
            Log("Error at creating report. Invalid server name/timeout?" + vbCrLf + vbCrLf + "Error Description: " + vbCrLf + ex.Message)
            Console.ReadKey()
            System.Environment.Exit(1)
        End Try
    End Sub ' End Function CreateThisReport

The problem occurs when you allocate a byte array that is at least 1 byte larger than the RDL (XML) file.

Specifically, I used a C# to vb.net converter, that converted

  btBuffer = new byte[fstrStream.Length];

into

  btBuffer = New Byte(fstrStream.Length) {}

But because in C# the number denotes the NUMBER OF ELEMENTS in the array, and in VB.NET, that number denotes the UPPER BOUND of the array, I had an excess byte, causing this error.

So the problem’s solution is simply:

  btBuffer = New Byte(fstrStream.Length - 1) {}

answered Nov 15, 2013 at 8:37

Stefan Steiger's user avatar

Stefan SteigerStefan Steiger

76.5k65 gold badges374 silver badges437 bronze badges

I’m using IronPython here (same as .NET API) and reading the file as UTF-8 in order to properly handle the BOM fixed the problem for me:

xmlFile = Path.Combine(directory_str, 'file.xml')
doc = XPathDocument(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))

It would work as well with the XmlDocument:

doc = XmlDocument()
doc.Load(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))

answered May 30, 2017 at 3:50

B Medeiros's user avatar

B MedeirosB Medeiros

2,22421 silver badges34 bronze badges

I haved the same issue, when I tried to save the file, whole code is perfect but in the last procedure, the follow error message appears:
«‘.’, Hexadecimal value 0x00 is a invalid character.»

1.Looking in the develop tool, I found in the name assigned to sheets collection {Hoja1}, {Cartera}, {JennyG, {MariaD, …

2.Then I saw last character ‘}’ in the name of sheets should be lost to the any time in the algorithm process to assign names of the sheet from a DataTable Object.

3.On the Name property the real Name of the sheet is «MariaD», the hidden character in property name is not supported «».

4.Finally, the solution is replace current character with «» empty string in the all sheets name.

answered May 25, 2021 at 18:23

Jesus Isidro Zamudio Cárdenas's user avatar

Проблема

При попытке запустить 3ds Max, после запуска ленты 3ds Max может появиться следующее сообщение об ошибке:

Ошибка разбора XAML

Ошибка при разборе файла XAML: «.», шестнадцатеричное значение 0x00, является недопустимым символом. Строка 1, позиция 1.

Изображение, добавленное пользователем

После нажатия ОК появляется другое сообщение:

Сброс настроек ленты?

Основной файл конфигурации ленты, возможно, поврежден. Восстановить стандартные параметры?

Изображение, добавленное пользователем

Причины:

Один или несколько пользовательских файлов настроек могут быть повреждены или отсутствуют. Это может быть вызвано различными проблемами, включая запись данных в эти файлы с помощью подключаемых модулей 3ds Max, или быстрое закрытие нескольких копий 3ds Max и запись в один и тот же файл одновременно.

Решение

Восстановите пользовательские настройки 3ds Max до значений по умолчанию, как описано в следующей статье: Восстановление пользовательских настроек 3ds Max до значений по умолчанию.

Замечания: После сброса папка настроек будет создана автоматически при следующем запуске программы. Эта процедура относится только к активному пользователю, который должен войти в систему, так как 3ds Max сохраняет настройки для каждого профиля пользователя в Windows.

Если настройки сброса параметров не помогают переустановить 3ds Max, так как приложение может быть повреждено из последних обновлений.

Добрый день!

При запуске фалов Ексель вылазит вот такая ошибка:

«.», шестнадцатеричное значение 0x00 является недопустимым знаком., строка 1, позиция 1.в system.xml.xmltextreaderlmpl.throw (Exception e)
в system.xml.xmltextreaderlmpl.throwlnvalidChar(Char data, int32 lenght, int32 invChair Pos)
в system.xml.xmltextreaderlmpl.ParseRootLevelWhitesp ace()
в system.xml.xmltextreaderlmpl.ParseDocumentContent( )
в system.xml.Linq.XDocument.Load(String uri, LoadOptions options)
В ASC.UI.Settings.Load()
в ASC.ASCAddln.ASCStartup()
В ASC.ASCAddln.ThisAddln_Sturtup(Object sender, EventArgs e)

Более того, если таблица ексель интегрирована в другое приложение, например Автокад, то снова вылазит эта ошибка! Например, я вставил в Автокад таблицу ексель, она не появится там, пока я не нажму ОК на этой ошибке и так постоянно!

Фото прикрепил!

Помогите решить проблему, без переустановки винды!

П.С. Офис переустанавливал — не помогло!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

  • Remove From My Forums

 none

Проблемы при развертывании приложения

  • Вопрос

  • При отладке приложения, на стадии развертывания получаю сообщение :

    DEP0600: При развертывании произошла следующая ошибка:

    «.», шестнадцатеричное значение 0x00, является недопустимым знаком., строка 1, позиция 1.

    в каком файле это происходит не указано. просмотрел все файлы настройки в HEX формате, нет ничего подобного, сохранил их в из Unicode в ANSI на всякий случай. Ни какого эффекта, в форумах нет решений. Разве что нашел информацию
    что переустановка студии ничего не дает в аналогичном случае. «http://stackoverflow.com/questions/38678303/dep0600-error-when-deploying-uwp-project»

    Все новые создаваемые приложения та же проблема, хотя сборка для магазина с последующей установкой через Shell, проходит нормально.

    Может кто сталкивался с подобным?

Ответы

  • Добрый день.

    Получилось.

    >>А пробовали удалять: «C:ProgramDataMicrosoftWindowsAppRepositoryedb.log» ?

    >>Наверное легче всего все же будет, удалить полностью VS и установить среду заново.

    Не стоит делать ни первое ни второе.

    А ответы следует искать в этом документе — «http://winitpro.ru/index.php/2015/07/30/kak-udalit-sovremennye-prilozheniya-v-windows-10/».

    Вот уж не думал что ситуация в ОС будет влиять на VS. Немного проектировщики системы не продумали. Или просто разные команды над VS и ОС работали, и координации между ними — НОЛЬ.

    • Помечено в качестве ответа

      29 августа 2016 г. 10:43

    • Изменено
      Sergej__
      29 августа 2016 г. 12:33

  • Remove From My Forums
  • Вопрос

  • После ввода логина и пароля в OWA возникает ошибка:

    Ошибка сервера в приложении '/owa'.
    
    ".", шестнадцатеричное значение 0x00, является недопустимым знаком., строка 1, позиция 1.
    
    Описание: Необработанное исключение при выполнении текущего веб-запроса. Изучите трассировку стека для получения дополнительных сведений о данной ошибке и о вызвавшем ее фрагменте кода. 
    
    Сведения об исключении: System.Xml.XmlException: ".", шестнадцатеричное значение 0x00, является недопустимым знаком., строка 1, позиция 1.
    
    Ошибка источника: 
    
    Необработанное исключение при выполнении текущего веб-запроса. Информацию о происхождении и месте возникновения исключения можно получить, используя следующую трассировку стека исключений.
    
    Трассировка стека: 
    
    
    [XmlException: ".", шестнадцатеричное значение 0x00, является недопустимым знаком., строка 1, позиция 1.]
       System.Xml.XmlTextReaderImpl.Throw(String res, String[] args) +163
       System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() +7420178
       System.Xml.XmlTextReaderImpl.ParseDocumentContent() +1027
       System.Xml.XmlReader.ReadToFollowing(String name) +112
       Microsoft.Exchange.Data.ApplicationLogic.Extension.KillBitHelper.ReadKillBitXmlContent(XmlReader reader, Int32& refreshRate) +185
       Microsoft.Exchange.Data.ApplicationLogic.Extension.KillBitHelper.TryReadKillBitFile(Int32& refreshRate, DateTime& lastModifiedTime) +661
       Microsoft.Exchange.Data.ApplicationLogic.Extension.KillBitTimer.Start() +193
       Microsoft.Exchange.Clients.Owa2.Server.Core.OwaApplication.Initialize() +485
       Microsoft.Exchange.Clients.Owa2.Server.Core.BaseApplication.ExecuteApplicationStart(Object sender, EventArgs e) +1319
    
    [HttpException (0x80004005): ".", шестнадцатеричное значение 0x00, является недопустимым знаком., строка 1, позиция 1.]
       System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +12582201
       System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +175
       System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304
       System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +404
       System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +475
    
    [HttpException (0x80004005): ".", шестнадцатеричное значение 0x00, является недопустимым знаком., строка 1, позиция 1.]
       System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12599232
       System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
       System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12438981
    
    Информация о версии: Платформа Microsoft .NET Framework, версия:4.0.30319; ASP.NET, версия:4.0.30319.33440

    Ранее все работало стабильно. Установлен Exchange 2013. С чем это может быть связано, как решить данную проблему?

Ответы

  • Добрый день!

    Думаю, у Вас не установлены обновления на Exchange.

    Установка CU1 помогла людям с данной проблемой. 

    Или напишите какие установлены.

    С чем это связано…  А после чего перестала работать? Кто что поменял?

    • Помечено в качестве ответа

      9 июня 2014 г. 10:56

Без ваших фактических данных или источника нам будет трудно диагностировать, что происходит не так. Тем не менее, я могу сделать несколько предложений:

  • Unicode NUL (0x00) является недопустимым во всех версиях XML, и проверяющие синтаксические анализаторы должны отклонять ввод, содержащий его.
  • Несмотря на вышесказанное; реальный непроверенный XML может содержать любой мусор, неправильный формат байтов, который только можно вообразить.
  • XML 1.1 допускает использование непечатаемых управляющих символов нулевой ширины (кроме NUL), поэтому вы не можете просмотреть файл XML 1.1 в текстовом редакторе и определить, какие символы он содержит.

Учитывая то, что вы написали, я подозреваю, что все, что преобразует данные базы данных в XML, не работает; он распространяет символы, отличные от XML.

Создайте несколько записей базы данных с символами, отличными от XML (NUL, DEL, управляющие символы и т. д.), и запустите на них свой конвертер XML. Выведите XML в файл и просмотрите его в шестнадцатеричном редакторе. Если он содержит символы, отличные от XML, ваш преобразователь неисправен. Исправьте это или, если не можете, создайте препроцессор, который отклоняет вывод с такими символами.

Если выходные данные преобразователя выглядят хорошо, проблема заключается в вашем потребителе XML; он где-то вставляет символы, отличные от XML. Вам придется разбить процесс потребления на отдельные этапы, изучить результаты на каждом этапе и сузить круг того, что представляет собой плохие символы.

Проверить кодировку файла (для UTF-16)

Обновление: я сам только что столкнулся с примером этого! Происходило то, что производитель кодировал XML как UTF16, а потребитель ожидал UTF8. Поскольку UTF16 использует 0x00 в качестве старшего байта для всех символов ASCII, а UTF8 — нет, потребитель видел каждый второй байт как NUL. В моем случае я мог бы изменить кодировку, но предложил, чтобы все полезные данные XML начинались со спецификации.

Я создаю XML-документ из StringBuilder, в основном что-то вроде:

string.Format("<text><row>{0}</row><col>{1}</col><textHeight>{2}</textHeight><textWidth>{3}</textWidth><data>{4}</data><rotation>{5}</rotation></text>

Позже, что-то вроде:

XmlDocument document = new XmlDocument();
document.LoadXml(xml);
XmlNodeList labelSetNodes = document.GetElementsByTagName("labels");
for (int index = 0; index < labelSetNodes.Count; index++)
{
//do something
}

Все данные поступают из базы данных.
Недавно у меня было несколько проблем с ошибкой:

Шестнадцатеричное значение 0x00 является недопустимым символом, строка 1, позиция nnnnn

Но его непротиворечивость.
Иногда некоторые «пустые» данные будут работать.
«Ошибочные» данные работают на некоторых ПК, но не на других.

В базе данных данные всегда являются пустой строкой. Это никогда не «null»
и в XML файле он отображается как < data>< /data>, то есть символ между открытием и закрытием. (но не уверен, что на это можно положиться, поскольку я вытаскиваю его из окна «немедленного», это vis studio и вставка его в текстовую панель).

Возможно, существуют различия в версиях sql-сервера (в 2008 году это будет неудачно, 2005 год будет работать) и сортировки.
Не уверены, что это может быть причиной?

Но точно так же код и данные будут иногда терпеть неудачу. Любые идеи, в которых проблема?

Без ваших фактических данных или источника нам будет сложно диагностировать, что происходит неправильно. Однако я могу сделать несколько предложений:

    Unicode NUL (0x00) является незаконным во всех версиях XML, и проверяющие синтаксические анализаторы должны отклонять ввод, содержащий его.
    Несмотря на вышеизложенное; реальный неаудированный XML-код может содержать любой вид неправильных форматов мусора, которые можно вообразить.
    XML 1.1 допускает нулевые и непечатаемые управляющие символы (кроме NUL), поэтому вы не можете посмотреть файл XML 1.1 в текстовом редакторе и сообщить, какие символы он содержит.

Учитывая то, что вы написали, я подозреваю, что все преобразования данных базы данных в XML нарушены; он распространяет не-XML-символы.

Создайте несколько записей базы данных с не-XML-символами (NUL, DEL, управляющие символы и т.д.) и запустите на нем свой XML-конвертер. Выведите XML в файл и посмотрите на него в шестнадцатеричном редакторе. Если это содержит символы, отличные от XML, ваш конвертер не работает. Исправьте его или, если вы не можете, создадите препроцессор, который отклоняет вывод с такими символами.

Если выход преобразователя выглядит хорошо, проблема в вашем XML-потребителе; он где-то вставляет символы, отличные от XML. Вам придется разбить свой процесс потребления на отдельные этапы, изучить выход на каждом шаге и сузить, что представляет плохие символы.

Обновление: я просто столкнулся с этим примером! Случилось то, что производитель кодировал XML как UTF16, и потребитель ожидал UTF8. Поскольку UTF16 использует 0x00 в качестве старшего байта для всех символов ASCII, а UTF8 — нет, потребитель просматривал каждый второй байт как NUL. В моем случае я мог бы изменить кодировку, но предложил, чтобы все полезные данные XML начинались с спецификации.

В моем случае это потребовало некоторого рытья, но нашло его.

Мой контекст

Я просматриваю журналы ошибок/ошибок с веб-сайта, используя Elmah. Elmah возвращает состояние сервера в момент исключения, в виде большого XML-документа. Для нашего механизма отчетности я довольно хорошо печатаю XML с XmlWriter.

Во время атаки на веб-сайт я заметил, что некоторые xmls не анализируются и получают это исключение '.', hexadecimal value 0x00, is an invalid character..

НЕРАЗРЕШЕНИЕ: Я преобразовал документ в byte[] и очистил его от 0x00, но не нашел его.

Когда я просмотрел XML-документ, я нашел следующее:

...
<form>
...
<item name="SomeField">
<value
string="C:boot.ini.htm" />
</item>
...

Был nul-байт, закодированный как объект html !!!

РАЗРЕШЕНИЕ:. Чтобы исправить кодировку, я заменил значение перед загрузкой в ​​мой XmlDocument, потому что при загрузке он создаст нулевой байт, и его будет трудно дезинфицировать из объект. Здесь весь мой процесс:

XmlDocument xml = new XmlDocument();
details.Xml = details.Xml.Replace("", "[0x00]"); // in my case I want to see it, otherwise just replace with ""
xml.LoadXml(details.Xml);

string formattedXml = null;

// I have this in a helper function, but for this example I have put it in-line
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
OmitXmlDeclaration = true,
Indent = true,
IndentChars = "t",
NewLineHandling = NewLineHandling.None,
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
xml.Save(writer);
formattedXml = sb.ToString();
}

LESSON LEARNED: санировать за незаконные байты с помощью связанного объекта html, если ваши входящие данные кодируются html при записи.

Чтобы добавить к Sonz ответ выше, мы работаем для нас.

//Instead of 
XmlString.Replace("", "[0x00]");
// use this
XmlString.Replace("x00", "[0x00]");

Я также получаю ту же ошибку в приложении ASP.NET, когда я сохранил некоторые данные Unicode (хинди) в файле Web.config и сохранил его с кодировкой «Unicode».

Он исправил ошибку для меня, когда я сохранил файл Web.config с кодировкой «UTF-8».

В качестве своего рода позднего ответа:

У меня возникла проблема с SSRS ReportService2005.asmx при загрузке отчета.

    Public Shared Sub CreateReport(ByVal strFileNameAndPath As String, ByVal strReportName As String, ByVal strReportingPath As String, Optional ByVal bOverwrite As Boolean = True)
Dim rs As SSRS_2005_Administration_WithFOA = New SSRS_2005_Administration_WithFOA
rs.Credentials = ReportingServiceInterface.GetMyCredentials(strCredentialsURL)
rs.Timeout = ReportingServiceInterface.iTimeout
rs.Url = ReportingServiceInterface.strReportingServiceURL
rs.UnsafeAuthenticatedConnectionSharing = True

Dim btBuffer As Byte() = Nothing

Dim rsWarnings As Warning() = Nothing
Try
Dim fstrStream As System.IO.FileStream = System.IO.File.OpenRead(strFileNameAndPath)
btBuffer = New Byte(fstrStream.Length - 1) {}
fstrStream.Read(btBuffer, 0, CInt(fstrStream.Length))
fstrStream.Close()
Catch ex As System.IO.IOException
Throw New Exception(ex.Message)
End Try

Try
rsWarnings = rs.CreateReport(strReportName, strReportingPath, bOverwrite, btBuffer, Nothing)

If Not (rsWarnings Is Nothing) Then
Dim warning As Warning
For Each warning In rsWarnings
Log(warning.Message)
Next warning
Else
Log("Report: {0} created successfully with no warnings", strReportName)
End If

Catch ex As System.Web.Services.Protocols.SoapException
Log(ex.Detail.InnerXml.ToString())
Catch ex As Exception
Log("Error at creating report. Invalid server name/timeout?" + vbCrLf + vbCrLf + "Error Description: " + vbCrLf + ex.Message)
Console.ReadKey()
System.Environment.Exit(1)
End Try
End Sub ' End Function CreateThisReport

Проблема возникает, если вы выделяете массив байтов, который по крайней мере на 1 байт больше, чем файл RDL (XML).

В частности, я использовал конвертер С# в vb.net, который преобразовал

  btBuffer = new byte[fstrStream.Length];

в

  btBuffer = New Byte(fstrStream.Length) {}

Но поскольку в С# число обозначает NUMBER OF ELEMENTS в массиве, а в VB.NET это число обозначает UPPER BOUND массива, у меня был избыточный байт, вызывающий эту ошибку.

Итак, решение проблемы просто:

  btBuffer = New Byte(fstrStream.Length - 1) {}

Я использую IronPython здесь (так же, как .NET API) и читаю файл как UTF-8, чтобы правильно обрабатывать спецификацию, исправил проблему для меня:

xmlFile = Path.Combine(directory_str, 'file.xml')
doc = XPathDocument(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))

Он будет работать также с XmlDocument:

doc = XmlDocument()
doc.Load(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))

Введите минимум 50 символов

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Шерхан 9 fail ошибка на брелке
  • Шестеро глаз уставились на меня ошибка