Меню

Ошибка получения объекта com 2147221021 0x800401e3 операция недоступна

Я
   IKSparrow

02.06.14 — 16:08

Код такой:

    Попытка

        Коннектор = ПолучитьCOMОбъект(Объект.ИмяФайла);

    Исключение

        ЗаписьЖурналаРегистрации(

            «#COM»,

            УровеньЖурналаРегистрации.Ошибка,

            ЭтотОбъект,

            «Коннектор = ПолучитьCOMОбъект(Объект.ИмяФайла): «+Объект.ИмяФайла,

            ОписаниеОшибки());

        Возврат;

    КонецПопытки;

Ошибка такая: Ошибка получения объекта COM: -2147221014(0x800401EA): Не удается открыть файл при помощи специального имени

Платформа вот такая: 8.3.4.482

Где ошибка?

   1cVandal

1 — 02.06.14 — 16:11

Объект.ИмяФайла что там?

   IKSparrow

2 — 02.06.14 — 16:11

(1) D:Книга1.xls

   1cVandal

3 — 02.06.14 — 16:14

Коннектор = ПолучитьCOMОбъект(Объект.ИмяФайла,»Excel.Application»);

а так?

   1cVandal

4 — 02.06.14 — 16:15

да и прежде чем его обрабатывать,попробуй закрой его

   IKSparrow

5 — 02.06.14 — 16:16

(3) Неа, теперь так Ошибка получения объекта COM: -2147221005(0x800401F3): Недопустимая строка с указанием класса. Вроде же всю жизнь было Excel.Application.

   salvator

6 — 02.06.14 — 16:20

(5) Эксель не установлен?

   1cVandal

7 — 02.06.14 — 16:20

(5) а он у тебя установлен? может код на сервере выполняется?

   IKSparrow

8 — 02.06.14 — 16:24

(6) Excel установлен.

Балин…. Ну да… В процедуре формы с директивой &НаСервере

   IKSparrow

9 — 02.06.14 — 16:25

А на сервере Excel’я нет. А у меня тонкий клиент. Стало быть мне только Excel на сервак ставить и без вариантов, да?

   RomaH

10 — 02.06.14 — 16:27

(9) почему? — читаешь таблицу на клиенте

пишешь её в формат 1С — любая коллекция

передаешь её на сервер

   IKSparrow

11 — 02.06.14 — 16:32

(10) ТЬфу, не в тот раздел СП посмотрел и не на тот метод «ПолучитьCOMОбъект» =)))

Всем спасибо =)

   IKSparrow

12 — 02.06.14 — 16:33

Ну вот же гадство. Теперь Ошибка в получении объекта COM (0x80004002) Интерфейс не поддерживается. Что за фигня.

   IKSparrow

13 — 02.06.14 — 16:34

Процедура теперь на клиенте выполняется.

  

1cVandal

14 — 02.06.14 — 17:00

наКлиенте

Режим = РежимДиалогаВыбораФайла.Открытие;

    ДиалогОткрытияФайла = Новый ДиалогВыбораФайла(Режим);

    ДиалогОткрытияФайла.ПолноеИмяФайла = «»;

    Фильтр = «Таблица(*.xlsx)|*.xlsx»;

    ДиалогОткрытияФайла.Фильтр                = Фильтр;

    ДиалогОткрытияФайла.МножественныйВыбор    = Ложь;

    ДиалогОткрытияФайла.Заголовок            = «Выберите файл c описью вложения»;

    
    Если ДиалогОткрытияФайла.Выбрать() Тогда

        ПутьКФайлу = ДиалогОткрытияФайла.ПолноеИмяФайла;

    Иначе

        Возврат;

    КонецЕсли;

    
    Тз = объект.ТЗ;

    Тз.Очистить();

    //Тз.Колонки.Добавить(«ШК»);

    //Тз.Колонки.Добавить(«Сумма»);

    
    
    
    Попытка

        Excel = Новый COMОбъект(«Excel.Application»);

        Excel.WorkBooks.Open(ПутьКФайлу);

        ExcelЛист = Excel.Sheets(1);

    Исключение

        Сообщить(«Не установлено приложение MS Excel!»);

        Возврат;

    КонецПопытки;

