One of the ways to transfer data from one 1C configuration to another is software connection using COM. Many companies use several different bases, between which there must be certain connections and dependencies. If it is necessary not only to transfer data, but also to perform certain data processing, then a COM connection will be the optimal mechanism. The ability to analyze data from another 1C database is useful to any developer.

We connect via COM to the 1C database

To implement a COM connection in 1C, a special mechanism called COMConnector is used. This object is installed with the platform and is used for communication information bases. It should be noted that for versions 8.2 and 8.3, objects of different names are used - "V82.COMConnector" and "V83.COMConnector", respectively.

Remember that a license is spent for the duration of the COM connection to the database - you should not get carried away with making several connections at the same time. This is especially important for organizations that have a limited number of licenses. This issue can be resolved with routine tasks that are executed when there are no active user connections to the infobase.

To be able to connect to another database and request necessary information you must know the following data:

  1. What type is it - file or client-server;
  2. Where is it located;
  3. Under what name and password can you enter it;
  4. What data are you interested in.

From the first three points, to implement a COM connection, you need to form a parameter string. Depending on the type of IB, it will differ appearance. Using the received string, a connection is made with which you can collect data from another database for analysis and processing by any methods.

ConnectionParametersFileIB = "File=""Path_to_base""; Usr=""User_name"";Pwd=""Password"""; ConnectionParametersClientServerIB = "Srvr=""Server_Name""; Ref=""Base_Name""; Usr=""User_Name""; Pwd=""Password""";

The connection function is simple and should not raise questions if all parameters are correct. To speed up debugging and analysis possible errors it is better to enclose the connection in an Attempt construct. The function will return a value of the "COM object" type, with which you will have to work, getting the necessary data.

&AtServer Function ConnectToBase() export ConnectionParametersIB = "File=""E:\base 1c\ERP""; Usr=""Administrator"";Pwd=""1"""; V83COMCon= New COMObject("V83.COMConnector"); Attempt Return V83COMCon.Connect(ConnectionParametersIB); Exception Report(ErrorDescription()); Return Undefined; End of Attempt; EndFunctions

Through a COM connection, you can not only select data, but also add it to the database you are connecting to. Remember that we can transfer 4 primitive data types through a COM object. Other types will have to be specified using the search functions built into the platform. Please note that global functions platforms are also called via a COM connection.

We receive data from the 1C database

After you have received the desired object, you need to read the data from another database. To do this, we apply a request through a COM connection in 1C 8.3 using the received value of the "COM object" type from the function. It is important to first connect to the database, and then execute the query. Execution occurs through the NewObject method with the indication of the type of the object in string form - "Request" as a parameter.

&OnServer Procedure TestCOMOnServer() Connection = ConnectToBase(); If TypeValue(Connection) Type("Undefined") Then QueryBPO = Connection.NewObject("Query"); Query BPZO.Text = "SELECT the first 15 | User Directory. Name AS Name | FROM | User Directory AS User Directory"; Selection = QueryBPO.Run().select(); While Sample.next() loop Report(Selection.Number); EndCycle; EndIf; End of Procedure >

For example, to get information about users of a certain department, we will set a condition in the request through parameters. One parameter will be of a simple type - a string, and the department - a link to the element of the "Enterprise Structure" directory. The query result is a table with enumerated fields of the type they exist in the database to which the COM connection has occurred. If you need to convert them to other types, use the standard platform functions:

  • Line();
  • Number();
  • The date().
RequestBPO = Connection.NewObject("Request"); QueryBPO.Text = "SELECT first 15 | User Directory.Name AS Name |FROM | Directory.Users AS User Directory I WHERE | User Directory.Department = &DesiredDepartment | And UserDirectory.Name like ""%"" + &DesiredName+ ""%""" ; BPZO Request.SetParameter("Desired Department", Connection.Directories.Enterprise Structure.FindByCode("00-000023")); RequestBPO.SetParameter("RequiredName","Ekaterina"); Selection = QueryBPO.Run().select(); While Selection.next() loop Report(Selection.Name); EndCycle;

