Get data from C# to 1C Enterprise 8.3 is error.

The 1C:Enterprise developers forum

#1
People who like this:0Yes/0No
Just came
Rating: 1
Joined: Sep 16, 2014
Company:

I setup 1C Enterprise 8. web-extension 1.1 (8.0.13 support 1C Enterprise 8.3)

I code on C#:

Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using _1C;
using _1C.V8;
using _1C.V8.Data;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            V8DbConnection.PoolCapacity = 2;
            V8DbConnection.PoolTimeout = 60;
            V8DbConnection.MaxConnections = 4;
            V8DbConnection.Version = ComConnectorVersion.Ver8_3;
            using (V8DbConnection conn1 = new V8DbConnection("File = E:\\BACNINH; Usr = THACH;Pwd=Htt123456;"))
            {
                //conn1.Open();
                V8DbSelectCommand v8Select = new V8DbSelectCommand();
                v8Select.CommandType = CommandType.TableDirect;
                //command.CommandText = "SEL ECT a.Code FR OM catalog.dmbophan AS a";
                v8Select.Connection = conn1;
                v8Select.CommandText = "Catalog.DmBophan";
                v8Select.Fields = "Code,Description";
                conn1.Open();
                try
                {
                    string code, description;
                    using (V8DataReader v8Reader = (V8DataReader)v8Select.ExecuteReader())
                    {
                        while (v8Reader.Read())
                        {
                            code = v8Reader.GetString(0);
                            description = v8Reader.GetString(1);

                            Console.WriteLine("{0}; {1}", code, description);
                        }
                    }
                    Console.ReadLine();
                }
                finally
                {
                    conn1.Close();
                }            

            }

        }

    }
}

