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
}
} |