frmImportNVisionWI.cs

*frmImportNVisionWI.cs*

using DevExpress.Office.Services;
using DevExpress.Spreadsheet;
using DevExpress.Xpo;
using DevExpress.XtraPrinting.BarCode.Native;
using DevExpress.XtraSpreadsheet.Commands;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Windows.Forms;
using WICore.DataSources;



//using xTrace03_SG_Data;

namespace xTraceMassUploadTool
{
    public partial class frmImportNVisionWI : Form
    {
        const string c_ConnectionString = "XpoProvider=MSSqlServer;Data Source={0};Integrated Security=False;User ID={2};Password={3};Initial Catalog={1};Persist Security Info=false";
        const string c_ConnectionStringWI = "Data Source={0};Integrated Security=False;User ID={2};Password={3};Initial Catalog={1}";

        string m_ConnectionString;
        Session m_XpoSession = null;
        //Division m_Division = null;
        bool m_xTraceConnected = false;

        List<NVisionXlsDocument> m_documentsToImport;

        class NVisionXlsDocumentItem
        {
            public string Poradi { get; set; }
            public string CisloVyrDokumentace { get; set; }
            public string Revize { get; set; }
            public string NazevVykresu { get; set; }
            public string Soubor { get; set; }
            public string Name { get; set; }
            public string Datum { get; set; }
            public string PopisZmeny { get; set; }
            public bool IsValid { get; set; }
            public bool HasData { get; set; }
            public string Message { get; set; }
            public string FilePath { get; private set; }
            public byte[] FileBinary { get; set; }
            public bool ImportOK { get; set; }
            public NVisionXlsDocumentItem()
            {
                IsValid = false;
                HasData = false;
                ImportOK = false;
            }

            public void Validate(string defaultPath)
            {
                if (string.IsNullOrEmpty(this.CisloVyrDokumentace))
                {
                    Message = "Není Číslo výrobní dokumentce";
                    IsValid = false;
                }
                // musim zjistit jestli soubor v te ceste existuje
                string filePath = GetFileLocation2(defaultPath);
                this.FilePath = string.IsNullOrEmpty(filePath) ? GetFileLocation(defaultPath) : filePath;

                // pokud je prazdne potom nenasel soubor
                if (string.IsNullOrEmpty(FilePath))
                {
                    IsValid = false;
                    Message = $"Soubor nebyl nalezen:{Message}";
                }
                else
                    IsValid = true;
            }
            /// <summary>
            /// Funkce vraci cestu a nazev souboru kde se fyzicky skutecne nachazi.
            /// </summary>
            /// <param name="filePath">Cast fyzicke cesty (adresar) kde by se mel soubor nachazet. Projdou se podadresare a zjisti se nazev souboru</param>
            public string GetFileLocation(string defaultPath)
            {
                this.Message = string.Empty;

                string[] files = System.IO.Directory.GetFiles(defaultPath, $"{Soubor}", SearchOption.AllDirectories);

                if (files == null)
                {
                    this.Message = "File not found.";
                    return string.Empty;

                }

                if (files.Length == 0)
                {
                    this.Message = "File not found.";
                    return string.Empty;
                }

                foreach (string f in files)
                {
                    if (ValidateFileLocation(f))
                    {
                        return f;
                    }
                }
                return string.Empty;
            }
            public string GetFileLocation2(string defaultPath)
            {
                this.Message = string.Empty;

                // najdu jestli existuje slozka s produktem                
                string[] folders = System.IO.Directory.GetDirectories(defaultPath, $"{CisloVyrDokumentace}=*", SearchOption.TopDirectoryOnly);

                // pokud nic nenasel chyba              
                if (folders == null)
                {
                    this.Message = "Folder not found.";
                    return string.Empty;

                }

                if (folders.Length == 0)
                {
                    this.Message = "Folder not found.";
                    return string.Empty;
                }

                // podivam se jestli exituje soubor
                string fileName = System.IO.Path.Combine(folders[0], this.Soubor);

                if (!System.IO.File.Exists(fileName))
                {
                    this.Message = $"File '{fileName} not found'";
                    return string.Empty;
                }
                else
                    return fileName;
            }
            private bool ValidateFileLocation(string fileName)
            {
                string projectName = System.IO.Path.GetDirectoryName(fileName).TrimEnd(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar).Last();

                if (string.IsNullOrEmpty(projectName))
                    return false;

                if (!projectName.StartsWith($"{CisloVyrDokumentace}="))
                    return false;

                if (!string.IsNullOrEmpty(projectName) && projectName.Split('=').First().Equals(this.CisloVyrDokumentace, StringComparison.InvariantCultureIgnoreCase))
                {
                    return true;
                }

                return false;
            }
        }
        class NVisionXlsDocument
        {
            public string FileName { get; set; }
            public string DocumentGroupName { get; set; }
            public string FirmName { get; set; }
            public bool IsValid { get; set; }
            public bool ImportOK { get { return Documents.All(o => o.ImportOK == true); } }
            public string Message { get; set; }
            public List<NVisionXlsDocumentItem> Documents { get; private set; }