If you need to transfer an array to the database for selection by several parameters, for example, divisions, the NewObject command is also used. Similarly, you can pass a list or table of values, filling them with elements of another database through the connection. All are available for you to search. existing methods objects and mechanisms of the platform.

RequestBPO = Connection.NewObject.("Request"); QueryBPO.Text = "SELECT first 15 | User Directory.Name AS Name | FROM | Directory.Users AS User Directory I WHERE | User Directory. Department In (&Desired Department) | And User Directory. Name like ""%"" + & DesiredName + ""%" ""; Subdivisions Array = Connection.NewObject("Array"); Departments array.Add(Connection.Catalogs.EnterpriseStructure.FindByCode("00-000023")); Departments array.Add(Connection.Catalogs.EnterpriseStructure.FindByCode("00-000038")); Departments array.Add(Connection.Catalogs.EnterpriseStructure.FindByCode("00-000046")); Query BPZO.SetParameter("Desired Subdivision", Array of Subdivisions); RequestBPO.SetParameter("RequiredName","Ekaterina"); Selection = QueryBPO.Run().select(); While Selection.next() loop Report(Selection.Name); EndCycle;

When transferring documents or elements of directories, the question always arises of controlling the transfer of a specific object. With COM connections, you can solve such problems through a unique identifier. You need to find an object in the pluggable database by the identifier from the current IB using the "GetLink" function, using the identifier as a string. If there isn't one, you can create it using a COM connection.

StrIdent = String(Directories.Users.FindByCode("00-0000313").UniqueIdentifier()); If NOT ValueFilled(Connection.Catalogs.Users.GetReference(Connection.NewObject("UniqueIdentifier", StrIdent))) then NewUser = Connection.Catalogs.Users.CreateItem(); NewUser.Name = Directories.Users.FindByCode("00-0000313").Name; NewUser.Individual = Directories.Users.FindByCode("00-0000313").Individual; NewUser.Write(); EndIf;

Also, the COM connection has the right to use procedures and functions from common 1C modules with the "External connection" property enabled. In addition to this condition, the called function or procedure must be an export function and not include interactive actions performed on the server. Otherwise, you will see an error about the invalid operation.

Compound..; VariableFromFunction = Connection..; function call>common module name>procedure call>common module name>

The possibilities of external connection with another database in 1C are quite extensive and can allow you to perform many tasks. It is important to be able to correctly evaluate the tools and choose the best solution. In most cases, this skill appears only with experience or by studying examples of the work of experienced professionals.

) That's right

At the same time, I have seen more than once when publications simply "take off" that do not pull even 10 points.
Why did this happen? Probably because someone obviously liked them.


I’m talking about this and saying that it would be nice not to read the article by rating to understand how much you need it, or to evaluate it not so primitively +/-. As for what I liked, I would correct it like this: she scored so much due to the fact that the stars formed in such a way and a lot of people gathered on the site and many liked it, you yourself understand this is a matter of chance. as soon as the article leaves home page then it can already be found only on request, and so everyone passing by votes. And to support on the main page, as far as I understand, they allow just constant comments = promotion of the article.
It is for this that they put shops on the thoroughfare streets - after all, it is often not the quality and relevance of the product that matters, but the patency of the place, people walking often buy what they will throw out the next day, just for the sake of the process. This is a well-known disease - shopomania. Or simply increasing flow increases the likelihood of the right buyer.

And the pros and cons ... are just some kind of "thank you" for the time and work spent


Those. Does a minus count as "thank you" too? So I wanted to know your attitude to whether it is necessary to put it in such cases, and how interesting do others think? Whether to put it when the article is harmful / bad or when it is simply useless / empty for you.
In my opinion, the article looks like just a rating increase, because:
1. The problem with types given by me was generally ignored by the author, although he was not too lazy to write a bunch of comments.
2. There is a clear inaccuracy in the article: it is said that this is the only way

