Example #1
0
        // Метод для асинхронного создания подключения к БД
        private async Task<bool> DbConnectAsync(string dbname)
        {                        
            try
            {
                // Создаем строку подключения
                EntityConnectionStringBuilder ConnectionString = new EntityConnectionStringBuilder();
                ConnectionString.ProviderConnectionString = "data source=" + Uchet.Properties.Settings.Default.dbDir
                                                             + dbname;
                ConnectionString.Provider = Uchet.Properties.Settings.Default.dbProvider;
                ConnectionString.Metadata = @Uchet.Properties.Settings.Default.dbMetadata;

                // Асинхронно создаем подключение
                await Task.Run(() => { 
                    this.DB = new DBEntity(ConnectionString.ToString());                    

                    // Задаем DataSource для таблиц в соответствии с таблицами БД приложения  
                    this.Invoke((Action)delegate{
                        gearCountEntityBindingSource.DataSource = DB.GC.ToList<GearCountEntity>();
                        gearCountEntityBindingSource.DataSource = DB.GC.Local.ToBindingList<GearCountEntity>();
                        gearPriceEntityBindingSource.DataSource = DB.GP.ToList<GearPriceEntity>();
                        gearSumEntityBindingSource.DataSource = DB.GS.ToList<GearSumEntity>();
                        gearSumEntityBindingSource.DataSource = DB.GS.Local.ToBindingList<GearSumEntity>();                    
                    });                    
                });                

                return true;
            }

            catch (Exception exeption)
            {                
                MessageBox.Show(exeption.Message, "Ошибка!");
            }

            return false;
        }
Example #2
0
        // Обработчик нажатия на пункт меню Экспорт\в Excel
        private async void ExportToExcel_Click(object sender, EventArgs e)
        {
            string DbName;
            using (DbListForm dblistwindow = new DbListForm("db"))
            {
                dblistwindow.Text = "Экспорт базы данных в Excel";
                dblistwindow.ShowDialog();
                DbName = dblistwindow.ChosenDbName;
            }

                try
                {
                    // Если задано имя БД
                    if (DbName != null && DbName != "NULL")                                            
                        // Задаем имя Excel файла для экспорта
                        using (SaveFileDialog savefiledialog = new SaveFileDialog())
                        {
                            savefiledialog.Title = "Экспорт базы данных в Excel";
                            savefiledialog.Filter = "*.xlsx|*.xlsx";

                            if (savefiledialog.ShowDialog() == DialogResult.OK)
                            {
                                await Task.Run(() =>
                                {
                                    // Создаем строку подключения
                                    string DbPath = Uchet.Properties.Settings.Default.dbDir + DbName;
                                    EntityConnectionStringBuilder ConnectionString = new EntityConnectionStringBuilder();
                                    ConnectionString.ProviderConnectionString = "data source=" + DbPath;
                                    ConnectionString.Provider = Uchet.Properties.Settings.Default.dbProvider;
                                    ConnectionString.Metadata = @Uchet.Properties.Settings.Default.dbMetadata;

                                    // Создаем подключение
                                    DBEntity DB = new DBEntity(ConnectionString.ToString());

                                    // Заполняем коллекции объектами записей таблиц БД
                                    List<GearCountEntity> GCList = DB.GC.ToList<GearCountEntity>();
                                    List<GearPriceEntity> GPList = DB.GP.ToList<GearPriceEntity>();
                                    List<GearSumEntity> GSList = DB.GS.ToList<GearSumEntity>();

                                    // Создаем и открываем Excel файл
                                    File.Copy(Uchet.Properties.Settings.Default.xlsTemplate, savefiledialog.FileName, true);
                                    Excel.Application ExcelApp = new Excel.Application();
                                    ExcelApp.Visible = false;
                                    Excel.Workbook ExcelBook = ExcelApp.Workbooks.Open(savefiledialog.FileName);

                                    // Выводим содержимое колекции GCList в 1ую таблицу Excel файла
                                    Excel.Worksheet ExcelSheet = ExcelBook.Sheets[1];
                                    int i = 2;
                                    foreach (GearCountEntity Item in GCList)
                                    {
                                        ExcelSheet.Cells[i, 1] = Item.ID;
                                        ExcelSheet.Cells[i, 2] = Item.FIO;
                                        ExcelSheet.Cells[i, 3] = Item.Gear1_Count;
                                        ExcelSheet.Cells[i, 4] = Item.Gear2_Count;
                                        ExcelSheet.Cells[i, 5] = Item.Gear3_Count;
                                        ++i;
                                    }

                                    // Выводим содержимое колекции GPList в 2ую таблицу Excel файла
                                    ExcelSheet = ExcelBook.Sheets[2];
                                    i = 2;
                                    foreach (GearPriceEntity Item in GPList)
                                    {
                                        ExcelSheet.Cells[i, 1] = Item.Gear_Name;
                                        ExcelSheet.Cells[i, 2] = Item.Gear_Price;
                                        ++i;
                                    }

                                    // Выводим содержимое колекции GSList в 3ую таблицу Excel файла
                                    ExcelSheet = ExcelBook.Sheets[3];
                                    i = 2;
                                    foreach (GearSumEntity Item in GSList)
                                    {
                                        ExcelSheet.Cells[i, 1] = Item.ID;
                                        ExcelSheet.Cells[i, 2] = Item.FIO;
                                        ExcelSheet.Cells[i, 3] = Item.Gear1_Sum;
                                        ExcelSheet.Cells[i, 4] = Item.Gear2_Sum;
                                        ExcelSheet.Cells[i, 5] = Item.Gear3_Sum;
                                        ExcelSheet.Cells[i, 6] = Item.Gear_Sum;
                                        ++i;
                                    }

                                    // Сохраняем изменения и выходим
                                    ExcelBook.Save();
                                    ExcelApp.Quit();
                                    DB.Dispose();
                                });
                            }
                        }
                        else
                            if (DbName != "NULL")
                                MessageBox.Show("Не выбрана База Данных", "Ошибка!");     
                    }                

                catch (Exception exeption)
                {
                    MessageBox.Show(exeption.Message, "Ошибка!");
                }                        
        }