TurboConf — расширение возможностей Конфигуратора 1С

ВНИМАНИЕ! Если вы потеряли окно ввода сообщения, нажмите Ctrl-F5 или Ctrl-R или кнопку «Обновить» в браузере.

Тема не обновлялась длительное время, и была помечена как архивная. Добавление сообщений невозможно.
Но вы можете создать новую ветку и вам обязательно ответят!
Каждый час на Волшебном форуме бывает более 2000 человек.

i am try to hook to outlook application from windows Service but getting an exception Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE)) here is my code.

   public void ItemSendEvent()
    {
        try
        {
           if (Process.GetProcessesByName(ApplicationConstants.OUTLOOK_PROCESS_NAME).Count() > 0)
                {
                    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                    outlookApplication = Marshal.GetActiveObject(ApplicationConstants.OUTLOOK_APPLICATION_NAME) as Microsoft.Office.Interop.Outlook.Application;
                    Microsoft.Office.Interop.Outlook.NameSpace nameSpace = outlookApplication.GetNamespace(ApplicationConstants.OUTLOOK_NAME_SPACE);
                    nameSpace.Logon("", "", Missing.Value, Missing.Value);
                    nameSpace = null;
                    outlookApplication.ItemSend += outlookApplication_ItemSend;
                }
                log.Info("Outlook Item Send event registered successfully.");
        }
        catch (System.Exception ex)
        {
            log.Error("Exception occurred while registering Outlook Item Send event. " + ex.Message);
        }
    }

but the same code when i launch it through Windows Form Application its working Fine. i gone through some site’s and they were saying that outlook object is not in ROT Table. what will be the solution.

asked Jun 2, 2016 at 10:58

Ravi Kanth's user avatar

0

Outlook, or any other Office app, cannot run in a Windows service even if your service is running as an interactive user. Only Extended MAPI (C++ or Delphi only) or an Extended MAPI wrapper like Redemption (I am its author — its RDO family objects) can be used in a service.

In your particular case, it looks like you are trying to trap the Application.ItemSend event. There is absolutely no reason to create a Windows service for that. Create a COM addin — it will be loaded by Outlook and run as long as Outlook itself is running in the same process in the same security context.

answered Jun 2, 2016 at 22:45

Dmitry Streblechenko's user avatar

4

Two common issues could cause this.

The first would be that you are running Visual Studio in Administrator mode and you are starting your program from within VS, and the Office application is not. To fix that, you need to run your Office application with elevated privileges, in Administrator mode, as well.

The second could be caused by the application not being fully started/loaded when you call Marshal.GetActiveObject(...).

answered Jun 2, 2016 at 11:14

gmiley's user avatar

gmileygmiley

6,4561 gold badge11 silver badges24 bronze badges

3

Old, but still significant thread.

I collided with this error when tried to access Outlook data using the MS example.

Treating the error in a Try / Catch block and offering the option of newing Outlook solves the problem:

const int ERROR_HRESULT_0x800401E3_MK_E_UNAVAILABLE= -2147221021;
        Outlook.Application application = null;
        // Check whether there is an Outlook process running.
        if (Process.GetProcessesByName("OUTLOOK").Any())
        {
            try
            {
                // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                }
            }
            catch (Exception ex)
            {
                //This is the branch where you can get correctly the current Outlook instance
                if (ex.HResult == ERROR_HRESULT_0x800401E3_MK_E_UNAVAILABLE)
                {
                    application = new Outlook.Application();
                }
            }
        }
        else
        {
            application = new Outlook.Application();
        }

Although the newing trick functions, no other Outlook instance is created, as Outlook behaves like a Singleton.