V82 = New COMobject("V82.ComConnector"); Code = ContractorCOM.Code;


but I calmly do it with the help of processing like this:

Notify(Base.Directories.Counterparties.FindBy Name("LLC").Code);


and everything is fine! And I choose the connection V82.ComConnector
It is somehow strange that the author does not care at all that his article contains such problems that have been pointed out, but he does not react in any way.
3. But there is still a problem when the error "Class does not exist" pops up
4. But there is a problem when 8.2 is installed, and then 8.1 is installed - try to exchange via OLE / COM with a typical UT-BP exchange!
5. Could you indicate the main processing on the site that allows you to universally connect via OLE / COM so that beginners do not waste time, you write for them! By the way, for some reason, her picture flaunts with you, why would ?. And as a result, 2 words on the merits, and 6 more behind the scenes.

In general, I do not throw mud at you, but point out specific gaps, but there is no reaction. If this is the experience that you share, then it is somehow erroneous and incomplete.
I mean, if the author had a desire to collect all the glitches, then he could at least listen to someone else's experience, and not snap at the comments. Immediately there is a situation when the one who read it knows more than the author, they tell him (sometimes incorrectly), and he also fights back. As a result, all the information is not in the article, but in the comments! Funny! It often happens, but at the same time, you don’t need to rest on what you wanted the best - I show how it is better, and others show it! Include this in the article and it will be worthwhile, not everyone is interested in reading this skirmish.

Hi Khabravchans!

In this article, I want to talk about how integration with the 1C platform is established in my organization. Made me do it practically complete absence technical information on this topic. Reading various articles and reports on the topic of linking 1C with any information system, you are convinced over and over again that they are all marketing, demonstration in nature, and never technical, reflecting the problem and the essence of its solution.

I warn you that the method in no way claims to be universal. Since there are many 1C configurations themselves, and information systems, languages ​​and platforms - even more, the number of possible combinations is huge. My goal is to demonstrate one possible solution.


As a language that will integrate with 1C, I chose Python. It is very well suited for process automation. This is facilitated by the minimalistic syntax (the code is typed very quickly), the rich standard library (less need for third-party modules), cross-platform - with a high probability, the code written in the Linix OS will work successfully in Windows.

To begin with, I will outline the data with which we will work. The organization - a power supply company in the Far East region - serves approximately 400 thousand subscribers, the base is 1C on a self-written configuration. For each subscriber, his payments, accruals, consumed services and calculation schemes, metering devices, readings and many other data are stored.

Once in the organization there was a program written in Delphi and using MSSQL / Firebird as a database. In those glorious times, it was possible to connect to the database using any language and perform many actions - select debtor subscribers, post payments received, record instrument readings. Not surprisingly, the collection of scripts that automate the routine has been constantly growing. Programmers could perform any action without opening the program itself.

Alas, with the transition to 1C, the freebie ended - it was no longer possible to connect to the database directly. In general, the 1C platform itself is indivisible and is poorly integrated with other systems. It is, as they say, a thing in itself. When loading data into 1C, it should be remembered that it will not be so easy to extract them from there. But in view of the fact that the organization was required to implement payment systems and Personal Area, a solution had to be found.

The main tasks that I faced were the ability to quickly obtain data on a specific personal account- Full name, address, metering devices, instrument readings, payments, charges. Plus, the formation of documents - an act of reconciliation, payment receipt. So, there is no possibility of a direct connection to the database - everyone who looked at the 1C database on the SQL server saw that it was difficult to figure it out in the mass of tables like aaa1, aaa2. And to build queries with such names of tables and fields is simply unrealistic. In addition, many 1C tables (especially the most important ones, such as the cut of the last, balances and revolutions) are virtual and are scattered across different physical tables, gathering in multiple joins. This method is not suitable.