            public NVisionXlsDocument()
            {
                FileName = string.Empty;
                IsValid = false;
                Documents = new List<NVisionXlsDocumentItem>();
            }
            public NVisionXlsDocument(string fileName)
            {
                FileName = fileName;
                IsValid = false;
                Documents = new List<NVisionXlsDocumentItem>();
            }
            /// <summary>
            /// Validace jestli se moze XLS importovat do WI - nastavuje IsValid propertu
            /// </summary>
            public void Validate()
            {
                try
                {
                    // validace, jestli DocumenGroupName zacina ED
                    this.IsValid = DocumentGroupName.StartsWith("ED") && !string.IsNullOrEmpty(this.FileName) && this.Documents.Count > 0;

                    if (!DocumentGroupName.StartsWith("ED"))
                    {
                        Message = "Chybí ED nebo nemá sprvný formát";
                        return;
                    }
                    if (string.IsNullOrEmpty(this.FileName))
                    {
                        Message = "Chybí zákazník";
                        return;
                    }
                    if (this.Documents.Count == 0)
                    {
                        Message = "Seznam dokumentů je prázdný";
                        return;
                    }

                    if (IsValid) Message = "OK";
                }
                catch (Exception ex)
                {
                    Message = ex.Message;
                    IsValid = false;
                }
            }
        }

