Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.52/21: Рейтинг темы: голосов - 21, средняя оценка - 4.52
39 / 38 / 32
Регистрация: 24.11.2014
Сообщений: 352
1

Регистрация библиотеки как ActiveX

03.11.2018, 17:56. Показов 4265. Ответов 9
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Всем привет, есть проблема в регистрации простой библиотеки как COM компонента
я не понимаю в чем проблема.
Приведу код и сразу скажу делал как в справочнике msdn и как в codeproject
Дошло до того что при компиляции возникает ошибка вида :
Код
Error	The assembly "E:\Study\...\...\...\Std_Lib\Std_Lib\bin\Release\StudentX.dll" could not be converted to a type library. 
Type library exporter encountered an error while processing 'StudentX.TStudents, StudentX'. 
Error: Element not found.Std_Lib
Регистрацию библиотеки делал так же через консольку командой :
Код
C:\Windows\Microsoft.NET\Framework\v2.0.50727>regasm /codebase e:\StudentX.dll
(П.С. пути разные в Visual и в консольке потому что я переташил файлик в корень диска что бы небыло русских букв в пути специально)
Но там тоже выходит ошибка
Код
RegAsm : error RA0000 : Failed to load 'e:\StudentX.dll' because it is not a valid .NET assembly
Так же как и в описании написано в меню проекта нажал на галочку "Make Assembly COM-Visible"
Даже в видео это сказано
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
 
namespace StudentX
{
    [ClassInterface(ClassInterfaceType.AutoDual)]//Это тоже не очень понятно
    [Guid("b73a30cb-fb43-4ae3-97fc-92f60e17f0fd")]//это я так понимаю id Для реестра
    [ProgId("Student")]//Вот это я не понимаю зачем юзать
    [ComVisible(true)]//Это понятно 
    class Student
    {
 
        public Student() { }
        public Student( string[] _grades , string _name , string _secondName )
        {
            Name = _name;
            SecondName = _secondName;
            Grades = _grades;
        }
        [ComVisible(true)]
        public string[] Grades { get; set; }
        [ComVisible(true)]
        public string Name { get; set; }
        [ComVisible(true)]
        public string SecondName { get; set; }
        [ComVisible(true)]
        public string LastName { get; set; }
 
