Ошибка не является допустимой датой oleaut

Как это исправить? Привет! Вставьте ваши данные в фиктивную строку в строке 1 и вставьте столбцы, о которых идет речь, в строку (только в этом случае — это ошибка типа данных, поэтому примените исправление в соответствии с типом).

Необходимо понимать, что делает адаптер данных, который интерпретирует тип данных каждого столбца, исследуя по умолчанию первые 8 строк данных (без заголовка, если HDR=Yes в строке подключения) и выбирая тип данных (это можно переопределить — да, есть переопределение — в строке подключения до 16 строк — почти никогда не бывает очень полезно).

Адаптеры данных могут делать и другие неприятные вещи, например пропускать строки в столбцах со смешанными типами данных, например string/double (на самом деле это просто столбец строки, но не для адаптера, если все первые строки двойные). В этом примере вы даже не увидите ошибки.

Это часто происходит с данными, поступающими из источников ERP, которые содержат столбцы «произвольной формы». Определяемые пользователем столбцы — обычные подозреваемые. Это может быть очень сложно найти в проблемах с другими типами данных. Однажды я потратил довольно много времени на решение проблемы со столбцом, который был набран как строка с максимальной длиной 255 символов. Глубоко в данных были ячейки, которые превышали эту длину и выдавали ошибки.

Если вы не хотите продвигаться к уровню «генной инженерии» в работе с адаптерами данных, самый быстрый способ решить подобную проблему — это загрузить ваши данные и установить правильные значения столбцов, о которых идет речь. тип (или неправильный, который вы затем можете исправить в своем собственном коде, если это необходимо). План Б — вернуть данные клиенту / пользователю и попросить их исправить их. Удачи с планом Б. Есть причина, по которой это не план А.

Подробнее об управлении через строку подключения и аналогичных проблемах с адаптером — но будьте осторожны, результаты не будут на 100% надежными. Я тщательно тестировал изменение настроек IMEX и HDR. Если вы хотите быстро выполнить проект, привет! OleDB и смешанные типы данных Excel: недостающие данные

Вот еще один пост, похожий по контексту, обратите внимание на все возможные решения, требующие много времени. Мне еще предстоит убедиться, что есть лучшее решение, и оно просто противоречит логике, которую программист вводит в клавиатуру каждое утро. Жаль, у вас есть работа, иногда вам нужно быть хакером. Несоответствие формата даты и времени при импорте из таблицы Excel

How can you fix this? Hi!jack your data with a dummy row at row 1 and force the column(s) in question into a string (in this case only — it is a data type error, so apply the fix according to the type).

It is necessary to understand what the data adaptor does, which interprets the data type of each column by examining, by default, the first 8 rows of data (sans header if HDR=Yes in connect string) and deciding on a data type (it can be over-ridden -yes there is an override — in the connection string to 16 rows — almost never very helpful).

Data adaptors can do other nasty things, like skip strings in columns of mixed data types, like string/double (which is really just a string column, but not to the adaptor if the first rows are all double). It won’t even give you the courtesy of an error in this example.

This often occurs in data coming from ERP sources that contains «Free Form» columns. User defined columns are the usual suspects. It can be very difficult to find in other data type issues. I once spent quite a bit of time resolving an issue with a column that typed as a string with a max length of 255 chars. Deep in the data there were cells that exceeded that length and threw errors.

If you don’t want to advance to the level of «Genetic Engineering» in working with data adaptors, the fastest way to resolve an issue like this is to hi!jack your data and force the column(s) in question to the correct type (or incorrect, which you can then correct in your own code if need be). Plan B is to give the data back to the customer/user and tell them to correct it. Good luck with Plan B. There is a reason it isn’t Plan A.

More on manipulating via the connection string and similar issues with the adaptor — but be wary, results are not going to be 100% fool proof. I’ve tested changing IMEX and HDR settings extensively. If you want to get through the project quickly, hi!jack the data. OleDB & mixed Excel datatypes : missing data

Here is another posting similar in context, note all of the possible time consuming solutions. I have yet to be convinced there is a better solution, and it simply defies the logic a programmer brings to the keyboard every morning. Too bad, you have a job to do, sometimes you have to be a hack. DateTime format mismatch on importing from Excel Sheet

How can you fix this? Hi!jack your data with a dummy row at row 1 and force the column(s) in question into a string (in this case only — it is a data type error, so apply the fix according to the type).

It is necessary to understand what the data adaptor does, which interprets the data type of each column by examining, by default, the first 8 rows of data (sans header if HDR=Yes in connect string) and deciding on a data type (it can be over-ridden -yes there is an override — in the connection string to 16 rows — almost never very helpful).

Data adaptors can do other nasty things, like skip strings in columns of mixed data types, like string/double (which is really just a string column, but not to the adaptor if the first rows are all double). It won’t even give you the courtesy of an error in this example.

This often occurs in data coming from ERP sources that contains «Free Form» columns. User defined columns are the usual suspects. It can be very difficult to find in other data type issues. I once spent quite a bit of time resolving an issue with a column that typed as a string with a max length of 255 chars. Deep in the data there were cells that exceeded that length and threw errors.

If you don’t want to advance to the level of «Genetic Engineering» in working with data adaptors, the fastest way to resolve an issue like this is to hi!jack your data and force the column(s) in question to the correct type (or incorrect, which you can then correct in your own code if need be). Plan B is to give the data back to the customer/user and tell them to correct it. Good luck with Plan B. There is a reason it isn’t Plan A.