I only tested it with Office 365 64 bits installed.

answered Nov 15, 2020 at 15:44

Marcelo Scofano Diniz's user avatar

you don’t need to have your application as a service to get it on the background …

if your winform work well, just put your winform in background running on the systray for instance

answered Nov 8, 2016 at 21:11

bobzer's user avatar

bobzerbobzer

891 silver badge7 bronze badges

i am try to hook to outlook application from windows Service but getting an exception Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE)) here is my code.

   public void ItemSendEvent()
    {
        try
        {
           if (Process.GetProcessesByName(ApplicationConstants.OUTLOOK_PROCESS_NAME).Count() > 0)
                {
                    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                    outlookApplication = Marshal.GetActiveObject(ApplicationConstants.OUTLOOK_APPLICATION_NAME) as Microsoft.Office.Interop.Outlook.Application;
                    Microsoft.Office.Interop.Outlook.NameSpace nameSpace = outlookApplication.GetNamespace(ApplicationConstants.OUTLOOK_NAME_SPACE);
                    nameSpace.Logon("", "", Missing.Value, Missing.Value);
                    nameSpace = null;
                    outlookApplication.ItemSend += outlookApplication_ItemSend;
                }
                log.Info("Outlook Item Send event registered successfully.");
        }
        catch (System.Exception ex)
        {
            log.Error("Exception occurred while registering Outlook Item Send event. " + ex.Message);
        }
    }

but the same code when i launch it through Windows Form Application its working Fine. i gone through some site’s and they were saying that outlook object is not in ROT Table. what will be the solution.

asked Jun 2, 2016 at 10:58

Ravi Kanth's user avatar

0

Outlook, or any other Office app, cannot run in a Windows service even if your service is running as an interactive user. Only Extended MAPI (C++ or Delphi only) or an Extended MAPI wrapper like Redemption (I am its author — its RDO family objects) can be used in a service.

In your particular case, it looks like you are trying to trap the Application.ItemSend event. There is absolutely no reason to create a Windows service for that. Create a COM addin — it will be loaded by Outlook and run as long as Outlook itself is running in the same process in the same security context.

answered Jun 2, 2016 at 22:45

Dmitry Streblechenko's user avatar

4

Two common issues could cause this.

The first would be that you are running Visual Studio in Administrator mode and you are starting your program from within VS, and the Office application is not. To fix that, you need to run your Office application with elevated privileges, in Administrator mode, as well.

The second could be caused by the application not being fully started/loaded when you call Marshal.GetActiveObject(...).

answered Jun 2, 2016 at 11:14

gmiley's user avatar

gmileygmiley

6,4561 gold badge11 silver badges24 bronze badges

3

Old, but still significant thread.

I collided with this error when tried to access Outlook data using the MS example.

Treating the error in a Try / Catch block and offering the option of newing Outlook solves the problem:

const int ERROR_HRESULT_0x800401E3_MK_E_UNAVAILABLE= -2147221021;
        Outlook.Application application = null;
        // Check whether there is an Outlook process running.
        if (Process.GetProcessesByName("OUTLOOK").Any())
        {
            try
            {
                // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                }
            }
            catch (Exception ex)
            {
                //This is the branch where you can get correctly the current Outlook instance
                if (ex.HResult == ERROR_HRESULT_0x800401E3_MK_E_UNAVAILABLE)
                {
                    application = new Outlook.Application();
                }
            }
        }
        else
        {
            application = new Outlook.Application();
        }

Although the newing trick functions, no other Outlook instance is created, as Outlook behaves like a Singleton.

I only tested it with Office 365 64 bits installed.

answered Nov 15, 2020 at 15:44

Marcelo Scofano Diniz's user avatar

you don’t need to have your application as a service to get it on the background …

if your winform work well, just put your winform in background running on the systray for instance

answered Nov 8, 2016 at 21:11

bobzer's user avatar

bobzerbobzer