        [ComVisible(true)]
        public string GetTest()
        {
            return "Testing Student";
        }
        [ComVisible(true)]
        [ComRegisterFunction()]
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendFormat("| {0} {1} \n" , Name , SecondName);
            for ( int i = 0 ; i < Grades.GetLength(0) ; i++ )
                stringBuilder.AppendFormat("| {0}\n" , Grades[i]);
            return stringBuilder.ToString();
        }
    }
 
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [Guid("b73a30cb-fb43-4ae3-97fc-92f60e17f0fd")]
    [ProgId("TStudents")]
    [ComVisible(true)]
    public class TStudents
    {
        List<Student> Std_list = new List<Student>();
 
        public TStudents( string _folder )
        {
            if ( _folder != "" )
                foreach ( var item in Directory.GetFiles(_folder) )
                {
                    int size = File.ReadAllLines(item).Count();
                    string[] FIO = Path.GetFileNameWithoutExtension(item).Split(' ').ToArray();
                    string[] Grades = File.ReadAllLines(item);
 
                    Std_list.Add(new Student(Grades , FIO[0] , FIO[1]));
                }
        }
 
        [ComVisible(true)]
        public int Count
        {
            get { return Std_list.Count; }
        }
 
        [ComVisible(true)]
        internal Student this[int index]
        {
            get { return Std_list[index]; }
            set { Std_list[index] = value; }
        }
 
        [ComVisible(true)]
        [ComRegisterFunction()]
        public string GetTest()
        {
            return "Testing TStudents";
        }
        [ComVisible(true)]
        [ComRegisterFunction()]
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach ( Student item in Std_list )
                stringBuilder.AppendLine(item.ToString());
            stringBuilder.AppendFormat("+{0}+" , new string('-' , 30));
 
            return stringBuilder.ToString();
        }
    }
}
И сам Ассемблер файл может тоже поможет
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
 
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("StudentX")]
[assembly: AssemblyDescription("Active X Object")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Deimos Idustry")]
[assembly: AssemblyProduct("StudentX")]
[assembly: AssemblyCopyright("Copyright ©  2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
 
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]
 
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b73a30cb-fb43-4ae3-97fc-92f60e17f0fd")]
 
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
В чем проблема как Исправить эту ошибку либо в Визуалке либо через консольку????
Код
RegAsm : error RA0000 : Failed to load 'e:\StudentX.dll' because it is not a valid .NET assembly
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
03.11.2018, 17:56
Ответы с готовыми решениями:

Установочные регистрирующий библиотеки ActiveX
Добрый день, возможно ли стандартными средствами (используя visual studio у меня 2012)...

Регистрация библиотеки ActiveX DLL
Что-то у меня каша в голове образовалась, помогите понять основные моменты. Создана библиотека...

Регистрация библиотеки классов, как COM объекта и ее дальнейшее использование
Здравствуйте. Не уверен, что правильно выбрал секцию, поэтому поясню: библиотека классов написана...

регистрация ActiveX
Здравствуйте, срочно нужно зарегистрировать элемент ActiveX. Access97, он отказывается подключать -...

9
Эксперт .NET
17685 / 12871 / 3365
Регистрация: 17.09.2011
Сообщений: 21,137
03.11.2018, 18:56 2
Цитата Сообщение от Deimos_ Посмотреть сообщение
C:\Windows\Microsoft.NET\Framework\v2.0.50727>regasm
Смущает, что вы запускаете regasm из папки со второй версией фреймворка, а сама сборка скорее всего написана под четвертую или выше.
Попробуйте запускать его из соответствующей папки, а еще лучше — из командной строки Студии.
1
39 / 38 / 32
Регистрация: 24.11.2014
Сообщений: 352
04.11.2018, 12:33  [ТС] 3
К стати да что то я не то взял, списал как в гайде а он же древний, но теперь выходит другая ошибка

Код
C:\Windows\Microsoft.NET\Framework\v4.0.30319>regasm /codebase e:\StudentX.dll
Microsoft .NET Framework Assembly Registration Utility version 4.7.3062.0
for Microsoft .NET Framework version 4.7.3062.0
Copyright (C) Microsoft Corporation.  All rights reserved.

RegAsm : warning RA0000 : No types were registered
Добавлено через 5 минут
А в консольке студии я не знаю что печатать никогда не работал с ней
0
Эксперт .NET
17685 / 12871 / 3365
Регистрация: 17.09.2011
Сообщений: 21,137
04.11.2018, 12:39 4
Цитата Сообщение от Deimos_ Посмотреть сообщение
No types were registered
У вас в сборке два класса: Student с модификатором доступа internal и TStudents без конструктора по умолчанию.
Попробуйте пометить Student как public и добавить в TStudents конструктор без параметров.

Цитата Сообщение от Deimos_ Посмотреть сообщение
А в консольке студии я не знаю что печатать никогда не работал с ней
Печатайте то же самое, только без полного пути к программам — студия сама настроит среду выполнения с нужными папками.
0
39 / 38 / 32
Регистрация: 24.11.2014
Сообщений: 352
04.11.2018, 12:46  [ТС] 5
Сейчас пересоздал проект, скопировал и оставил атрибудты только у наследованного класса контейнера TStudents
Теперь компиляция(F6) прошла успешно но выдает ошибку при запуске программы на F5

Код
Error The assembly "E:\Study\..\..\StudentX\StudentX\bin\Debug\StudentX.dll" could not be converted to a type library. Type library exporter encountered an error while processing 'StudentX.TStudents, StudentX'. Error: Element not found.	StudentX
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Student
    {
 
        public Student() { }
        public Student( string[] _grades , string _name , string _secondName )
        {
            Name = _name;
            SecondName = _secondName;
            Grades = _grades;
        }
 
        public string[] Grades { get; set; }
 
        public string Name { get; set; }
 
        public string SecondName { get; set; }
 
        public string LastName { get; set; }
 
 
        public string GetTest()
        {
            return "Testing Student";
        }
 
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendFormat("| {0} {1} \n" , Name , SecondName);
            for ( int i = 0 ; i < Grades.GetLength(0) ; i++ )
                stringBuilder.AppendFormat("| {0}\n" , Grades[i]);
            return stringBuilder.ToString();
        }
    }
 
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [Guid("626aec8e-2eed-4f04-8931-3d0c53ad3863")]
    [ProgId("StudentX.TStudents")]
    [ComVisible(true)]
    public class TStudents
    {
        List<Student> Std_list = new List<Student>();
 
        public TStudents( string _folder )
        {
            if ( _folder != "" )
                foreach ( var item in Directory.GetFiles(_folder) )
                {
                    int size = File.ReadAllLines(item).Count();
                    string[] FIO = Path.GetFileNameWithoutExtension(item).Split(' ').ToArray();
                    string[] Grades = File.ReadAllLines(item);
 
                    Std_list.Add(new Student(Grades , FIO[0] , FIO[1]));
                }
        }
 
        [ComVisible(true)]
        public int Count
        {
            get { return Std_list.Count; }
        }
 
        [ComVisible(true)]
        internal Student this[int index]
        {
            get { return Std_list[index]; }
            set { Std_list[index] = value; }
        }
 
        [ComVisible(true)]
        [ComRegisterFunction()]
        public string GetTest()
        {
            return "Testing TStudents";
        }
        [ComVisible(true)]
        [ComRegisterFunction()]
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach ( Student item in Std_list )
                stringBuilder.AppendLine(item.ToString());
            stringBuilder.AppendFormat("+{0}+" , new string('-' , 30));
 
            return stringBuilder.ToString();
        }
    }