More on manipulating via the connection string and similar issues with the adaptor — but be wary, results are not going to be 100% fool proof. I’ve tested changing IMEX and HDR settings extensively. If you want to get through the project quickly, hi!jack the data. OleDB & mixed Excel datatypes : missing data

Here is another posting similar in context, note all of the possible time consuming solutions. I have yet to be convinced there is a better solution, and it simply defies the logic a programmer brings to the keyboard every morning. Too bad, you have a job to do, sometimes you have to be a hack. DateTime format mismatch on importing from Excel Sheet

Error Message

В некоторых случаях при использовании инструмента Выбрать в слое по атрибуту на слое, импортированном из ArcGIS Online, или при попытке открыть таблицу атрибутов класса пространственных объектов или размещенного сервиса объектов в ArcGIS Pro, возвращается следующее сообщение об ошибке:

Ошибка: недопустимая дата OleAut

Сообщение об ошибке: Не удалось загрузить данные. Ошибка: недопустимая дата OleAut

Cause

Эта ошибка возникает по следующим известным причинам:

  • Поля даты пусты и не читаются как null.
  • Значения поля даты содержат специальные символы, как показано на изображении ниже.

Скриншот таблицы атрибутов со специальным символом'?'

Solution or Workaround

В зависимости от причины, выберите один из указанных методов решения проблемы.

Примечание: Выполните следующие обходные пути в ArcMap, если сообщение об ошибке запрещает редактирование таблицы атрибутов в ArcGIS Pro.

Присвойте значения null пустым полям

Замените пустые значения поля на null. Обратитесь к FAQ: Можно ли присвоить полю значения null с помощью Калькулятора поля? для дополнительной информации.

Удалите специальные символы из значений поля даты

Чтобы удалить специальные символы из значения поля, дважды щелкните ячейку, выберите специальные символы и нажмите клавишу Удалить на клавиатуре. При желании установите для пустых полей значение null. Обратитесь к FAQ: Можно ли присвоить полю значения null с помощью Калькулятора поля?, чтобы понять, как это сделать.

Related Information

  • ArcGIS Online: Работа с полями дат
  • ArcGIS Pro: Поля дат
  • ArcGIS Pro: Поиск и Замена
  • ArcGIS Pro: Редактирование значения в ячейке таблицы

Last Published: 12/27/2022

Article ID: 000024929

Software: ArcGIS Online Current ArcGIS Pro 3.0.3, 3.0.2, 3.0.1, 3.0, 2.9.5, 2.9.4, 2.9.3, 2.9.2, 2.9.1, 2.9, 2.8.8, 2.8.7, 2.8.6, 2.8.5, 2.8.4, 2.8.3, 2.8.2, 2.8.1, 2.8, 2.7.7, 2.7.6, 2.7.5, 2.7.4, 2.7.3, 2.7.2, 2.7.1, 2.7, 2.4.3, 2.4.2, 2.4.1, 2.4, 2.3.3, 2.3.2, 2.3.1, 2.3, 2.2.4, 2.2.3, 2.2.2, 2.2.1, 2.2, 2.1.3, 2.1.2, 2.1.1, 2.1, 2.0.1, 2.0

Does anyone know what this means. Getting this in C# winforms applications:

Not a legal OleAut date

Reza Aghaei's user avatar

Reza Aghaei

117k17 gold badges192 silver badges377 bronze badges

asked Nov 22, 2008 at 1:35

leora's user avatar

1

It means that somewhere in the program is attempting to convert to or from an OLE Automation Date outside the valid range 1-January-4713 BC to 31-December-9999 AD. It might have slipped through because OLE Automation Dates are represented as a double.

Start by looking for any uses of the methods:

DateTime.FromOADate

DateTime.ToOADate

answered Nov 22, 2008 at 15:49

xyz's user avatar

xyzxyz

26.9k29 gold badges103 silver badges125 bronze badges

An OADate is represented as a double value whose value is the number of days from midnight on 30 december 1899 (negative values representing earlier dates).

This exception is thrown when trying to convert a value that is outside the valid range of Ole Automation dates to/from a .NET DateTime value (methods DateTime.FromOADate and DateTime.ToOADate — which are also used implicitly for COM Interop).

I believe to be valid for conversion to an OADate the .NET DateTime value needs to be strictly greater than 01/01/0100.

To convert from OADate to a .NET DateTime value, the double value needs to be strictly greater than -657435 (= 01/01/0100) and strictly less than 2958466.0 (01/01/10000).

answered Nov 22, 2008 at 15:50

Joe's user avatar

JoeJoe

120k30 gold badges200 silver badges332 bronze badges

It means you provided an invalid date somewhere, attempting to convert to or from an OLE Automation date outside the valid range 1-January-4713 BC to 31-December-9999 AD. A possible cause is that it might have slipped through because OLE Automation Dates are represented as a double.

Raymond Hettinger's user avatar

answered Nov 22, 2008 at 1:47

Robert Gamble's user avatar

Robert GambleRobert Gamble

105k25 gold badges145 silver badges137 bronze badges

3

Others have struggled with this. I suggest looking at these threads on DotNetNuke and DevShed.

answered Nov 22, 2008 at 14:57

bugmagnet's user avatar

bugmagnetbugmagnet

7,5617 gold badges66 silver badges126 bronze badges

I’ve used:

try
{
    if (folderItem.ModifyDate.Year != 1899)
    {
        this.FileModifiedDate = folderItem.ModifyDate.ToShortDateString() + 
            " " +
            folderItem.ModifyDate.ToLongTimeString();
    }
}
//we need this because it throws an exception if it's an invalid date...
catch (ArgumentException) { } 

to deal with the same problem I’m having. It throws the exception when we check the year in my case. Doing nothing on an invalid date is exactly the behavior I want, so this hack works.

Uwe Keim's user avatar

Uwe Keim

39k56 gold badges174 silver badges289 bronze badges

answered Dec 12, 2008 at 14:29

lc.'s user avatar

lc.lc.

112k20 gold badges157 silver badges185 bronze badges

What I found was that a column with a large row_id ‘257381195’ was attempting to be read by Excel as a Date. What I ended up doing was altering that column’s data to a string by preceding the row_id with a single quote. This resolved my issue. Hope this helps.

answered Nov 5, 2015 at 20:54

warren caulton's user avatar

Does anyone know what this means. Getting this in C# winforms applications:

Not a legal OleAut date

Reza Aghaei's user avatar

Reza Aghaei

117k17 gold badges192 silver badges377 bronze badges

asked Nov 22, 2008 at 1:35

leora's user avatar

1

It means that somewhere in the program is attempting to convert to or from an OLE Automation Date outside the valid range 1-January-4713 BC to 31-December-9999 AD. It might have slipped through because OLE Automation Dates are represented as a double.

Start by looking for any uses of the methods:

DateTime.FromOADate

DateTime.ToOADate

answered Nov 22, 2008 at 15:49

xyz's user avatar

xyzxyz

26.9k29 gold badges103 silver badges125 bronze badges

An OADate is represented as a double value whose value is the number of days from midnight on 30 december 1899 (negative values representing earlier dates).

This exception is thrown when trying to convert a value that is outside the valid range of Ole Automation dates to/from a .NET DateTime value (methods DateTime.FromOADate and DateTime.ToOADate — which are also used implicitly for COM Interop).

I believe to be valid for conversion to an OADate the .NET DateTime value needs to be strictly greater than 01/01/0100.

To convert from OADate to a .NET DateTime value, the double value needs to be strictly greater than -657435 (= 01/01/0100) and strictly less than 2958466.0 (01/01/10000).

answered Nov 22, 2008 at 15:50

Joe's user avatar

JoeJoe

120k30 gold badges200 silver badges332 bronze badges

It means you provided an invalid date somewhere, attempting to convert to or from an OLE Automation date outside the valid range 1-January-4713 BC to 31-December-9999 AD. A possible cause is that it might have slipped through because OLE Automation Dates are represented as a double.

Raymond Hettinger's user avatar

answered Nov 22, 2008 at 1:47

Robert Gamble's user avatar

Robert GambleRobert Gamble

105k25 gold badges145 silver badges137 bronze badges

3

Others have struggled with this. I suggest looking at these threads on DotNetNuke and DevShed.

answered Nov 22, 2008 at 14:57

bugmagnet's user avatar

bugmagnetbugmagnet

7,5617 gold badges66 silver badges126 bronze badges

I’ve used:

try
{
    if (folderItem.ModifyDate.Year != 1899)
    {
        this.FileModifiedDate = folderItem.ModifyDate.ToShortDateString() + 
            " " +
            folderItem.ModifyDate.ToLongTimeString();
    }
}
//we need this because it throws an exception if it's an invalid date...
catch (ArgumentException) { } 

to deal with the same problem I’m having. It throws the exception when we check the year in my case. Doing nothing on an invalid date is exactly the behavior I want, so this hack works.

Uwe Keim's user avatar

Uwe Keim

39k56 gold badges174 silver badges289 bronze badges

answered Dec 12, 2008 at 14:29

lc.'s user avatar

lc.lc.

112k20 gold badges157 silver badges185 bronze badges

What I found was that a column with a large row_id ‘257381195’ was attempting to be read by Excel as a Date. What I ended up doing was altering that column’s data to a string by preceding the row_id with a single quote. This resolved my issue. Hope this helps.

answered Nov 5, 2015 at 20:54

warren caulton's user avatar

Кто-нибудь знает что это значит. Получение этого в приложениях C # winforms:

Не официальная дата OleAut

6 ответы

Это означает, что где-то в программе выполняется попытка преобразования в дату OLE-автоматизации или обратно за пределы допустимого диапазона с 1 января 4713 года до н.э. до 31 декабря 9999 года нашей эры. Это могло произойти, потому что даты OLE-автоматизации представлены как двойной.

Начните с поиска возможных вариантов использования этих методов:

DateTime.FromOADate

DateTime.ToOADate

Создан 22 ноя.

OADate представлен как двойное значение, значение которого представляет собой количество дней от полуночи 30 декабря 1899 г. (отрицательные значения представляют более ранние даты).

Это исключение возникает при попытке преобразовать значение, выходящее за пределы допустимого диапазона дат Ole Automation, в / из значения .NET DateTime (методы DateTime.FromOADate и DateTime.ToOADate, которые также неявно используются для COM-взаимодействия).

Я считаю, что для преобразования в OADate значение .NET DateTime должно быть строго больше 01/01/0100.

Чтобы преобразовать из OADate в значение .NET DateTime, значение типа double должно быть строго больше -657435 (= 01/01/0100) и строго меньше 2958466.0 (01/01/10000).

Создан 22 ноя.