        public frmImportNVisionWI()
        {
            InitializeComponent();

            m_ConnectionString = string.Format(c_ConnectionStringWI, Properties.Settings.Default.DBServer, "WI_Data", "bartech", "He$lo123");
            m_documentsToImport = new List<NVisionXlsDocument>();

            LogMessage("Start aplikace...");
            // kontrola existence te vychozi zlozky
            if (!System.IO.Directory.Exists(Properties.Settings.Default.DefaultFilePath))
            {
                btnSelectFile.Enabled = false;

                LogMessage($"Výchozí složka '{Properties.Settings.Default.DefaultFilePath}' neexistuje nebo není zadána nebo k ní není přísup");
            }

            btnAnalyseDocument.Enabled = false;
            btnImportDocument.Enabled = false;

            // nactu nastaveni WICore
            WICore.GlobalSettings.Load(m_ConnectionString);

            // neco vypsat            
            LogMessage($"Načten parametr WICore.StorageMethod={WICore.GlobalSettings.StorageMethod}");
            LogMessage($"Načten parametr WICore.StorageLocation={WICore.GlobalSettings.StorageLocation}");
        }
        void LogMessage(string message)
        {
            try
            {
                DateTime dt = DateTime.Now;
                string logFile = Path.Combine(Application.LocalUserAppDataPath, Path.ChangeExtension(string.Format("{0:yyyyMMdd}", dt), ".log"));
                //lock (m_lock)
                //{
                //    using (StreamWriter w = new StreamWriter(logFile, true, Encoding.GetEncoding(1250)))
                //    {
                //        w.WriteLine("[{0:HH:mm:ss.fff}] {1}", dt, message);
                //    }
                //}
                System.IO.File.AppendAllText(logFile, string.Format("[{0:HH:mm:ss.fff}] {1}\r\n", dt, message), Encoding.GetEncoding(1250));
            }
            catch { }
            finally
            {
                listBox1.Items.Add(message);                
                listBox1.Refresh();
            }
        }
        void LogError(Exception e)
        {
            LogMessage(e.Message);
        }
        private string GetCellValue(Worksheet ws, string cell, int row)
        {
            return (ws.Cells[string.Format("{0}{1}", cell, row)].Value != null) ? ws.Cells[string.Format("{0}{1}", cell, row)].Value.ToString() : string.Empty;
        }
        private string GetCellValue(Worksheet ws, string cell)
        {
            return (ws.Cells[cell].Value != null) ? ws.Cells[cell].Value.ToString() : string.Empty;
        }
        /// <summary>
        /// Projde seznam dokumentu pro import a pokusi se je validovat
        /// </summary>
        void UpdateDocumentsListBox1(bool onlyClear = false)
        {
            if (onlyClear)
            {
                listBoxControl1.BackColor = Color.White;
                listBoxControl1.ForeColor = Color.Black;

                listBoxControl1.Items.BeginUpdate();
                listBoxControl1.Items.Clear();
                listBoxControl1.Items.EndUpdate();

                return;
            }
            listBoxControl1.BackColor = Color.White;
            listBoxControl1.ForeColor = Color.Black;

            listBoxControl1.Items.BeginUpdate();
            listBoxControl1.Items.Clear();

            foreach (NVisionXlsDocument doc in m_documentsToImport)
            {
                string message = string.Format("{0}:\t {1}", Path.GetFileName(doc.FileName), doc.Message);

                listBoxControl1.Items.Add(message);
            }

            if (m_documentsToImport.All(o => o.IsValid))
            {
                listBoxControl1.BackColor = Color.Green;
                listBoxControl1.ForeColor = Color.White;

            }
            else if (m_documentsToImport.Any(o => o.IsValid))
            {
                listBoxControl1.BackColor = Color.Orange;
                listBoxControl1.ForeColor = Color.Black;
            }
            else if (m_documentsToImport.All(o => o.IsValid == false))
            {
                listBoxControl1.BackColor = Color.Red;
                listBoxControl1.ForeColor = Color.Black;
            }

            listBoxControl1.Items.EndUpdate();
        }
        void UpdateDocumentsListBox2(bool onlyClear = false)
        {
            if (onlyClear)
            {
                listBoxControl2.BackColor = Color.White;
                listBoxControl2.ForeColor = Color.Black;

                listBoxControl2.Items.BeginUpdate();
                listBoxControl2.Items.Clear();
                listBoxControl2.Items.EndUpdate();

                return;
            }

            listBoxControl2.BackColor = Color.White;
            listBoxControl2.ForeColor = Color.Black;

            listBoxControl2.Items.BeginUpdate();
            listBoxControl2.Items.Clear();
            foreach (NVisionXlsDocument doc in m_documentsToImport)
            {
                foreach (NVisionXlsDocumentItem docItem in doc.Documents)
                {
                    string message = string.Format("{0}\t{1}\t{2}\t{3}\t-{4}", doc.DocumentGroupName, docItem.CisloVyrDokumentace, docItem.Revize, docItem.Soubor, docItem.Message);

                    listBoxControl2.Items.Add(message);
                }

                if (doc.ImportOK)
                {
                    listBoxControl2.BackColor = Color.Green;
                    listBoxControl2.ForeColor = Color.White;
                }
                else
                {
                    listBoxControl2.BackColor = Color.Red;
                    listBoxControl2.ForeColor = Color.Black;
                }
            }

            listBoxControl2.Items.EndUpdate();
        }
        bool CheckXlsDocument(string fileName)
        {
            try
            {
                listBox1.Items.Clear();

                Workbook workbook = new Workbook();

                LogMessage($"Otevírám soubor {fileName}");
                bool m_DocumentLoaded = workbook.LoadDocument(fileName);

                LogMessage("Hledám sešity...");

                foreach (Worksheet ws in workbook.Worksheets)
                {
                    NVisionXlsDocument xlsDoc = new NVisionXlsDocument(fileName);
                    xlsDoc.DocumentGroupName = GetCellValue(ws, "G3").Trim().Replace(" ", string.Empty).ToUpper();
                    xlsDoc.FirmName = GetCellValue(ws, "I3").Trim();


                    LogMessage($"Načítám sešit {ws.Name}, ED={xlsDoc.DocumentGroupName} , Zákazník={xlsDoc.FirmName}");
                    // podivej se jake jsou tam dokumenty
                    int rowIndex = 13;
                    while (true)
                    {
                        NVisionXlsDocumentItem xlsDocItem = new NVisionXlsDocumentItem();
                        xlsDocItem.CisloVyrDokumentace = GetCellValue(ws, "B", rowIndex);

                        if (string.IsNullOrEmpty(xlsDocItem.CisloVyrDokumentace)) break;

                        xlsDocItem.Revize = GetCellValue(ws, "C", rowIndex);
                        xlsDocItem.NazevVykresu = GetCellValue(ws, "F", rowIndex);
                        xlsDocItem.Soubor = GetCellValue(ws, "G", rowIndex);
                        // nazwv dokumentu bez pripony
                        xlsDocItem.Name = System.IO.Path.GetFileNameWithoutExtension(xlsDocItem.Soubor);
                        xlsDocItem.PopisZmeny = GetCellValue(ws, "I", rowIndex);

                        // pridam do seznamu dokumentu, ktere budu chtit importovat
                        xlsDoc.Documents.Add(xlsDocItem);

                        rowIndex++;
                    }
                    // validace
                    xlsDoc.Validate();

                    // pridej do seznamu
                    m_documentsToImport.Add(xlsDoc);

                    // budu ted cist jen ten prvni list
                    break;
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
                return false;
            }
            finally
            {
                LogMessage($"Ověření XLS dokumentu: {m_documentsToImport.All(o => o.IsValid == true)}");
            }

            return m_documentsToImport.All(o => o.IsValid == true);
        }
        private void AnalyseXlsDocuments()
        {
            // prochazim jeste dokumenty pro import a validuji cesty k souborum
            foreach (NVisionXlsDocument doc in m_documentsToImport)
            {
                if (!doc.IsValid)
                {
                    LogMessage($"Analýza dokumentu {doc.FileName} nelze provést. Není OK!");
                    break;
                }
                // poskladam slozku podle vychozi + zakaznik
                string path = System.IO.Path.Combine(Properties.Settings.Default.DefaultFilePath, doc.FirmName);

                if (!System.IO.Directory.Exists(path))
                {
                    doc.IsValid = false;
                    doc.Message = $"Nenalezena složka {path}";
                    LogMessage(doc.Message);
                    continue;
                }

                // projdu seznam dokumentu a najdu jestli existuji souboroy. musim najit jeden soubor
                foreach (NVisionXlsDocumentItem item in doc.Documents)
                {
                    LogMessage($"Hledám soubor:'{item.Soubor}'");
                    item.Validate(path);
                    LogMessage($"Složka:'{item.FilePath}'");
                    LogMessage($"Výsledek:{item.IsValid}");
                    LogMessage($"Zpráva:{item.Message}");
                }
                // dokumentace je valid pokud jsou vsechny jeji dokumenty valid
                doc.IsValid = doc.Documents.All(o => o.IsValid);
                doc.Message = doc.IsValid ? "OK" : "Chyba validace dokumentů";
                // kontrola ED
                if (CheckED(doc.DocumentGroupName)) doc.Message = "OK - ED již existuje";
            }
            UpdateDocumentsListBox2(true);
            btnImportDocument.Enabled = m_documentsToImport.Any(o => o.IsValid);
        }
        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            try
            {
                btnAnalyseDocument.Enabled = false;
                btnImportDocument.Enabled = false;

                m_documentsToImport.Clear();

                using (OpenFileDialog openFileDialog = new OpenFileDialog())
                {
                    openFileDialog.InitialDirectory = Properties.Settings.Default.InitialDirectory;
                    openFileDialog.Filter = "Sešit Excelu (*.xlsx)|*.xlsx|Sešit Excelu s podporou maker (*.xlsm)|*.xlsm";
                    openFileDialog.FilterIndex = 0;
                    openFileDialog.RestoreDirectory = true;

                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        if (CheckXlsDocument(openFileDialog.FileName))
                        {
                            btnAnalyseDocument.Enabled = true;
                            AnalyseXlsDocuments();
                        }

                        UpdateDocumentsListBox1();
                    }
                    else
                    {
                        UpdateDocumentsListBox1(true);
                    }
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
            finally
            {
                //LogMessage($"Celkový výsledek: {btnAnalyseDocument.Enabled}");
            }
        }
        /// <summary>
        /// Nacte binarni data importovaneho dokumentum prevede na XPS a ulozi do pole ve verzi dokumentu
        /// </summary>
        /// <param name="docXls"></param>
        /// <returns></returns>
        private bool LoadBinaryData(NVisionXlsDocumentItem docXls)
        {
            Bartech.Document.Conversion.DocConverter conv = new Bartech.Document.Conversion.DocConverter();
            byte[] fileBinary = null;
            string fileName = string.Empty;
            bool hasData = false;
            try
            {
                if (System.IO.File.Exists(docXls.FilePath))
                {
                    fileName = Path.GetFileName(docXls.FilePath);
                    conv.Open(docXls.FilePath);
                    LogMessage(string.Format("Probíhá konverze dokumentu {0}...", fileName));
                    fileBinary = conv.GetAsBinaryData();
                    hasData = true;
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
            finally
            {
                docXls.FileBinary = fileBinary;
                docXls.HasData = hasData;
            }
            return hasData;
        }
        /// <summary>
        /// Overi jestli uz existuje nejaky platny dokument pod tim ED 0 tedy existuej nejaka ED skupina
        /// </summary>
        /// <param name="documentGroupName"></param>
        /// <returns></returns>
        private bool CheckED(string documentGroupName)
        {
            try
            {
                DocumentVersionDBHelper docVersionDS = new DocumentVersionDBHelper(m_ConnectionString);

                return docVersionDS.CheckDocumentGroup(documentGroupName);
            }
            catch (Exception ex)
            {
                LogError(ex);
                return false;
            }
        }
        /// <summary>
        /// Funkce natahne verze dokumentu podle nazvu souboru a zjisti jestli nejaky znich uz existuje a je soucasti ED
        /// </summary>
        /// <param name="xlsDoc"></param>
        /// <param name="docVersion"></param>
        private List<DocumentVersion> LoadDocumentVersionByFileName(NVisionXlsDocument xlsDoc, NVisionXlsDocumentItem docVersion)
        {
            DocumentVersionDBHelper documentVersionDS = new DocumentVersionDBHelper(m_ConnectionString);
            DataTable dtVersions = documentVersionDS.FindByFileName(docVersion.Soubor);

            List<DocumentVersion> list = new List<DocumentVersion>();

            if (dtVersions != null)
            {
                for (int index = 0; index < dtVersions.Rows.Count; index++)
                {
                    DataRow row = dtVersions.Rows[index];
                    list.Add(new DocumentVersion(row));
                }
            }
            return list;
        }
        /// <summary>
        /// Provede import dokumentu do WI
        /// </summary>
        /// <param name="xlsDoc"></param>
        /// <param name="docVersion"></param>
        /// <returns></returns>
        private bool ImportDocument(NVisionXlsDocument xlsDoc, NVisionXlsDocumentItem docVersion)
        {
            DocumentVersionDBHelper documentVersionDS = new DocumentVersionDBHelper(m_ConnectionString);
            DocumentDDBHelper docDS = new DocumentDDBHelper(m_ConnectionString);
            Document doc = new Document();
            DocumentVersion dv = new DocumentVersion();
            bool importResult = false;
            bool docExist = false;
            try
            {
                docVersion.ImportOK = false;

                LogMessage($"Připravuji zápis dokumentu {docVersion.Soubor} do WI");


                // podivam se jestli uz tam nejaky dokument s tim nazvem mam
                docExist = docDS.checkDocumentName(docVersion.Name, -1);

                if (docExist)
                {
                    LogMessage($"Dokument {docVersion.Name} již existuje. Hledám verze...");
                    // najdu vsechny verze dokumentu podle nazvu souboru
                    DataTable dtVersions = documentVersionDS.FindByName(docVersion.Name);
                    // sem budu davat ED kterych je soucasti

                    if (dtVersions != null && dtVersions.Rows.Count > 0)
                    {
                        LogMessage($"Nelezeno celkem verzí:{dtVersions.Rows.Count}");
                        List<string> documentGroups = new List<string>();

                        for (int index = 0; index < dtVersions.Rows.Count; index++)
                        {
                            DataRow row = dtVersions.Rows[index];
                            dv = new DocumentVersion(row);
                            // kdyz jsem nasel vice verzi stejneho dokumentu, pak se podivam, ve kterych vsech ED je
                            LogMessage($"Verze dokumentu {docVersion.Soubor}. OID:{dv.OID}, DocumentID:{dv.DocumentID}, ED: {dv.DocumentGroup}, Enabled:{dv.Enabled}");
                            // jestli ED je souasti nejakych verzi
                            var dg = dv.DocumentGroup.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                            // abych vyloucil duplicity
                            foreach (string item in dg)
                            {
                                if (!documentGroups.Contains(item)) documentGroups.Add(item);
                            }

                            // pridam do seznamu
                            if (!documentGroups.Contains(xlsDoc.DocumentGroupName))
                            {
                                documentGroups.Add(xlsDoc.DocumentGroupName);
                                dv.DocumentGroup = string.Join(",", documentGroups);
                                LogMessage($"Aktualizuji seznam vyrobní dokumentace na:{dv.DocumentGroup}");
                                // uloz verzi dokumentu
                                documentVersionDS.Edit(dv);
                            }
                        }

                        importResult = documentGroups.Count > 0;
                    }
                    else
                    {
                        // dokument podle nazvu nalezen ale nema nahrane zadne verze
                        // musim nacist vsechny dokumenty
                        DataTable dtDocuments = docDS.List();
                        if (dtDocuments != null)
                        {
                            foreach(DataRow row in dtDocuments.Rows)
                            {
                                if (row["Name"].ToString() == docVersion.Name)
                                {
                                    importResult = CreateDocumentVersion(Convert.ToInt64(row["OID"]), xlsDoc.DocumentGroupName, docVersion);
                                }
                            }
                        }                        
                    }
                }
                else
                {
                    LogMessage($"Ukládám novou verzi dokumentu {docVersion.Soubor} pro ED={xlsDoc.DocumentGroupName}.");

                    // zcela nova verze dokumentu
                    doc = new Document();
                    doc.OID = -1;
                    doc.Name = Path.GetFileNameWithoutExtension(docVersion.Soubor);
                    doc.Deleted = false;
                    doc.store = true;
                    // ulozit
                    doc.OID = docDS.AddNew(doc);

                    if (doc.OID != -1)
                    {
                        //dv = new DocumentVersion();
                        //dv.OID = -1;
                        //dv.DocumentID = doc.OID;
                        //dv.Version = string.Empty;
                        //dv.Description = docVersion.NazevVykresu;
                        //dv.FileLocation = docVersion.FilePath;
                        //dv.EffectFrom = DateTime.Now;
                        //dv.OpSeqDisplay = string.Empty;
                        //dv.Deleted = false;
                        //dv.Enabled = true;
                        //dv.DocumentGroup = xlsDoc.DocumentGroupName;
                        //// ulozit
                        //documentVersionDS.AddNew(dv);
                        //if (dv.OID != -1)
                        //{
                        //    documentVersionDS.UpdateData(dv.OID, docVersion.FilePath, docVersion.FileBinary);
                        //    importResult = true;
                        //}
                        //else
                        //    docVersion.Message = "Neuložila se verze dokumentu";
                        importResult = CreateDocumentVersion(doc.OID, xlsDoc.DocumentGroupName, docVersion);
                    }
                    else
                        docVersion.Message = "Neuložil se dokument";
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
            }

            docVersion.ImportOK = importResult;
            docVersion.Message = (importResult) ? "Import OK" : $"Chyba importu: {docVersion.Message}";

            return importResult;
        }

        private bool CreateDocumentVersion(long documentID, string documentGroupName, NVisionXlsDocumentItem docVersion)
        {
            try
            {
                DocumentVersionDBHelper documentVersionDS = new DocumentVersionDBHelper(m_ConnectionString);

                DocumentVersion dv = new DocumentVersion();
                dv.OID = -1;
                dv.DocumentID = documentID;
                dv.Version = string.Empty;
                dv.Description = docVersion.NazevVykresu;
                dv.FileLocation = docVersion.FilePath;
                dv.EffectFrom = DateTime.Now;
                dv.OpSeqDisplay = string.Empty;
                dv.Deleted = false;
                dv.Enabled = true;
                dv.DocumentGroup = documentGroupName;
                // ulozit
                documentVersionDS.AddNew(dv);
                if (dv.OID != -1)
                {
                    documentVersionDS.UpdateData(dv.OID, docVersion.FilePath, docVersion.FileBinary);
                    return true;
                }
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }
        private void btnAnalyseDocument_Click(object sender, EventArgs e)
        {
            AnalyseXlsDocuments();
            UpdateDocumentsListBox1();
        }
        /// <summary>
        /// Pro vsechny validni XLS vyrobni dokumentace udela import
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImportDocument_Click(object sender, EventArgs e)
        {
            foreach (NVisionXlsDocument doc in m_documentsToImport.Where(o => o.IsValid))
            {
                // pokusim se nacist obsah PDF souboru
                foreach (NVisionXlsDocumentItem item in doc.Documents.Where(o => o.IsValid))
                {
                    LoadBinaryData(item);
                }

                // projdu jenom ty, ktere maji nejaka data
                foreach (NVisionXlsDocumentItem item in doc.Documents.Where(o => o.HasData))
                {
                    // provedu import dokumentu do WI. Pokud se jeden dokument nepodari importovat nema smysl pokracovat v ostatnich
                    if (!ImportDocument(doc, item))
                        break;
                }
            }

            UpdateDocumentsListBox2();
            UpdateDocumentsListBox1();

            // zakazat znova import dokud se neudela analyza
            btnImportDocument.Enabled = false;
        }
    }
}