The 1C platform provides the ability to connect to it via a COM connection. Like many windows programs, during the installation of 1C, two COM objects are registered in the system - Automation Server and COM Connector. You can work with both objects using a language that supports COM technology.

The Automation Server object is a 1C application that is almost no different from a regular client application. The difference is that in addition there is an opportunity program control application instance. When working with the COM Connector object, a lightweight version of the 1C application is launched, in which forms are not available, as well as functions and methods related to the interface and visual effects. The application itself starts in the "External connection" mode. Initialization of global variables (for example, determining the current user and his settings) must be performed in the 1C external connection module. If in outer connection mode a function is called in the code that is not available in this mode, an exception will be thrown (which will be passed to our python script). Calls to unsafe functions should be framed with constructions of the form

#If NOT OuterConnection Then Warning("Hello!"); #EndIf

Since working with COM objects is a windows-only technology, it is not surprising that it is not included in the standard Python distribution. You will need to install an extension - a set of modules that provide all the necessary functionality for programming under Windows in Python. It can be downloaded as an already assembled exe installer. The extension itself provides access to the registry, services, ODBC, COM objects, and so on. Alternatively, you can immediately install the ActiveState Python distribution, in which the Win32 extension comes out of the box.

For some time I experimented with COM connection in the development of web applications, in particular, a personal account. The following disadvantages have been identified:

COM connection is slow. Low performance is a well-known minus of COM technology.
- The process of establishing a connection with 1C, depending on the configuration, can take from 1 to 8 seconds (in my case - 6 seconds). Needless to say, establishing a connection for each request will cause each page to load in 8 seconds.
- Since python web applications work as independent servers, the previous point can be compensated by storing the connection in some global variable and restoring it in case of an error. How to maintain a connection in PHP, I, frankly, have not yet thought.
- Lost cross-platform web application.

Based on the points listed above, it was decided to change the principle of interaction, dividing it into 2 parts - the first platform-dependent (Windows), unloading 1C data into any convenient format, and the second, platform-independent, capable of working with data without suspecting anything about 1C in principle.

The action strategy is as follows: the python script connects to 1C, executes the right queries and uploads the data to the SQLite database. You can connect to this database from Python, PHP, Java. Most of our projects are in python, and since I hate writing raw SQL queries by hand, all work with the SQLite database is done through the SQLAlchemy ORM. It was only necessary to describe the database data structure in a declarative style:

From sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, Numeric, DateTime, Unicode, Boolean, LargeBinary, ForeignKey Base = declarative_base() class Abonent(Base): __tablename__ = "abonents" id = Column(Integer, primary_key= True) account = Column(Unicode(32), index=True) code = Column(Unicode(32)) address = Column(Unicode(512)) fio = Column(Unicode(256)) source = Column(Unicode(16) ) psu = Column(Unicode(256)) tso = Column(Unicode(256)) np = Column(Unicode(256)) street = Column(Unicode(256)) house = Column(Integer) flat = Column(Integer) mro = Column(Unicode(256)) class Payment(Base): __tablename__ = "payments" # and so on...

Now it is enough to import this module into any python project, and you can work with the data.

I foresee your question - "why SQLite"? main reason- the database is needed only for reading, so we should not worry about problems with writing to SQLite. Secondly, the format of this DBMS is convenient - it is more convenient to view it (there are many free utilities, including a super extension for FireFox). Thirdly, in some cases it was required to get access to subscribers from those machines on which there is no connection to the MySQL server. In this case, it is enough to copy the SQLite database file, and on this machine you will have access to all the information.

Unloading occurs once a day at night. Entering data into 1C can be automated in the same way. For example, it is required to record the readings left by subscribers on the personal account website. In this case, we again connect to 1C and programmatically create and carry out the document “Act of Taking Testimonies”. I will provide the code below.