Другие боролись с этим. Предлагаю посмотреть эти темы на DotNetNuke и ДевШед.

Создан 22 ноя.

Я использовал:

try
{
    if (folderItem.ModifyDate.Year != 1899)
    {
        this.FileModifiedDate = folderItem.ModifyDate.ToShortDateString() + 
            " " +
            folderItem.ModifyDate.ToLongTimeString();
    }
}
//we need this because it throws an exception if it's an invalid date...
catch (ArgumentException) { } 

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

Создан 20 ноя.

Я обнаружил, что столбец с большим row_id «257381195» пытался прочитать Excel как дату. В итоге я преобразовал данные этого столбца в строку, поставив перед row_id одинарную кавычку. Это решило мою проблему. Надеюсь это поможет.

Создан 05 ноя.

Это означает, что вы где-то указали недопустимую дату, пытаясь преобразовать в дату OLE Automation или из нее за пределами допустимого диапазона с 1 января 4713 года до н.э. до 31 декабря 9999 года нашей эры. Возможная причина в том, что это могло произойти, потому что даты OLE-автоматизации представлены как двойные.

ответ дан 15 мар ’17, в 08:03

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

c#
winforms
datetime

or задайте свой вопрос.

7 / 7 / 2

Регистрация: 28.09.2012

Сообщений: 82

1

23.10.2012, 10:05. Показов 5061. Ответов 5


Здравствуйте!
на SQL сервере есть таблица, в ней поле Data тип float. Дата в данной колонке записана как 41183,259778136577
Если поместить в Excel и поставить формат ячейки = дата то все нормально Т.Е. дата будет вида 01.10.2012 6:14:05
Подскажите каким образом можно сделать так, что бы дата формата 41183,259778136577 отображалась в textBox1 как 01.10.2012 6:14:05 ????

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

0

Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

23.10.2012, 10:05

5

Tessen

713 / 680 / 126

Регистрация: 30.03.2012

Сообщений: 1,124

23.10.2012, 10:11

2

C#
1
textBox1.Text = DateTime.FromOADate(/*тут число*/).ToString();

1

6042 / 3451 / 335

Регистрация: 14.06.2009

Сообщений: 8,136

Записей в блоге: 2

23.10.2012, 10:20

3

seneka, я бы рекомендовал не заниматься ……, а сделать в БД столбец типа DateTime, сэкономишь множество нервных клеток

0

seneka

7 / 7 / 2

Регистрация: 28.09.2012

Сообщений: 82

23.10.2012, 10:42

 [ТС]

4

Цитата
Сообщение от nio
Посмотреть сообщение

seneka, я бы рекомендовал не заниматься ……, а сделать в БД столбец типа DateTime, сэкономишь множество нервных клеток

C радостью но нельзя..

Добавлено через 11 минут

Цитата
Сообщение от Tessen
Посмотреть сообщение

C#
1
textBox1.Text = DateTime.FromOADate(/*тут число*/).ToString();
C#
1
2
3
4
 private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = DateTime.FromOADate(41183,2597781365).ToString();
        }

Ошибка: Ни одна из перегрузок метода «FromOADate» не принимает «2» аргументов
Ну а если

C#
1
2
3
4
 private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = DateTime.FromOADate(411832597781365).ToString();
        }

При нажатии на кнопку выдает исключение Не является допустимой датой OleAut

0

nio

6042 / 3451 / 335

Регистрация: 14.06.2009

Сообщений: 8,136

Записей в блоге: 2

23.10.2012, 10:44

5

seneka, попробуй

C#
1
textBox1.Text = DateTime.FromOADate(41183.2597781365).ToString();

1

seneka

7 / 7 / 2

Регистрация: 28.09.2012

Сообщений: 82

23.10.2012, 10:53

 [ТС]

6

После всего проделанного получилось так

C#
1
2
3
4
5
private void button1_Click(object sender, EventArgs e)
        {
            double dataUPC = (Double)dataGridView1.CurrentRow.Cells[1].Value;
            textBox1.Text = DateTime.FromOADate(dataUPC).ToString();
        }

Спасибо Всем!!!

0

IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

23.10.2012, 10:53

Помогаю со студенческими работами здесь

Вывести список из метода. Ошибка Неявное преобразование типа «System.Collections.Generic.List<double>» в «double»
Добрый день.

Есть функция в библиотеке классов, расчеты в которой приводят к получению списка:

Ошибка при преобразование типа строки из консоли в double
Есть переменная типа double, ввожу её значение с консоли, сразу же выбивает ошибку. Как правильно…

Перегрузите метод f так, чтобы соответствовала виду static void f (double x, out double y)
ПОМОГИТЕ!! Выдаёт ошибку!
До передачи управления из текущего метода выходному параметру &quot;y&quot; должно…

Как сгенерировать случайное число типа я double имея на входе 2 числа типа double — минимальное и максимальное
Например:
public class ExtendedRandom : Random
{
public ExtendedRandom()

Создать структуру включающую в себя константу типа double, закрытое поле типа double
Помогите пожалуйста с заданием, создать структуру включающую в себя константу типа double, закрытое…

Перегрузите метод f так, чтобы его сигнатура соответствовала виду static void f (double x, out double y)
Как сделать метод, чтобы он соответствовал заданию?

class Program
{
static double…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

6

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