891 silver badge7 bronze badges

  • Remove From My Forums
  • Question

  • I am trying to access Microsoft word instance through my service (windows service) but I am getting this error

    Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE)) ,

     I have opened word document ( i can also see WINWORD.EXE in Task Manager) ,

    I am using VS 2010 and MS Office 2003. Here is my code

    Dim fs As New FileStream("D:log.txt", FileMode.OpenOrCreate,
    FileAccess.Write)
    
                Dim sw As
    New StreamWriter(fs)
    
               
    sw.BaseStream.Seek(0, SeekOrigin.End)
    
                Dim
    wordapp As Word.Application
    
                wordapp = Marshal.GetActiveObject("Microsoft.Office.Interop.Word.Application")
    
                For Each
    doc As Word.Document In wordapp.Documents
    
                   
    sw.WriteLine(doc.FullName.ToString() + "n" +
    
                   
    doc.ActiveWindow.WindowState.ToString())
    
                Next
    
                sw.Flush()
    
                sw.Close()

    if i use this code in windows form application it works perfect, but doesn’t works in windows service.Why is that for ? Windows Service Doesn’t support Microsoft.Office.Interop ? If it does work please guide.

    • Moved by

      Tuesday, February 26, 2013 9:58 AM

Answers

  • As Ken mentioned — this is not supported so do not expect any real help for this on Microsoft forum. That said, ProgId you pass to Marshal.GetActiveObject is wrong, fix this.

    • Marked as answer by
      Quist Zhang
      Tuesday, March 5, 2013 10:53 AM

  • Even if you do succeed in somehow automating Word or another Office application in a Windows service it will break or fail at the worst possible moment. It’s just not relable, and if an error message or warning or other UI message
    is spawned that will hang your application compltely. What you want to do is really a very bad and unreliable thing to do.

    thanks,

    if Progid is wrong then why does this code works fine in windows form application ?


    Ken Slovak MVP — Outlook

    • Marked as answer by
      Quist Zhang
      Tuesday, March 5, 2013 10:53 AM

After searching on the web without success, here’s my question.

I’ve a task that i want to schedule to retrieve the attachment of an email from outlook and extract the data.
It works fine when I launch the task manually but whenever I try to launch it through a scheduled task it fails with the error :

COMException (0x800401E3): Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))

It occurs when the program tries to retrieve or create an instance of Outlook as follow:

private Application GetApplicationObject()
    {

        Application application = null;

        if (Process.GetProcessesByName("OUTLOOK").Any())
        {
            application = Marshal.GetActiveObject("Outlook.Application") as Application;
        }
        else
        {
            application = new Application();
        }
        return application;
    }

I tried several ways (batch file, .exe file, parameter from a program) but they all failed.
It was launched with the same account that was use to launch the task manually.

Can someone help me ? Any help would be appreciated!
Cheers!

asked Nov 5, 2015 at 12:05

A.Brg's user avatar

3

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.

You may consider using a low-level API (or any other third-party wrappers) — Extended MAPI on which Outlook is based on. Or EWS in case of Exchange profiles, see EWS Managed API, EWS, and web services in Exchange for more information.

answered Nov 5, 2015 at 12:27

Eugene Astafiev's user avatar

Eugene AstafievEugene Astafiev

41.6k3 gold badges21 silver badges39 bronze badges

1

Just a couple of thoughts:

  1. It could be a GUI issue. According to this answer, GUI tasks cannot be run from scheduled tasks. There may be a workaround, but I am not aware of one.

  2. It could be a context or permission issue. What settings are you configuring in the task, and are they the same as when you run the task outside of task scheduler?

Community's user avatar

answered Nov 5, 2015 at 12:26

theMayer's user avatar

theMayertheMayer

15.1k7 gold badges56 silver badges87 bronze badges

1

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

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

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

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка пользовательского интерфейса windows xp
  • Ошибка после замены аккумулятора iphone xs