Working with COM objects in Python is a bit unusual. Firstly, the “pythonicity” of the code is lost - the rules for naming variables and functions in 1C, to put it mildly, do not correspond to the Zen of Python. Secondly, everyone knows that 1C objects are often called Cyrillic characters, which will cause problems when developing in Python ... but they are solvable. I suggest you take a look at the code:

Import pythoncom import win32com.client V82_CONN_STRING = "Srvr=v8_server;Ref=v8_db;Usr=username;Pwd=megapass;" pythoncom.CoInitialize() V82 = win32com.client.Dispatch("V82.COMConnector").Connect(V82_CONN_STRING)

As you can see from the code, the client is initialized to work with 1C. The COM object is defined by the name "V82.COMConnector". Please note that this name is valid for the V8.2 platform, if you have version 8.1, then the name will be "V81.COMConnector".

On the initialized client, we call the Connect() method, passing it the connection string. The string consists of the server name, database, user and password. The resulting V82 object stores the connection to the 1C application. It doesn't have a Disconnect() method or anything like that. To disconnect from the base, it is enough to remove the object from memory with the del () function or assign the variable to None.

Having an object, you can access any fields and methods of the 1C global context, operate with universal objects such as TabularDocument, TableValues, etc. It is important to note that when working through a COM connection, 1C works in the "External connection" mode. It does not include any features for interactive work, such as pop-up dialogs, notifications, and, most importantly, forms. I'm sure you'll curse configuration developers more than once for wrapping the most important functionality in the Button1Press() procedure in the document form module.

Let's talk about such an important thing as Cyrillic attributes. Despite the fact that 1C is a bilingual environment and there is an English equivalent for each Russian method, sooner or later you will need to turn to the Cyrillic attribute. If on PHP languages or VBSCript it won't cause any problems,

Set Con = CreateObject("v81.COMConnector") Set v8 =Con.Connect("Connection string") Set AccountsManager = v8.Documents.Accounts.... Set AccountsRecord= AccountsManager.CreateItem() AccountsRecord.Account = .... .... AccountsWrite.Write()

Then the python code will simply crash with a Syntax Error. What to do? Edit config? No, just use the getattr and setattr methods. By passing a COM object and a Cyrillic attribute name to these functions, you can get and set values ​​accordingly:

#coding=cp1251 catalog = getattr(V82.Catalogs, "PersonalAccounts")

The following is important: attribute names, as well as function and method parameters, must be passed in the cp1251 encoding. Therefore, in order to avoid coding confusion in advance, it makes sense to declare it at the beginning of the file: #coding=cp1251. After that, you can pass strings without worrying about their encoding. But! All strings received from 1C (results of function calls, requests) will be encoded in UTF-8.

An example of a code that executes a query in the 1C environment, iterates over the result and saves the database in SQLite:

#coding=cp1251 q = """ SELECT PersonalAccounts.Code AS code, PersonalAccounts.Building.Location.Name + ", " + PersonalAccounts.ShortAddress AS address, PersonalAccounts.Subscriber.Name AS fio, PersonalAccounts.Division.Name AS psu, EXPRESS(CharacteristicsPersonalAccountsSliceLast.Value AS Directory.Territorial GridOrganizations).Name AS tso, PersonalAccounts.Building.Settlement.Name AS np,PersonalAccounts.Building.Street.Name AS street,PersonalAccounts.Building.House AS flat,PersonalAccounts.Accounts Personal accounts. Dression. The child. Name as a mro from a reference book. Little evidence as a facial account of the left connection of regests. Characteristics of the signaling. The following (, vidcharacteristics = value (reference book. Vidcharacteristic. Territorial -shaped -based surveillance. = V82.NewObject( "Query", q) selection = query.Execute().Choose() CONN = db.connect() CONN.query(models.Abonent).delete() while selection.Next(): abonent = models.Abonent() abonent.account = selection.code.strip() abonent.code = selection.code abonent.fio = selection.fio abonent.address = selection.address abonent.psu = selection.psu abonent.tso = selection.tso abonent.source = u"ASRN" abonent.np = selection.np abonent.street = selection.street abonent.house = selection.house abonent.flat = selection.flat abonent.mro = selection.mro CONN.add(abonent) CONN.commit()