  • Дополнительные сведения: Не является допустимой датой OleAut.
    Всем доброго времени суток, вот такую ошибку я получаю при сборки проекта в 12 студии,
    в 15 таких проблем не было, если в классе убрать 
    public DateTime t_n { get; set; }
    public DateTime t_k { get; set; }
    , тогда ошибки исключения не возникает, с чем это может
    быть связанно ? как можно решить данную проблему на данной студии, всем большое спасибо за ваши ответы.

    Ниже  проект с данной проблемой:

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace TestF
    {
        public class test
        {
            public float resm { get; set; }
            public float[] resp { get; set; }
            public float[] result { get; set; }
            public str_pereval pereval { get; set; }
        };
    
    
    
        [StructLayout(LayoutKind.Sequential)]
        public class str_pereval                      //Класс данных валков
        {
            public int nk { get; set; } //Номер клети
            public int N_lower { get; set; } //Номер нижнего валка
            public int N_top { get; set; } //Номер верхнего валка
            public float d_lower { get; set; } //Диаметр нижнего валка 
            public float d_top { get; set; } //Диаметр верхнего валка
            public DateTime t_n { get; set; } //ДатаВремя перевалки
            public DateTime t_k { get; set; }
            public float L { get; set; } //Длина
            public float P { get; set; } //Вес в тоннах
            public float Pm { get; set; } //Вес в тоннах при прокате меньше 0.7мм
            public float Pp { get; set; } //Вес в тоннах при прокате больше либо равно 0.7 мм
            public float kal_n { get; set; }
            public float kal_v { get; set; }
            public float res_v { get; set; } //Ресурс валков
    
    
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            private float[] frez;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            private int[] irez;
    
            public float[] Frez { get { return frez; } }
            public int[] Irez { get { return irez; } }
            //  public test tester { get; set; }
        };
        public partial class MainWindow : Window
        {
            public ObservableCollection<test> List { get; private set; } 
            public ObservableCollection<str_pereval> List1 { get; private set; } 
            public MainWindow()
            {
                List  = new ObservableCollection<test>();
                List1 = new ObservableCollection<str_pereval>();
                InitializeComponent();
                DataContext = List;
            }
    
            private void button_Click(object sender, RoutedEventArgs e)
            {
                List.Clear();
                List1.Clear();
                int counter = 0;
                float[] res_val_m = new float[] { 2700, 2100, 1300, 1000, 30000, 30000, 30000, 20000 };
                float[] res_val_p = new float[] { 3500, 3000, 2200, 2000, 40000, 40000, 40000, 30000 };
                float[] objj = new float[8];
                float[] res_mm = new float[8];
                float[] res_pp = new float[8];
                using (var reader = new BinaryReader(File.OpenRead("fpereval.dat")))
                {
    
    
                    while (reader.BaseStream.Position != reader.BaseStream.Length)
                    {
    
                        var obj = ReadStruct<str_pereval>(reader);
                        var un = new test { pereval = obj, resm = res_mm[counter], resp = res_pp }; //, resm = res_mm[counter], resp = res_pp
                        if (counter < 4)
                            List.Add(un);
                        else
                            List1.Add(obj);
                        counter++;
                    }
                }
           /**/
            int j = 0;
                for (int i = 0; i< 4; i++)
                {
                    
                    objj[i] = 1 - (List[i].pereval.Pm / res_val_m[i]) - (List[i].pereval.Pp / res_val_p[i]);
                    if (objj[i] > 0)
                    {
                        res_mm[i] = res_val_m[i] * objj[i];
                        res_pp[i] = res_val_p[i] * objj[i];
                       
                    }
                    else
                    { res_mm[i] = 0; res_pp[i] = 0; }
    
    
    List.Add(new test { resm = res_mm[i], resp = res_pp, result = objj });
                }
             
                /**/
    
            }
    
            T ReadStruct<T>(BinaryReader reader) where T : class, new()
            {
                byte[] rawData = reader.ReadBytes(Marshal.SizeOf(typeof(T)));
                GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
                var returnObject = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
                handle.Free();
                return returnObject;
            }
        }
    }
    

    исключение в этой строке :

    var returnObject = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));

    Всем спасибо

Ответы

  • В общем то подобная проблема ожидаема при любой смене версий так как ваш код имеет ряд проблем.

    0. Такое использование структур опасно и нестабильно в целом. Для надежности замените весь этот код сохранением данных в XML или JSON формате. Это гарантирует переносимость и совместимость версий. 

    1. Нет никаких гарантий как именно будут расположены поля созданные компилятором для автоматических свойств. Уберите все автоматические свойства и замените их полями (можно private). Если надо добавьте свойства
    которые будут возвращать/устанавливать эти поля.

    2. Замените DateTime на конкретный формат используемый в источнике (например double) . Используйте свойство для преобразование в DateTime. Не используйте поля никаких типов кроме простейших (double, float, int и т.п.).

    3. Подумайте об использовании LayoutKind.Explicit и атрибутов FieldOffset.

    4. Добавьте тесты которые будут проверять правильность положения полей.

    Советы по работу с форумом:

    1. Терпение, терпение и еще раз терпение. Никаких «апов» в течении по меньшей мере недели.

    2. Одна тема — один вопрос.


    This posting is provided «AS IS» with no warranties, and confers no rights.

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

      16 декабря 2015 г. 18:50

Does anyone know what this means. Getting this in C# winforms applications:

Not a legal OleAut date

Reza Aghaei's user avatar

Reza Aghaei

119k17 gold badges198 silver badges388 bronze badges