V8DbConnection is OK (conn1.Open()).
But error (using (V8DataReader v8Reader =(V8DataReader)v8Select.ExecuteReader())
"Could not load file or assembly '1cv8' or one of its dependencies. The system cannot find the file specified."

Pls, help me.

Download setup.jpg (194.29 KB)
Download V8Data.jpg (156.11 KB)
Download error.jpg (237.46 KB)
Download 1C.jpg (197.05 KB)
Edited: Ha Thien Thach - May 31, 2015 11:53 PM
 
#2
People who like this:0Yes/0No
Timofey Bugaevsky
Guest

Joined:
Company:

Hello, Ha Thien Thach!

Please check that your application is built for 32-bit environment and web server supports 32-bit applications.

 
#3
People who like this:0Yes/0No
Just came
Rating: 1
Joined: Sep 16, 2014
Company:

I build on x86 (32bit) but error.

Could not load file or assembly '1cv8' or one of its dependencies. The system cannot find the file specified.

Edited: Ha Thien Thach - Jun 01, 2015 03:07 AM
 
#4
People who like this:0Yes/0No
Active user
1C:Professional
Rating: 6
Joined: May 8, 2013
Company: 1C Company

Could you, please, explain what functionality you are implementing? What is the point of using the WEB-extension?

The thing is that the WEB-extension is obsolete and stopped being supported by 1C effective 31.01.2014. There are many other tools providing the same functionality, but I need to know what you are trying to do to help you to choose one.

Edited: Konstantin Rupasov - Jun 02, 2015 03:22 PM
 
#5
People who like this:0Yes/0No
Just came
Rating: 1
Joined: Sep 16, 2014
Company:

I have an accounting software is programmed in C #. So I want to connect to 1C small business solution to get information Sales and HR.

Pls, help get data from 1C 8.3.

Edited: Ha Thien Thach - Jun 03, 2015 02:27 AM
 
#6
People who like this:0Yes/0No
Active user
1C:Professional
Rating: 6
Joined: May 8, 2013
Company: 1C Company

There are a lot of ways to implement this functionality. To offer the best option for your case I need more information. Could you, please, answer the following questions:

1. How are these two systems connected? Are they inside the same local network (LAN) or C# system needs to get to 1C system through WAN (Internet)?
2. Do you need the 1C data to be physically stored in C# system or you want just read the data from 1C system when C# system needs them?

 
#7
People who like this:0Yes/0No
Just came
Rating: 1
Joined: Sep 16, 2014
Company:

1. I built the project as follows: 1C Business (front end - http://armapp.cloudapp.net/arm/vi_VN/) and accounting software (back end - C# VS2005) on the same LAN.

2. Accounting software only reads data from 1C Business without writing data to 1C. Both will use the database SQL2008R2.

Download hr1.jpg (112.31 KB)
Download ac1.jpg (202.57 KB)
Edited: Ha Thien Thach - Jun 03, 2015 06:39 PM
 
#8
People who like this:0Yes/0No
Active user
1C:Professional
Rating: 6
Joined: May 8, 2013
Company: 1C Company

If you work under Windows you best choice, probably, is a COMConnector. You need to write something like that:

Code
        string user = "Admin";
        string pas = "123";
        string file = "C:\\Users\\Sergey\\Documents\\ms";
        
        V83.COMConnector connector = new V83.COMConnector();
        //string connectionString = "File=C:\\Users\\Sergey\\Documents\\ms;" +
            //"Usr=\"Admin\";Pwd=\"123\";";
        string connectionString = ("File='" + file + "';Usr='" + user + "';pwd='" + pas + "';");
        dynamic connection = connector.Connect(connectionString);


This gives you the connection object which allows you to manipulate with 1C infobase data using usual 1C syntax. Here is an example:

Code
        dynamic Contagents = connection.Catalogs.Contragents;
        dynamic Recordset = Contagents.Select();
        while (Recordset.Next() == true)
            Console.WriteLine(Recordset.Decription);
        Console.ReadKey(true);

 
#9
People who like this:0Yes/0No
Just came
Rating: 1
Joined: Sep 16, 2014
Company:

I use code:

Code
using System;
using System.Text;
using System.Reflection;

namespace MyProject
{
    class CommandTo1C
    {
        /// <summary>
        /// Transfers. Determine the choice for extracting action.
        /// </summary>
        private static BindingFlags CREATE_OBJECT = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.CreateInstance;
        private static BindingFlags INVOKE_METHOD = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static;
        private static BindingFlags GET_PROPERTY = BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static;
        private static BindingFlags SET_PROPERTY = BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Static;

        /// <summary>
        /// Static method to create an object in 1C
        /// </summary>
        /// <param name="Object1C">Object 1C, which creates a new object</param>
        /// <param name="NameObject">Name of the new object</param>
        /// <param name="Arguments">The arguments required to create a new object</param>
        /// <returns>Returns the created object</returns>
        public static object ExecuteCreateObject(object Object1C, string NameObject, object[] Arguments)
        {
            return Object1C.GetType().InvokeMember(NameObject, CREATE_OBJECT, null, Object1C, Arguments);
        }

        /// <summary>
        /// Static method vypolnneniya procedure or function in 1C
        /// </summary>
        /// <param name="Object1C">1C object for which you want to perform a procedure or function</param>
        /// <param name="NameObject">Name of the procedure or function</param>
        /// <param name="Arguments">The arguments required for the function</param>
        /// <returns>Gets the object. formed as a result of execution of the function</returns>
        public static object ExecuteFunction(object Object1C, string NameObject, object[] Arguments)
        {
            return Object1C.GetType().InvokeMember(NameObject, INVOKE_METHOD, null, Object1C, Arguments);
        }

        /// <summary>
        /// Static method for setting object properties 1C
        /// </summary>
        /// <param name="Object1C">1C object for which you want to set a property</param>
        /// <param name="NameObject">Property name</param>
        /// <param name="Arguments">The arguments needed to set the property</param>
        public static void SetProperty(object Object1C, string NameObject, object[] Arguments)
        {
            Object1C.GetType().InvokeMember(NameObject, SET_PROPERTY, null, Object1C, Arguments);
        }

        /// <summary>
        /// Static method to get any value object 1C
        /// </summary>
        /// <param name="Object1C">Object 1C, which is necessary to obtain property</param>
        /// <param name="NameObject">Property name</param>
        /// <returns>Returns the value obtained</returns>
        public static object GetProperty(object Object1C, string NameObject)
        {
            return Object1C.GetType().InvokeMember(NameObject, GET_PROPERTY, null, Object1C, null);
        }
        /// <summary>
        /// Static method. Generates the query text for a price
        /// </summary>
        /// <param name="only_availability">True - Only get the price of goods that
        /// Available in stock, False - receive a price for the whole range</param>
        /// <returns></returns>
        public static string CreateRequest(bool only_availability) 
        {
           
            string date = "Datetime(" + DateTime.Now.Year + "," + DateTime.Now.Month + "," + DateTime.Now.Day + ")";
            string request = @"SEL ECT a.Code, a.Description FR OM Catalog.DmVatTu AS a WH ERE a.MaNhomHang.Description = &MaNhomHang";

//        @"ВЫБРАТЬ
//         ЦеныНоменклатурыСрезПоследних.Номенклатура.Наименование КАК Номенклатура,
//         ЦеныНоменклатурыСрезПоследних.Цена,
//         ЦеныНоменклатурыСрезПоследних.Валюта.Наименование КАК Валюта,
//         ЦеныНоменклатурыСрезПоследних.ЕдиницаИзмерения.Наименование КАК ЕдиницаИзмерения
//      ИЗ
//         РегистрНакопления.ТоварыВРознице.Остатки(" + date + @", Склад.Наименование = &Склад) КАК ТоварыВРозницеОстатки
//            " + keyword + " СОЕДИНЕНИЕ РегистрСведений.ЦеныНоменклатуры.СрезПоследних(" + date + @", ТипЦен.Наименование = &ТипыЦен) КАК ЦеныНоменклатурыСрезПоследних
//            ПО ТоварыВРозницеОстатки.Номенклатура = ЦеныНоменклатурыСрезПоследних.Номенклатура";
            return request;
        }

        /// <summary>
        /// The query string to get the list of warehouses
        /// </summary>
        public static string RequestStorage = @"SEL ECT a.Description FROM Catalog.DmKho AS a";

        /// <summary>
        /// The query string for the range of types price
        /// </summary>
        public static string RequestTypePrice = @"SEL ECT a.Description FROM Catalog.DmNhomHang AS a";


    }
}

And

using System;
using System.Threading;
using System.Windows.Forms;
using System.Reflection;
using System.Text;
using V83;
using Microsoft.Office.Interop.Word;

namespace MyProject
{
    public partial class Form1 : Form
    {
        // StatusControl
        StatusControl ctrl;
        // creating COM object to connect to 1C
        COMConnectorClass connector = new COMConnectorClass();
        // object database connection
        object v83Base = null;
        XMLSerialization xml = new XMLSerialization();
        // Creating a COM object to connect to Word
        _Application wrd = new Microsoft.Office.Interop.Word.Application();
        object missing = Type.Missing;
        object PriceList = null;
        int rowcount; // number of rows resulting from the query
        Table table; // instances originally tables in word document

        public Form1()
        {
            InitializeComponent();
        }
        // Download forms
        private void Form1_Load(object sender, EventArgs e)
        {
            ctrl = new StatusControl(EnabledControl);
            FillLogin();
        }
        // The "Connect"
        private void btnConnect1C_Click(object sender, EventArgs e)
        {
            label7.Text = "Connection...";
            Thread thread = new Thread(new ParameterizedThreadStart(Connect1C));
            thread.Start(GetConnectionString());
        }
        // Event click on the textbox "Path to the database"
        private void tbPathBase_Click(object sender, EventArgs e)
        {
            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                tbPathBase.Text = folderDialog.SelectedPath;
            }
        }
        // Connection string
        private object GetConnectionString() 
        {
            StringBuilder ConnectionString = new StringBuilder(100);
            //string user = "THACH";
            //string pas = "Htt123456";
            //string file = "E:\\BACNINH";
            ConnectionString.Append(@"File=""" + tbPathBase.Text + @""";");
            ConnectionString.Append(@"Usr=" + (comboLogin.Text == null ? @";" : @"""" + comboLogin.Text + @""";"));
            ConnectionString.Append(@"Pwd=" + (tbPassword.Text == null ? @";" : @"""" + tbPassword.Text + @""";"));
            return (object)ConnectionString.ToString(); 
            //"File='" + file + "';Usr='" + user + "';pwd='" + pas + "';";
            //return "File='" + file + "';Usr='" + user + "';pwd='" + pas + "';"; 
        }
        // Filling Login
        private void FillLogin() 
        {
            if (System.IO.File.Exists("login.xml"))
            {
                xml.Load();
                for (int i = 0; i < xml.Count; i++)
                {
                    comboLogin.Items.Add(xml[i]);
                }
            }
            else
                comboLogin.Items.Add("Administrator");
        }
        // The method for connecting to the 1C
        private void Connect1C(object connection) 
        {
            TextControl txt = new TextControl(LabelText);
            try
            {
                v83Base = connector.Connect((string)connection);
                label7.BeginInvoke(txt, "Connected");
                FillcBoxStorage();
                FillTypePrice();
                this.BeginInvoke(ctrl, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Connection Error!\n" + ex.Message);
                label7.BeginInvoke(txt, "No connect");
            }
        }
        // Closing Event form
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            xml.Save();
            object saveChange = WdSaveOptions.wdDoNotSaveChanges;
            object originalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
            object routeDocument = true;
            wrd.Quit(ref saveChange, ref originalFormat, ref routeDocument);
        }
        // The "Get price"
        private void btnPrice_Click(object sender, EventArgs e)
        {
            if (cBoxStorage.Text != "")
            {
                if (chBoxTypePrice.CheckedItems.Count != 0)
                {
                    try
                    {
                        // Creating a request object in 1C
                        object price_list = CommandTo1C.ExecuteCreateObject(v83Base, "NewObject", new object[] { "Query" });
                        // Set the query text
                        CommandTo1C.SetProperty(price_list, "Text", new object[] { CommandTo1C.CreateRequest(chboxAvailability.Checked) });
                        // We ask the query parameters
                        //CommandTo1C.ExecuteFunction(price_list, "SetParameter", new object[] { "MaKhoNhap", cBoxStorage.Text });
                        //CommandTo1C.ExecuteFunction(price_list, "SetParameter", new object[] { "MaNhomHang", chBoxTypePrice.SelectedItem.ToString() });
                        //perform queries
                        //object execute = CommandTo1C.ExecuteFunction(price_list, "Execute", new object[] { });
                        // Execute the command Select for lostupa to the values of our price list
                        //PriceList = CommandTo1C.ExecuteFunction(execute, "Select", null);
                        // We get the number of records in a query result
                        //int.TryParse(CommandTo1C.ExecuteFunction(PriceList, "Number", new object[] { }).ToString(), out rowcount);
                        //MessageBox.Show("Prices!");
                        //progressBar.Maximum = rowcount;

                        int i=0;
                        CommandTo1C.ExecuteFunction(price_list, "SetParameter", new object[] { "MaNhomHang", chBoxTypePrice.SelectedItem.ToString() });
                        object result = CommandTo1C.ExecuteFunction(price_list, "Execute", null);
                        object selection = CommandTo1C.ExecuteFunction(result, "Select", null);
                        while ((bool)CommandTo1C.ExecuteFunction(selection, "Next", null))
                        {

                            i = i + 1;
                        }


                        MessageBox.Show("Item count: " + i.ToString());
                        progressBar.Maximum = i;
                    }
                    catch (Exception ex) 
                    {
                        MessageBox.Show("An error has occurred!\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
                    }
                }
                else { MessageBox.Show("To be chosen the type of price!"); }
            }
            else
                MessageBox.Show("Not selected warehouse");
        }
        // The "Show the Word"
        private void btnView_Click(object sender, EventArgs e)
        {
            wrd.Visible = true;
        }
        // The "Hide Window Word"
        private void btnHide_Click(object sender, EventArgs e)
        {
            wrd.Visible = false;
        }
        // The "Upload to Word"
        private void btnWord_Click(object sender, EventArgs e)
        {
            CreateDocument();
            CreateTable();
            Thread thr = new Thread(new ThreadStart(FillPriceList));
            thr.Start();
            EnabledControl(false);
        }
        // The method for creating a document in word
        private void CreateDocument() 
        {
            object template = "";
            object newtemp = false;
            object visible = true;
            object document = WdNewDocumentType.wdNewBlankDocument;
            wrd.Documents.Add(ref template, ref newtemp, ref document, ref visible);
        }
        // The method to create a table
        private void CreateTable() 
        {
            object start = 0;
            object end = 0;
            Range rang = wrd.Application.ActiveDocument.Range(ref start, ref end);
            wrd.ActiveDocument.Tables.Add(rang, rowcount + 1, 4, ref missing, ref missing);
            table = wrd.ActiveDocument.Tables[1];
            table.Borders.Enable = 4;
            table.Range.Font.Name = "Verdana";
            table.Range.Font.Size = 10;
            table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

            #region Формирование шапки таблицы

            table.Rows[1].Range.Font.Size = 14;
            table.Rows[1].Range.Font.Name = "Times New Roman";
            table.Cell(1, 1).Range.Text = "Наименование";
            table.Cell(1, 2).Range.Text = "Единицы изм.";
            table.Cell(1, 3).Range.Text = "Валюта";
            if (chBoxTypePrice.SelectedItem.ToString().ToLower().Contains("розни"))
                table.Cell(1, 4).Range.Text = "Розница";
            else if (chBoxTypePrice.SelectedItem.ToString().ToLower().Contains("закуп"))
                table.Cell(1, 4).Range.Text = "Закуп";
            else if (chBoxTypePrice.SelectedItem.ToString().ToLower().Contains("мелкоопт"))
                table.Cell(1, 4).Range.Text = "Мелкий опт";
            else if (chBoxTypePrice.SelectedItem.ToString().ToLower().Contains("опт"))
                table.Cell(1, 4).Range.Text = "Оптовая цена";

            #endregion
        }
        // A list of warehouses
        private void FillcBoxStorage() 
        {
            FillSkladName skl = new FillSkladName(FillcBoxSklad);
            object storage = CommandTo1C.ExecuteCreateObject(v83Base, "NewObject", new object[] { "Query" });
            CommandTo1C.SetProperty(storage, "Text", new object[] { CommandTo1C.RequestStorage });
            object result = CommandTo1C.ExecuteFunction(storage, "Execute", null);
            object selection = CommandTo1C.ExecuteFunction(result, "Select", null);
            while ((bool)CommandTo1C.ExecuteFunction(selection, "Next", null))
            {
                cBoxStorage.BeginInvoke(skl, CommandTo1C.GetProperty(selection, "Description"));
            }
        }
        // A list of types price
        private void FillTypePrice() 
        {
            Filltype f = new Filltype(FillChBoxType);
            object price = CommandTo1C.ExecuteCreateObject(v83Base, "NewObject", new object[] { "Query" });
            CommandTo1C.SetProperty(price, "Text", new object[] { CommandTo1C.RequestTypePrice });
            object result = CommandTo1C.ExecuteFunction(price, "Execute", null);
            object selection = CommandTo1C.ExecuteFunction(result, "Select", null);
            while ((bool)CommandTo1C.ExecuteFunction(selection, "Next", null))
            {
                chBoxTypePrice.BeginInvoke(f, CommandTo1C.GetProperty(selection, "Description"));
            }
        }
        // The method for discharging the resulting price list in word
        private void FillPriceList() 
        {
            // PorgressBar
            ProgressUnloading progress = new ProgressUnloading(Progress);
            for (int i = 2; i <= rowcount + 1; i++)
            {
                //Getting the next record fr om the query result
                CommandTo1C.ExecuteFunction(PriceList, "Next", null);
                //Filling in the corresponding cells in the document
                table.Cell(i, 1).Range.Text = CommandTo1C.GetProperty(PriceList, "Code").ToString();
                table.Cell(i, 2).Range.Text = CommandTo1C.GetProperty(PriceList, "Description").ToString();
                table.Cell(i, 3).Range.Text = CommandTo1C.GetProperty(PriceList, "DonViCoSo").ToString();
                table.Cell(i, 4).Range.Text = CommandTo1C.GetProperty(PriceList, "MaNhomHang").ToString();
                //table.Cell(i, 1).Range.Text = CommandTo1C.GetProperty(PriceList, "Номенклатура").ToString();
                //table.Cell(i, 2).Range.Text = CommandTo1C.GetProperty(PriceList, "ЕдиницаИзмерения").ToString();
                //table.Cell(i, 3).Range.Text = CommandTo1C.GetProperty(PriceList, "Валюта").ToString();
                //table.Cell(i, 4).Range.Text = CommandTo1C.GetProperty(PriceList, "Цена").ToString();
                // Change the value of progressbar
                progressBar.BeginInvoke(progress, new object[] { i - 1 });
            }
            this.BeginInvoke(ctrl, true);
        }
        //Handler to select a single
        //CheckedListBox
        private void chBoxTypePrice_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            for (int i = 0; i < chBoxTypePrice.Items.Count; i++)
                if (i != e.Index)
                    chBoxTypePrice.SetItemChecked(i, false);
        }
        // Processor clicking "Print Price"
        private void btnPrint_Click(object sender, EventArgs e)
        {
            object background = false;
            object append = false;
            object range = WdPrintOutRange.wdPrintAllDocument;
            object outputFileName = "";
            object fr om = missing;
            object to = missing;
            object item = WdPrintOutItem.wdPrintDocumentContent;
            object copies = (int)numerCopies.Value;
            object pages = missing;
            object pagetype = WdPrintOutPages.wdPrintAllPages;
            object printToFile = false;
            object collate = true;
            object activePrinterMacGX = missing;
            object manualDuplexPrint = false;
            object printZoomColumn = missing;
            object printZoomRow = missing;
            object printZoomPaperWidth = missing;
            object printZoomPaperHeight = missing;
            try
            {
                wrd.ActiveDocument.PrintOut(ref background, ref append, ref range, ref outputFileName,
                    ref fr om, ref to, ref item, ref copies, ref pages, ref pagetype, ref printToFile,
                    ref collate, ref activePrinterMacGX, ref manualDuplexPrint, ref printZoomColumn,
                    ref printZoomRow, ref printZoomPaperWidth, ref printZoomPaperHeight);
            }
            catch (Exception ex) 
            {
                MessageBox.Show("An error occurred while trying to print a price!\n" + ex.Message + "\n" + ex.Source, "Exclusion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        #region Методы и делегаты для доступа к контролам из другого потока

        delegate void TextControl(string text);
        delegate void ProgressUnloading(int value);
        delegate void StatusControl(bool value);
        delegate void FillSkladName(object obj);
        delegate void Filltype(object obj);

        // ProgressBar
        private void Progress(int value) 
        {
            this.progressBar.Value = value;
        }
        // Label
        private void LabelText(string text) 
        {
            this.label7.Text = text;
        }
        // A method for locking and unlocking elements form
        private void EnabledControl(bool flag) 
        {
            groupBox1.Enabled = flag;
            groupBox2.Enabled = flag;
            groupBox3.Enabled = flag;
            groupBox4.Enabled = flag;
            btnPrice.Enabled = flag;
        }
        //List warehouses
        private void FillcBoxSklad(object obj) 
        {
            cBoxStorage.Items.Add(obj);
        }
        //CheckedListBox
        private void FillChBoxType(object obj) 
        {
            chBoxTypePrice.Items.Add(obj);
        }

        #endregion
    }
}


run on C# successfull :)  :)  :)

Thanks

Edited: Ha Thien Thach - Jun 09, 2015 04:45 AM
 
Subscribe
Be the first to know tips & tricks on business application development!

A confirmation e-mail has been sent to the e-mail address you provided .

Click the link in the e-mail to confirm and activate the subscription.