Here CONN is the connection session with the SQLite database. A query object is created, its text is filled. As noted above, the request text must be in cp1251, for which the encoding is first declared. After the query is executed, all subscribers are deleted in the database so as not to add duplicates, then they are added in a cycle and the final commit follows.

When working with requests, I discovered the following rules.

When selecting fields, give them Latin names, it will be much more convenient to access them through a selector (dot), instead of getattr().
- Choose only primitive data types: strings, numbers, dates and booleans. Never select links to an object (document, directory)! In this context, you absolutely do not need references and even harmful, because any access to the attribute or method of the reference will result in a request through a COM connection. If you access the link attributes in a loop, it will be extremely slow.
- If you select a Date field, it will be returned as a PyTime object. This is a special data type for passing date/time on a COM connection. It is not as convenient to work with it as with the usual datetime. If you pass this object to int(), then a timestamp will be returned, from which you can then get datetime using the fromtimestamp() method.

Now let's look at how printed documents are formed. The fact is that the consumer needs to be given the opportunity to download pre-prepared documents, for example, a payment receipt or a reconciliation act. These documents are generated in 1C in accordance with the established requirements, their implementation in Python will take a lot of time. Therefore, it is better to generate documents in 1C and save them in excel format.

So, the reconciliation act document is generated by a special external processing. For those who are not familiar with 1C terminology: processing is standalone program, which has its own module, forms, templates, designed to run in the 1C environment. It is necessary to initialize the processing, fill in its details and call a function that will return to us spreadsheet document, intended for viewing in 1C. This document must be saved in Excel format and copied to the server or written to the database.

Link = getattr(V82.Catalogs, "SystemReports").FindByDescription("Elen's Verification Act") nav_url = V82.GetURL(link, "Report") name = V82.ExternalReports.Connect(nav_url) ExternalReport = V82.ExternalReports.Create (name) setattr(ExternalReport, "PersonalAccount", reference) table_doc = ExternalReport.GetDoc() path = V82.GetTempFileName("xls") table_doc.Write(path, V82 .SpreadsheetDocumentFileType.XLS) report = models.Report() report .account = reference.Code.strip() report.type = u"act" report.document = open(path, "rb").read() CONN.add(report)

The above snippet does the following. The processing that forms the document is connected. Processing can be built into the configuration, stored on disk or in a 1C database (in some kind of directory). Since the processing changes frequently, in order not to update the configuration every time, the most frequently changing processing is stored in the “ReportsSystem” directory, in the attribute of the “value storage” type with the name Report. Processing can be initialized by unloading it from the database to disk and loading it, or by the GetURL() method, into which you need to pass a link to the directory element and the attribute name. We assign attribute values ​​to the received processing object, call the exported GetDoc() function, and get a spreadsheet document that is saved to a temporary Excel file. The content of this file is written to the SQlite database.

The last thing that remains to be considered is the programmatic entry of data into 1C. Let's assume that it is required to enter indications from subscribers. To do this, it is enough to create and conduct the document "Act of taking evidence":

#coding=cp1251 acts = getattr(V82.Documents, "Act of Taking Testimonies") act = acts.CreateDocument() setattr(act, "Indication", 1024.23) setattr(act, "Subscriber", "Ivanov") # Filling in other details. ..act.Write()
Now data entry is automated.

So, I have outlined a method that is based on programmatically uploading and downloading data using a COM connection. This method has been successfully operating in my organization for almost a year. The base, formed from 1C, serves 3 payment systems, Internet acquiring (payment by cards via the Internet), as well as a personal account. In addition, the database is connected various scripts for routine automation.

Despite the shortcomings of the method (slow speed of the COM connection), in general, it functions stably. We have data in a platform-independent form (SQLite) that can be worked with from any language. And the main part of the code is written in Python, which means that many tools and techniques are available that you can’t even dream of in 1C.

This is one of possible ways interaction with 1C. I am sure that it is not new and has probably already been tested and optimized by someone. However, I tried to set out as many details of the process as possible in order to save you from the pitfalls that I myself stepped on.

I wish you all good luck, and remember that 1C is not as scary as it is painted!

Print (Ctrl+P)

One of the options for exchanging data between 1C databases is an exchange via a COM connection. Using a COM connection, you can connect from one 1C database to another and read or write data. You can use this method both in client-server versions of databases and in file databases. This article discusses this kind of connections on the 8.3 platform

com connection

You can create two types of COM objects for the 1C application. It's ole connections V83.Application and com connections V83.COMConnector . In case of V83.Application an almost full-fledged copy of the 1C application is launched. In case of use V83.COMConnector a small server part is started. The speed of work in this case is higher, but some functions may not be available. In particular, working with forms and with common modules for which the property of working with external connections is not set. You should mainly use V83.COMConnector and only in case of lack of functionality V83.Application. The difference in speed can be especially noticeable on large databases. For platform 8.2 is used V82.Application or V82.COMConnector

Establish an OLE connection

Connection = New COMObject(“V83.Application” ) ;

Establish COM connection

Connection = New COMObject(“V83.COMConnector” ) ;

Connection string

//For client-server option
StringConnection= “Srvr = “ “ServerName” “;Ref = “ “BaseName” ;
//For the file mode option:
StringConnection= “File = “ “PathBase” “; Usr = Username; Pwd = Password”;
Attempt
Connection = Connection . Connect(ConnectionString) ;
Exception
Message = New MessageToUser;
Message . Text = "Failed to connect to database" + DescriptionError(); Message . To report();
EndTry ;

Breaking the connection

Connection = Undefined ;
For object V83.Application it is mandatory to disconnect the connection, otherwise an incomplete session will remain hanging, which will then have to be deleted manually. In case of V83.COMConnector the connection is terminated automatically at the end of the procedure in which the connection was made. And there is one more small moment. For the user under which the connection is being made, the checkbox "Ask for confirmation when closing the program" in its settings must be disabled.

NewObject() Method

To create a new object, you can use the NewObject() method, for example:

for V83.COMConnector

RequestCOM = Connection. NewObject( "Request ") ;
TableCOM = Connection. NewObject( “Value Table”) ;
ArrayCOM = Connection. NewObject("Array") ;

WidCOM = Connection.NewObject

for V83.Application

