Not a legal oleaut date ошибка

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

I am also receiving this error — Not a legal OleAut date.. —  with scheduled refresh only (on-demand refresh works fine).

mravestein — Can you please clarify the steps that you describe?

I went into desktop Power BI and changed the data type using the dropdown depicted below.

Power Bi - Data Type.png

Number options were: Decimal Number, Fixed Decimal Number, Whole Number — I tried a few different ones.

My field is actually date/time so I I changed it back to that.

a) Am I making the changes in the correct place

b) Which numeric data type should I choose

c) I am not clear what you mean by step #3 (Add another step in the Query editor)

I’m new to Power BI so I appreciate any assistance you can offer.

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

Error Message

In some instances, when using the Select Layer By Attribute tool on a layer imported from ArcGIS Online, or querying a feature in ArcGIS Pro, or attempting to open the attribute table of a feature class or a hosted feature service in ArcGIS Pro, the following error message is returned:

Error: 
Not a legal OleAut date.

Error message: Failed to load data. Error: Not a legal OleAut date.

Cause

This error occurs due to the following known causes:

  • The date fields are empty and do not read as null.
  • The date field values contain special characters, as shown in the image below.

Screenshot of the attribute table with the special character '?'

  • The table contains a datetime value that is earlier than midnight, January 1, 100 CE. ArcGIS Pro uses the Microsoft ToOADate method to access dates stored as datetime types. This method does not support date and time values earlier than midnight, January 1, 100.

Solution or Workaround

Depending on the cause, choose one of the methods provided to resolve the problem.

Note:
Perform the following workarounds in ArcMap if the error prompt disallows the editing of the attribute table in ArcGIS Pro.

Assign null values to the empty fields

Replace the empty field values with nulls. Refer to FAQ: Is it possible to assign nulls to a field using the Field Calculator? for more information.

Remove the special characters from the date field values

To remove special characters in the field value, double-click the cell, select the special characters, and press Delete on the keyboard. Optionally, set the empty field values to null. Refer to FAQ: Is it possible to assign nulls to a field using the Field Calculator? for steps to do so.

Correct or exclude dates earlier than January 1, 100

If the table contains datetime values earlier than midnight, January 1, 100, confirm that the values are valid and correct those that are not.  If all values are correct and you cannot make changes to the data, you can do one of the following to work with the table and avoid the error message:

  • Create a view of the table that excludes the datetime column. This allows viewing and querying the data in the view. However, you will not be able to access any of the date information (even those later than January 1, 100) nor can you edit the data.
  • Create a view that casts the date field to a string field. You’ll be able to view all the dates, but you won’t be able to perform date queries or edit.
  • Publish a map image layer and copy the data. Add the map image layer to Map Viewer to view and query the data. You’ll be able to view all the dates without error, but you cannot edit the data.
  • Remove From My Forums
  • Вопрос

  • Hello,

    I have a report that creates a chart.

    This report has been running fine for a while but today it generates an error on the chart «Not a legal OleAut Date».

    There is also a table onthis report, the table works. Furthermore, the development server also has the same report and there the report works well, no error.

    I do not see any difference between the two servers.

    Any idea?

    Update! This was a report converted from SQL2005 to SQL2008R2. The conversion was not seamless, I had to change a few things to get it to work again. It did work for a few weeks untill yesterday. I did the conversion all over again from
    a SQL2005 backup and I could repair it while I have no clue what went wrong. It is now working again. I just hope it will stay that way.


    Thanks/Regards, Philippe Cand

    • Изменено

      19 сентября 2010 г. 22:41
      Workaround

Понравилась статья? Поделить с друзьями:
  • Norton power eraser ошибка
  • Normaliz dll easy anti cheat ошибка
  • Normalemail dotm ошибка
  • Normal mode focus 3 что означает ошибка
  • Normal dotm ошибка word как исправить