0
Эксперт .NET
17685 / 12871 / 3365
Регистрация: 17.09.2011
Сообщений: 21,137
04.11.2018, 12:49 6
Лучший ответ Сообщение было отмечено Deimos_ как решение

Решение

Deimos_, у вас класс TStudents использует тип Student, который невидим для COM.
Либо не используйте тип Student в TStudents, либо регистрируйте его тоже.
1
39 / 38 / 32
Регистрация: 24.11.2014
Сообщений: 352
04.11.2018, 13:23  [ТС] 7
Да сделал все публичным и создал конструктор по умолчанию для TStudents теперь он просит что бы классы были статичными сейчас с этим разберусь и возможно заработает
Код
..\..\Release\StudentX.dll". COM register function must be static.
Добавлено через 17 минут
Сейчас сдела статичные все методы и поля, и эмм после компиляции выходит ошибка
Код
StudentX.dll". COM register function must have a System.Type parameter and a void return type.
Что то я совсем запутался как себе это представляет Студия, Как это иметь тип Type а возвращать пустоту

Добавлено через 1 минуту
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
 
namespace StudentX
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [Guid("626aec8e-2eed-4f04-8931-3d0c53ad3863")]
    [ProgId("StudentX.Student")]
    [ComVisible(true)]
    public class Student
    {
 
        public Student() { }
        public Student( string[] _grades , string _name , string _secondName )
        {
            Name = _name;
            SecondName = _secondName;
            Grades = _grades;
        }
        [ComVisible(true)]
        public static string[] Grades { get; set; }
        [ComVisible(true)]
        public static string Name { get; set; }
        [ComVisible(true)]
        public static string SecondName { get; set; }
        [ComVisible(true)]
        public static string LastName { get; set; }
 
        [ComVisible(true)]
        [ComRegisterFunction()]
        public static string GetTest()
        {
            return "Testing Student";
        }
 
        [ComVisible(true)]
        [ComRegisterFunction()]
        public static string GetString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendFormat("| {0} {1} \n" , Name , SecondName);
            for ( int i = 0 ; i < Grades.GetLength(0) ; i++ )
                stringBuilder.AppendFormat("| {0}\n" , Grades[i]);
            return stringBuilder.ToString();
        }
    }
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [Guid("626aec8e-2eed-4f04-8931-3d0c53ad3863")]
    [ProgId("StudentX.TStudents")]
    [ComVisible(true)]
    public class TStudents
    {
        static List<Student> Std_list = new List<Student>();
 
        public TStudents() { }
        public TStudents( string _folder )
        {
            if ( _folder != "" )
                foreach ( var item in Directory.GetFiles(_folder) )
                {
                    int size = File.ReadAllLines(item).Count();
                    string[] FIO = Path.GetFileNameWithoutExtension(item).Split(' ').ToArray();
                    string[] Grades = File.ReadAllLines(item);
 
                    Std_list.Add(new Student(Grades , FIO[0] , FIO[1]));
                }
        }
 
        [ComVisible(true)]
        public int Count
        {
            get { return Std_list.Count; }
        }
 
        [ComVisible(true)]
        public Student this[int index]
        {
            get { return Std_list[index]; }
            set { Std_list[index] = value; }
        }
 
        [ComVisible(true)]
        [ComRegisterFunction()]
        public static string GetString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach ( Student item in Std_list )
                stringBuilder.AppendLine(item.ToString());
            stringBuilder.AppendFormat("+{0}+" , new string('-' , 30));
 
            return stringBuilder.ToString();
        }
    }
}
0
Эксперт .NET
17685 / 12871 / 3365
Регистрация: 17.09.2011
Сообщений: 21,137
04.11.2018, 13:23 8
Цитата Сообщение от Deimos_ Посмотреть сообщение
теперь он просит что бы классы были статичными
Не классы, а методы, помеченные атрибутом ComRegisterFunction.
Кстати, зачем они им помечены?
1
39 / 38 / 32
Регистрация: 24.11.2014
Сообщений: 352
04.11.2018, 13:49  [ТС] 9
Я незнаю зачем пометил но где то нашел и так сделал )