QueryOLE = Connection. NewObject(“ Request ") ;
TableOLE = Connection. NewObject(“Value Table”) ;
ArrayOLE = Connection.NewObject(“Array” ) ;
WidCOM = Connection.NewObject(“UniqueIdentifier”,StringUID);

RequestCOM . Text ="CHOOSE
| Positions of Organizations. Code,
| Positions of Organizations. Name
| FROM | Directory.PositionsOrganizations
AS Positions of Organizations”;

Result = RequestCOM. Execute () ;
Sample = result. Choose () ;
While the selection. Next()Cycle
EndCycle ;
You can also use configuration object managers:
DirectoryCOM = Connection. Reference books. DirectoryName;
DocumentCOM = Connection. The documents. DocumentName;
RegisterCOM = Connection. RegistersInformation. RegisterName ;

Getting and comparing an enum over a COM connection

To compare the values ​​of the enumeration elements defined in the configuration, it is necessary to convert these elements to one of the primitive types, the comparison of which does not cause difficulties. These types can be either a numeric type or a string type. You can convert the value of an enumeration element to a numeric type like this

Enum element = Connection.Directories.Directory1.FindByCode(1).Attribute1;

PossibleValues ​​= EnumElement.Metadata().EnumValues;

EnumElementNumber = PossibleValues.Index(PossibleValues.Find(Connection.XMLString(EnumElement)));

If EnumItemNumber = 0 Then Report( “EnumValue1”);

ElseIf EnumItemNumber = 1 Then Report("EnumValue2");

EndIf;

Getting an object via COM by ID

Through configuration object managers we get a com object, for example:
DocumentCOM = Connection. The documents. DocumentName;

Then we get the unique identifier string:

StringUID = Connection.string ( DocumentCOM.UniqueIdentifier())

ID = New Y uniqueID(StringUID);
FROM linkByIdentifier = Documents[DocumentName].GetLink(Identifier);

If you need to find the com object by document by ID, then you need to write like this:

WidCOM = Connection.NewObject(“UniqueIdentifier”,StringUID );
LinkByIdentifier = Connection.Documents[DocumentName].GetLink(UidCOM);

One of the options for exchanging data between 1C databases is an exchange via a COM connection.

Using a COM connection, you can connect from one 1C database to another and read or write data. You can use this method both in client-server versions of databases and in file databases. In this article, we will analyze examples of such compounds. The examples use platform 8.2.

You can create two types of COM objects for the 1C application. it V82.Application and V82.COMConnector. In case of V82.Application an almost full-fledged copy of the 1C application is launched. in case of use V82.COMConnector a small server part is started.
The speed of work in this case is higher, but some functions may not be available. In particular, working with forms and with common modules for which the property of working with external connections is not set. You should mainly use V82.COMConnector and only in case of lack of functionality V82.Application. The difference in speed can be especially noticeable on large databases.

So let's get started

  1. Let's create a COM object
    • for V82.Application Connection = New COMObject("V82.Application" ) ;
    • for V82.COMConnector Connection = New COMObject("V82.COMConnector" ) ;
  2. Let's create a connection string
    • for the server version of the database ConnectionString = "Srvr = " "ServerName" ";Ref = " "BaseName" ;
    • for the file version of the database ConnectionString = "File = " "PathKBase" "; Usr = Username; Pwd = Password";
  3. Making a connection to the database Attempt Connection = Connection. Connect(ConnectionString) ; Exception Message = New MessageToUser; Message. Text = + DescriptionErrors() ; Message. To report() ; EndTry ;
  4. Disconnecting from the base Connection = Undefined ;

    For object V82.Application it is mandatory to disconnect the connection, otherwise an incomplete session will remain hanging, which will then have to be deleted manually. In case of V82.COMConnector the connection is terminated automatically at the end of the procedure in which the connection was made. And there is one more small moment.

    For the user under which the connection is being made, the checkbox "Ask for confirmation when closing the program" in its settings must be disabled.

And now let's put all the code together

Connection = New COMObject("V82.Application" ) ; //Connection = New COMObject("V82.COMConnector"); ConnectionString = "Srvr = ""Server1C"";Ref = ""MyBase""; Usr = Peter; Pwd = 123" ; //ConnectionString = "File = ""С:\MyBase""; Usr = Peter; Pwd = 123"; Attempt Connection = Connection. Connect(ConnectionString) ; Exception Message = New MessageToUser; Message. Text = "Unable to connect to database"+ DescriptionError() ; Message. To report() ; EndTry ; Connection = Undefined ;

For connection type V82.Application method is applied to the COM object that was originally created, and for V82.COMConnector the method is applied to the connection. further work with the request goes standard means 1C. in code it looks like this:

Request = Connection. NewObject("Request") ; // for V82.COMConnector Request = Connection. NewObject("Request") ; // for V82.Application Request. Text = "SELECT | Positions of Organizations. Code, | Positions of Organizations. Name| FROM | Directory. Positions of Organizations AS Positions of Organizations "; Result = Request. Execute () ; Sample = Result. Choose() ; While the selection. Next() Cycle EndCycle ;

For version 1C:Enterprise 8.3, everything remains unchanged, except that when creating COMObjects, you must use "V83.COMConnector" or V83.Application.