asked Nov 22, 2008 at 1:35

leora's user avatar

1

It means that somewhere in the program is attempting to convert to or from an OLE Automation Date outside the valid range 1-January-4713 BC to 31-December-9999 AD. It might have slipped through because OLE Automation Dates are represented as a double.

Start by looking for any uses of the methods:

DateTime.FromOADate

DateTime.ToOADate

answered Nov 22, 2008 at 15:49

xyz's user avatar

xyzxyz

27.1k29 gold badges104 silver badges125 bronze badges

An OADate is represented as a double value whose value is the number of days from midnight on 30 december 1899 (negative values representing earlier dates).

This exception is thrown when trying to convert a value that is outside the valid range of Ole Automation dates to/from a .NET DateTime value (methods DateTime.FromOADate and DateTime.ToOADate — which are also used implicitly for COM Interop).

I believe to be valid for conversion to an OADate the .NET DateTime value needs to be strictly greater than 01/01/0100.

To convert from OADate to a .NET DateTime value, the double value needs to be strictly greater than -657435 (= 01/01/0100) and strictly less than 2958466.0 (01/01/10000).

answered Nov 22, 2008 at 15:50

Joe's user avatar

JoeJoe

122k30 gold badges203 silver badges336 bronze badges

It means you provided an invalid date somewhere, attempting to convert to or from an OLE Automation date outside the valid range 1-January-4713 BC to 31-December-9999 AD. A possible cause is that it might have slipped through because OLE Automation Dates are represented as a double.

Raymond Hettinger's user avatar

answered Nov 22, 2008 at 1:47

Robert Gamble's user avatar

Robert GambleRobert Gamble

106k25 gold badges145 silver badges137 bronze badges

3

Others have struggled with this. I suggest looking at these threads on DotNetNuke and DevShed.

answered Nov 22, 2008 at 14:57

bugmagnet's user avatar

bugmagnetbugmagnet

7,6017 gold badges67 silver badges128 bronze badges

I’ve used:

try
{
    if (folderItem.ModifyDate.Year != 1899)
    {
        this.FileModifiedDate = folderItem.ModifyDate.ToShortDateString() + 
            " " +
            folderItem.ModifyDate.ToLongTimeString();
    }
}
//we need this because it throws an exception if it's an invalid date...
catch (ArgumentException) { } 

to deal with the same problem I’m having. It throws the exception when we check the year in my case. Doing nothing on an invalid date is exactly the behavior I want, so this hack works.

Uwe Keim's user avatar

Uwe Keim

39.3k56 gold badges174 silver badges291 bronze badges

answered Dec 12, 2008 at 14:29

lc.'s user avatar

lc.lc.

113k20 gold badges158 silver badges186 bronze badges

What I found was that a column with a large row_id ‘257381195’ was attempting to be read by Excel as a Date. What I ended up doing was altering that column’s data to a string by preceding the row_id with a single quote. This resolved my issue. Hope this helps.

answered Nov 5, 2015 at 20:54

warren caulton's user avatar

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

  • Дополнительные сведения: Не является допустимой датой OleAut.
    Всем доброго времени суток, вот такую ошибку я получаю при сборки проекта в 12 студии,
    в 15 таких проблем не было, если в классе убрать 
    public DateTime t_n { get; set; }
    public DateTime t_k { get; set; }
    , тогда ошибки исключения не возникает, с чем это может
    быть связанно ? как можно решить данную проблему на данной студии, всем большое спасибо за ваши ответы.

    Ниже  проект с данной проблемой:

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace TestF
    {
        public class test
        {
            public float resm { get; set; }
            public float[] resp { get; set; }
            public float[] result { get; set; }
            public str_pereval pereval { get; set; }
        };
    
    
    
        [StructLayout(LayoutKind.Sequential)]
        public class str_pereval                      //Класс данных валков
        {
            public int nk { get; set; } //Номер клети
            public int N_lower { get; set; } //Номер нижнего валка
            public int N_top { get; set; } //Номер верхнего валка
            public float d_lower { get; set; } //Диаметр нижнего валка 
            public float d_top { get; set; } //Диаметр верхнего валка
            public DateTime t_n { get; set; } //ДатаВремя перевалки
            public DateTime t_k { get; set; }
            public float L { get; set; } //Длина
            public float P { get; set; } //Вес в тоннах
            public float Pm { get; set; } //Вес в тоннах при прокате меньше 0.7мм
            public float Pp { get; set; } //Вес в тоннах при прокате больше либо равно 0.7 мм
            public float kal_n { get; set; }
            public float kal_v { get; set; }
            public float res_v { get; set; } //Ресурс валков
    
    
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            private float[] frez;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            private int[] irez;
    
            public float[] Frez { get { return frez; } }
            public int[] Irez { get { return irez; } }
            //  public test tester { get; set; }
        };
        public partial class MainWindow : Window
        {
            public ObservableCollection<test> List { get; private set; } 
            public ObservableCollection<str_pereval> List1 { get; private set; } 
            public MainWindow()
            {
                List  = new ObservableCollection<test>();
                List1 = new ObservableCollection<str_pereval>();
                InitializeComponent();
                DataContext = List;
            }
    
            private void button_Click(object sender, RoutedEventArgs e)
            {
                List.Clear();
                List1.Clear();
                int counter = 0;
                float[] res_val_m = new float[] { 2700, 2100, 1300, 1000, 30000, 30000, 30000, 20000 };
                float[] res_val_p = new float[] { 3500, 3000, 2200, 2000, 40000, 40000, 40000, 30000 };
                float[] objj = new float[8];
                float[] res_mm = new float[8];
                float[] res_pp = new float[8];
                using (var reader = new BinaryReader(File.OpenRead("fpereval.dat")))
                {
    
    
                    while (reader.BaseStream.Position != reader.BaseStream.Length)
                    {
    
                        var obj = ReadStruct<str_pereval>(reader);
                        var un = new test { pereval = obj, resm = res_mm[counter], resp = res_pp }; //, resm = res_mm[counter], resp = res_pp
                        if (counter < 4)
                            List.Add(un);
                        else
                            List1.Add(obj);
                        counter++;
                    }
                }
           /**/
            int j = 0;
                for (int i = 0; i< 4; i++)
                {
                    
                    objj[i] = 1 - (List[i].pereval.Pm / res_val_m[i]) - (List[i].pereval.Pp / res_val_p[i]);
                    if (objj[i] > 0)
                    {
                        res_mm[i] = res_val_m[i] * objj[i];
                        res_pp[i] = res_val_p[i] * objj[i];
                       
                    }
                    else
                    { res_mm[i] = 0; res_pp[i] = 0; }
    
    
    List.Add(new test { resm = res_mm[i], resp = res_pp, result = objj });
                }
             
                /**/
    
            }
    
            T ReadStruct<T>(BinaryReader reader) where T : class, new()
            {
                byte[] rawData = reader.ReadBytes(Marshal.SizeOf(typeof(T)));
                GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
                var returnObject = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
                handle.Free();
                return returnObject;
            }
        }
    }
    

    исключение в этой строке :

    var returnObject = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));

    Всем спасибо

Ответы

  • В общем то подобная проблема ожидаема при любой смене версий так как ваш код имеет ряд проблем.

    0. Такое использование структур опасно и нестабильно в целом. Для надежности замените весь этот код сохранением данных в XML или JSON формате. Это гарантирует переносимость и совместимость версий. 

    1. Нет никаких гарантий как именно будут расположены поля созданные компилятором для автоматических свойств. Уберите все автоматические свойства и замените их полями (можно private). Если надо добавьте свойства
    которые будут возвращать/устанавливать эти поля.

    2. Замените DateTime на конкретный формат используемый в источнике (например double) . Используйте свойство для преобразование в DateTime. Не используйте поля никаких типов кроме простейших (double, float, int и т.п.).

    3. Подумайте об использовании LayoutKind.Explicit и атрибутов FieldOffset.

    4. Добавьте тесты которые будут проверять правильность положения полей.

    Советы по работу с форумом:

    1. Терпение, терпение и еще раз терпение. Никаких «апов» в течении по меньшей мере недели.

    2. Одна тема — один вопрос.


    This posting is provided «AS IS» with no warranties, and confers no rights.

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

      16 декабря 2015 г. 18:50

Я работаю с электронными таблицами Excel, и до сих пор у меня не было никаких проблем с ними. Но эта ошибка, «Не законная дата OleAut»., появилась неожиданно, когда я попытался прочитать файл excel. Кто-нибудь знает, как я могу это исправить. Вот код, который я использую, чтобы прочитать excel и поместить данные в набор данных. Он работал нормально, но после того, как я внес некоторые изменения (которые не связаны с датами) в источник данных, эта ошибка появилась.

var fileName = string.Format("C:\Drafts\Excel 97-2003 formats\All Data 09 26 2012_Edited.xls");
        var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

        var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);

        DataSet Originalds = new DataSet();
        adapter.Fill(Originalds, "Employees"); // this is where the error shows up

How can you fix this? Hi!jack your data with a dummy row at row 1 and force the column(s) in question into a string (in this case only — it is a data type error, so apply the fix according to the type).

It is necessary to understand what the data adaptor does, which interprets the data type of each column by examining, by default, the first 8 rows of data (sans header if HDR=Yes in connect string) and deciding on a data type (it can be over-ridden -yes there is an override — in the connection string to 16 rows — almost never very helpful).

Data adaptors can do other nasty things, like skip strings in columns of mixed data types, like string/double (which is really just a string column, but not to the adaptor if the first rows are all double). It won’t even give you the courtesy of an error in this example.

This often occurs in data coming from ERP sources that contains «Free Form» columns. User defined columns are the usual suspects. It can be very difficult to find in other data type issues. I once spent quite a bit of time resolving an issue with a column that typed as a string with a max length of 255 chars. Deep in the data there were cells that exceeded that length and threw errors.

If you don’t want to advance to the level of «Genetic Engineering» in working with data adaptors, the fastest way to resolve an issue like this is to hi!jack your data and force the column(s) in question to the correct type (or incorrect, which you can then correct in your own code if need be). Plan B is to give the data back to the customer/user and tell them to correct it. Good luck with Plan B. There is a reason it isn’t Plan A.

More on manipulating via the connection string and similar issues with the adaptor — but be wary, results are not going to be 100% fool proof. I’ve tested changing IMEX and HDR settings extensively. If you want to get through the project quickly, hi!jack the data. OleDB & mixed Excel datatypes : missing data

Here is another posting similar in context, note all of the possible time consuming solutions. I have yet to be convinced there is a better solution, and it simply defies the logic a programmer brings to the keyboard every morning. Too bad, you have a job to do, sometimes you have to be a hack. DateTime format mismatch on importing from Excel Sheet

7 / 7 / 2

Регистрация: 28.09.2012

Сообщений: 82

1

23.10.2012, 10:05. Показов 5297. Ответов 5


Студворк — интернет-сервис помощи студентам

Здравствуйте!
на SQL сервере есть таблица, в ней поле Data тип float. Дата в данной колонке записана как 41183,259778136577
Если поместить в Excel и поставить формат ячейки = дата то все нормально Т.Е. дата будет вида 01.10.2012 6:14:05
Подскажите каким образом можно сделать так, что бы дата формата 41183,259778136577 отображалась в textBox1 как 01.10.2012 6:14:05 ????



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

23.10.2012, 10:05

5

Tessen

713 / 680 / 126

Регистрация: 30.03.2012

Сообщений: 1,124

23.10.2012, 10:11

2

C#
1
textBox1.Text = DateTime.FromOADate(/*тут число*/).ToString();



1



6043 / 3452 / 335

Регистрация: 14.06.2009

Сообщений: 8,136

Записей в блоге: 2

23.10.2012, 10:20

3

seneka, я бы рекомендовал не заниматься ……, а сделать в БД столбец типа DateTime, сэкономишь множество нервных клеток



0



seneka

7 / 7 / 2

Регистрация: 28.09.2012

Сообщений: 82

23.10.2012, 10:42

 [ТС]

4

Цитата
Сообщение от nio
Посмотреть сообщение

seneka, я бы рекомендовал не заниматься ……, а сделать в БД столбец типа DateTime, сэкономишь множество нервных клеток

C радостью но нельзя..

Добавлено через 11 минут

Цитата
Сообщение от Tessen
Посмотреть сообщение

C#
1
textBox1.Text = DateTime.FromOADate(/*тут число*/).ToString();
C#
1
2
3
4
 private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = DateTime.FromOADate(41183,2597781365).ToString();
        }

Ошибка: Ни одна из перегрузок метода «FromOADate» не принимает «2» аргументов
Ну а если

C#
1
2
3
4
 private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = DateTime.FromOADate(411832597781365).ToString();
        }

При нажатии на кнопку выдает исключение Не является допустимой датой OleAut



0



nio

6043 / 3452 / 335

Регистрация: 14.06.2009

Сообщений: 8,136

Записей в блоге: 2

23.10.2012, 10:44

5

seneka, попробуй

C#
1
textBox1.Text = DateTime.FromOADate(41183.2597781365).ToString();



1



seneka

7 / 7 / 2

Регистрация: 28.09.2012

Сообщений: 82

23.10.2012, 10:53

 [ТС]

6

После всего проделанного получилось так

C#
1
2
3
4
5
private void button1_Click(object sender, EventArgs e)
        {
            double dataUPC = (Double)dataGridView1.CurrentRow.Cells[1].Value;
            textBox1.Text = DateTime.FromOADate(dataUPC).ToString();
        }

Спасибо Всем!!!



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

23.10.2012, 10:53

Помогаю со студенческими работами здесь

Вывести список из метода. Ошибка Неявное преобразование типа «System.Collections.Generic.List<double>» в «double»
Добрый день.

Есть функция в библиотеке классов, расчеты в которой приводят к получению списка:

Ошибка при преобразование типа строки из консоли в double
Есть переменная типа double, ввожу её значение с консоли, сразу же выбивает ошибку. Как правильно…

Перегрузите метод f так, чтобы соответствовала виду static void f (double x, out double y)
ПОМОГИТЕ!! Выдаёт ошибку!
До передачи управления из текущего метода выходному параметру &quot;y&quot; должно…

Как сгенерировать случайное число типа я double имея на входе 2 числа типа double — минимальное и максимальное
Например:
public class ExtendedRandom : Random
{
public ExtendedRandom()

Создать структуру включающую в себя константу типа double, закрытое поле типа double
Помогите пожалуйста с заданием, создать структуру включающую в себя константу типа double, закрытое…

Перегрузите метод f так, чтобы его сигнатура соответствовала виду static void f (double x, out double y)
Как сделать метод, чтобы он соответствовал заданию?

class Program
{
static double…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

6

I’m getting this error when a schduled refresh runs (it doesn’t error when manually refreshing). I’ve found the reason why this happens in this forum, e.g. ANSWERED QUESTION.

Data source error: Not a legal OleAut date.. The exception was raised by the IDataReader interface. Table: Manual Attendance Full.
Cluster URI: WABI-EUROPE-NORTH-B-redirect.analysis.windows.net
Activity ID: 452648da-2252-4845-88de-515b0dd58161
Request ID: 8a1ec65c-a4a4-4c79-bb04-62807acc2ecc
Time: 2019-02-12 07:24:10Z

The question is WHY and HOW is this an error. Dates before 1/1/1900 are more than valid, I don’t understand why Power BI would kick them out. And why Power BI would kick them out on a schduled refresh, of all things.

I’m purposefully displaying dates that are not 100% correct as this dashboard is to help us validate incorrect scans of documents.

Does anyone have a work around? I don’t want to lose the incorrect data as I need the entire dataset to be present.

Thank you,

Ken.

Понравилась статья? Поделить с друзьями:
  • Ошибка не является выпуском core
  • Ошибка не устранилась
  • Ошибка не устранена как пишется
  • Ошибка не установлен плагин госуслуги chrome
  • Ошибка не установлен плагин zakupki gov ru