Добавлено через 3 минуты
Короче убрал все ComRegisterFunction вернул все наместо опять пришла эта ошибка
Error: Element not found. StudentX
хотя как вы и сказали я создал констуктор по умолчанию и сделал все публичным

Добавлено через 5 минут
Слава БОГАМ !!!
Код
C:\Windows\Microsoft.NET\Framework\v4.0.30319>RegAsm.exe e:\StudentX.dll
Microsoft .NET Framework Assembly Registration Utility version 4.7.3062.0
for Microsoft .NET Framework version 4.7.3062.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Types registered successfully
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
 
namespace StudentX
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ProgId("StudentX.Student")]
    [Guid("55DC203B-1A3C-4CA5-8162-6FFFD4183A2A")]
    [ComVisible(true)]
    public class Student
    {
 
        public Student() { }
        public Student( string[] _grades , string _name , string _secondName )
        {
            Name = _name;
            SecondName = _secondName;
            Grades = _grades;
        }
        [ComVisible(true)]
        public string[] Grades { get; set; }
        [ComVisible(true)]
        public string Name { get; set; }
        [ComVisible(true)]
        public string SecondName { get; set; }
        [ComVisible(true)]
        public string LastName { get; set; }
 
        [ComVisible(true)]
        public string GetTest()
        {
            return "Testing Student";
        }
        [ComVisible(true)]
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendFormat("| {0} {1} \n" , Name , SecondName);
            for ( int i = 0 ; i < Grades.GetLength(0) ; i++ )
                stringBuilder.AppendFormat("| {0}\n" , Grades[i]);
            return stringBuilder.ToString();
        }
    }
 
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ProgId("StudentX.TStudents")]
    [Guid("55DC203B-1A3C-4CA5-8162-6FFFD4183A2A")]
    [ComVisible(true)]
    public class TStudents
    {
        List<Student> Std_list = new List<Student>();
 
        public TStudents() { }
        public TStudents( string _folder )
        {
            if ( _folder != "" )
                foreach ( var item in Directory.GetFiles(_folder) )
                {
                    int size = File.ReadAllLines(item).Count();
                    string[] FIO = Path.GetFileNameWithoutExtension(item).Split(' ').ToArray();
                    string[] Grades = File.ReadAllLines(item);
 
                    Std_list.Add(new Student(Grades , FIO[0] , FIO[1]));
                }
        }
 
        [ComVisible(true)]
        public int Count
        {
            get { return Std_list.Count; }
        }
 
        [ComVisible(true)]
        public Student this[int index]
        {
            get { return Std_list[index]; }
            set { Std_list[index] = value; }
        }
 
        [ComVisible(true)]
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach ( Student item in Std_list )
                stringBuilder.AppendLine(item.ToString());
            stringBuilder.AppendFormat("+{0}+" , new string('-' , 30));
 
            return stringBuilder.ToString();
        }
    }
}
0
39 / 38 / 32
Регистрация: 24.11.2014
Сообщений: 352
04.11.2018, 13:52  [ТС] 10
А Вот так я его использовал и вроде подгрузил Ура.
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE>
 
<html>
 
   <head>
 
          <title>StudentX webpage</title>
 
   </head>
 
   <body>
 
       <OBJECT id="StudentX" classid="clsid:55DC203B-1A3C-4CA5-8162-6FFFD4183A2A" codebase="StudentX.cab"></OBJECT>  
 
 
 
        <script type="text/javascript">
 
            try {
 
                var obj = document.StudentX;
 
                if (obj) {
 
                    alert("Yes Correct");
 
                } else {
 
                    alert("Object is not created!");
 
                }
 
            } catch (ex) {
 
                alert("Some error happens, error message is: " + ex.Description);
 
            }
 
       
 
        </script>
 
   </body>
 
</html>
Миниатюры
Регистрация библиотеки как ActiveX  
0
04.11.2018, 13:52
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
04.11.2018, 13:52
Помогаю со студенческими работами здесь

Автоматическая регистрация ACTIVEX
Всем привет. Написал собственный компонент ACTIVEX, зарегистрировал, вставляю в программу - всё...

ActiveX регистрация элемента
Мне необходимо использовать mshflxgrd.ocx контрол в форме проекта MS Access. Но вставить этот...

Регистрация ActiveX компонента
С подключенным ActiveX компонентом приложение работает только на том компьютере, на котором этот...

Регистрация ActiveX (.NET , ATL)
Решился перейти от BCB к VC и, ессно, столктулся с проблемами ... Проблема 1 (насущная). Создаю в...


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

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru