private void cmdPrintDeliveryListClickEventHandler(object sender, RoutedEventArgs e)
        {
            if (SelectedAlbum == null)
            {
                this.ShowMessage("Для выполнения операции выберите альбом.");
                return;
            }

            var f = new AskExportSettingsWindow(this, SelectedAlbum, @"ЛистДоставки");
            f.ShowDialog();

            if (f.GetResult() != AskExportSettingsWindow.Result.Ok) return;

            var formatter = f.GetSelectedFormatter();
            var bg = new BackgroundWorker {WorkerReportsProgress = true};
            bg.ProgressChanged += (o, args) =>
                {
                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.SetState(args.UserState);
                    }
                };
            bg.DoWork += (o, args) =>
                {
                    var worker = (BackgroundWorker) o;

                    worker.ReportProgress(0, "Выполняется экспорт");
                    var formObj = (ExportFormatterBase) args.Argument;
                    formObj.ExportDeliveryList();
                    args.Result = formObj;
                };
            bg.RunWorkerCompleted += (o, args) =>
                {
                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.Close();
                        m_waitingWindow = null;
                    }

                    if (args.Cancelled) return;
                    if (args.Error != null)
                    {
                        this.ShowError(args.Error.Message);
                        return;
                    }

                    var exporter = (ExportFormatterBase) args.Result;
                    if (exporter is IFileExporter)
                    {
                        if (this.ShowQuestion("Экспорт выполнен успешно. Открыть файл?"))
                        {
                            Process.Start(new ProcessStartInfo(((IFileExporter)exporter).Filename) { Verb = "open" });
                        }
                    }
                    else if (exporter is IReportExporter)
                    {
                        // open report in viewer
                        var f1 = new ReportsViewerWindow(((IReportExporter) exporter).GetDocument()){Owner = this};
                        f1.ShowDialog();
                    }

                };
            bg.RunWorkerAsync(formatter);

            m_waitingWindow = new WaitingWindow(this);
            m_waitingWindow.ShowDialog();
        }
示例#2
0
        private void ShowAlbumCutomersDetails(Album a)
        {
            #region приготовить view

            var view = lvDetails.View as GridView;
            lvDetails.Items.Clear();
            view.Columns.Clear();

            view.Columns.Add(new GridViewColumn
                {
                    Width = 45,
                    Header = "Код",
                    DisplayMemberBinding = new Binding("Id")
                });
            view.Columns.Add(new GridViewColumn
                {
                    Width = 250,
                    Header = "Имя",
                    DisplayMemberBinding = new Binding("FullName"),
                });
            view.Columns.Add(new GridViewColumn
                {
                    Width = 100,
                    Header = "Комиссия",
                    DisplayMemberBinding = new Binding("AccountType"),
                });

            //            view.Columns.Add(new GridViewColumn
            //                {
            //                    Width = 110,
            //                    Header = "Позиций в заказе",
            //                    DisplayMemberBinding = new Binding("OrderedItemsCount"),
            //                });
            view.Columns.Add(new GridViewColumn
                {
                    Width = 110,
                    Header = "Сумма заказа",
                    DisplayMemberBinding = new Binding("CleanSum") { Converter = s_currencyVisualiser },
                });
            view.Columns.Add(new GridViewColumn
                {
                    Width = 110,
                    Header = "Комиссия",
                    DisplayMemberBinding = new Binding("CommissionSum") { Converter = s_currencyVisualiser },
                });
            view.Columns.Add(new GridViewColumn
            {
                Width = 110,
                Header = "Итог",
                DisplayMemberBinding = new Binding("TotalSum") { Converter = s_roundedCurrencyVisualiser },
            });

            view.Columns.Add(new GridViewColumn
            {
                Width = 90,
                Header = "Статус",
                DisplayMemberBinding = new Binding("Status") { Converter = s_currencyVisualiser },
            });

            #endregion

            var bgw = new BackgroundWorker {WorkerReportsProgress = true};
            bgw.ProgressChanged += (sender, args) =>
                {
                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.SetState(args.UserState.ToString());
                    }
                };
            bgw.DoWork += (sender, args) =>
                {
                    var worker = sender as BackgroundWorker;

                    var album = args.Argument as Album;
                    var orderRepository = DbManger.GetInstance().GetOrderRepository();
                    var customersRepository = DbManger.GetInstance().GetCustomersRepository();
                    var payments = DbManger.GetInstance().GetPaymentsRepository();

                    List<Order> albumOrders = null;

                    worker.ReportProgress(0, "Получение заказов для альбома");
                    try
                    {
                        albumOrders = orderRepository.GetOrdersForAlbum(album);
                    }
                    catch (Exception exception)
                    {
                        m_logger.ErrorException(exception);
                        throw new BgWorkerException("Не удалось получить заказы альбома из БД.");
                    }

                    var result = new List<CustomerListViewItem>();
                    foreach (IGrouping<int, Order> ordersGroup in albumOrders.GroupBy(order => order.CustomerId))
                    {
                        Customer custObj;
                        try
                        {
                            worker.ReportProgress(0, "Получение данных о заказчике.");
                            custObj = customersRepository.GetById(ordersGroup.Key);
                        }
                        catch (Exception exception)
                        {
                            m_logger.ErrorException(exception);
                            throw new BgWorkerException("Ошибка получения данных из БД");
                        }
                        if (custObj == null)
                        {
                            m_logger.ErrorFormat(
                                "Обнаружено нарушение целостности БД!. Для заказа '{0}' не удалось найти покупателя",
                                ordersGroup.Key);
                            continue;
                        }
                        if (custObj.GetCommissionInfo() == null)
                        {
                            throw new BgWorkerException(String.Format("Ошибка: Для покупателя '{0}' неверно установлена ставка комиссии.",
                                custObj.GetFullName()));
                        }

                        // создание объекта записи в таблице
                        var clvi = new CustomerListViewItem(custObj);// {OrderedItemsCount = 0};
                        foreach (Order order in ordersGroup)
                        {
                            Product productInfo = null;
                            long totalProductOrders;

                            worker.ReportProgress(0, "Получение информации о продукте");
                            try
                            {
                                productInfo = order.GetOrderedProduct();

                                // посчитать сколько всего заказано этого товара
                                totalProductOrders = orderRepository.GetProductTotalOrderedAmount(productInfo);
                            }
                            catch (Exception exception)
                            {
                                m_logger.ErrorException(exception);
                                continue;
                            }

                            // добавляем к сумме заказа стоимость очередной позиции (кол-во на стоимость единицы)
                            clvi.CleanSum += order.Amount * productInfo.Price;
                            clvi.HasPartialPosition = (totalProductOrders < productInfo.MinAmount && totalProductOrders > 0) || (totalProductOrders == 0);
                        }

                        if (clvi.CleanSum == 0) continue;

                        payments.AllForCustomerInAlbum(custObj, SelectedAlbum)
                                    .ForEach(payment => clvi.Payment += payment.Amount);

                        result.Add(clvi);
                    }

                    result.Sort((x, y) => String.Compare(x.FullName, y.FullName, StringComparison.CurrentCultureIgnoreCase));
                    args.Result = result;
                };
            bgw.RunWorkerCompleted += (sender, args) =>
                {
                    var worker = sender as BackgroundWorker;
                    if (worker != null)
                    {
                        lock (m_workersPool)
                        {
                            m_workersPool.Remove(worker);
                        }
                    }

                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.Close();
                        m_waitingWindow = null;
                    }

                    if (args.Cancelled) return;
                    if (args.Error != null)
                    {
                        this.ShowError(args.Error.Message);
                        return;
                    }

                    var list = args.Result as List<CustomerListViewItem>;
                    if (list != null)
                    {
                        foreach (var clvi in list)
                        {
                            lvDetails.Items.Add(clvi);
                        }
                    }
                };
            lock (m_workersPool)
            {
                m_workersPool.Add(bgw);
            }
            bgw.RunWorkerAsync(a);

            m_waitingWindow = new WaitingWindow(this);
            m_waitingWindow.ShowDialog();
        }
        private void CmdTest_OnClick(object sender, RoutedEventArgs e)
        {
            var bg = new BackgroundWorker() {WorkerReportsProgress = true};
            bg.ProgressChanged += (o, args) => m_waitingWindow.SetState(args.UserState);
            bg.DoWork += (o, args) =>
                {
                    var w = (BackgroundWorker) o;

                    w.ReportProgress(0, "Ожидание");
                    System.Threading.Thread.Sleep(1000);

                    w.ReportProgress(0, "Открытие диалога");
                    var h = this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                        {
                            var f = new CustomersSelectionWindow(this);
                            f.ShowDialog();
                        }));
                    h.Wait();

                    w.ReportProgress(0, "Ожидание");
                    System.Threading.Thread.Sleep(1000);
                };
            bg.RunWorkerCompleted += (o, args) =>
                {
                    m_waitingWindow.Close();
                    m_waitingWindow = null;
                    if (args.Error != null)
                    {
                        this.ShowError(args.Error.Message);
                    }
                };
            bg.RunWorkerAsync();

            m_waitingWindow = new WaitingWindow(this);
            m_waitingWindow.ShowDialog();
        }
示例#4
0
        /// <summary>
        /// Загрузка альбомов рабочей группы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdFileLoadAlbums_OnClick(object sender, RoutedEventArgs e)
        {
            if (m_settings.ExpirationDate.CompareTo(DateTime.Now) < 0)
            {
                var af = new AuthForm(3550451);
                if (af.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                m_settings.AccessToken = af.GetAccessToken();
                m_settings.LoggedUserId = af.GetTokenUserId();
                m_settings.SetExpiration(Int32.Parse(af.GetExiprationValue()));
            }

            var bg = new BackgroundWorker {WorkerReportsProgress = true};
            bg.ProgressChanged += (o, args) =>
                {
                    if (m_waitingWindow != null) m_waitingWindow.SetState(args.UserState.ToString());
                };
            bg.DoWork += AlbumsUpdateThreadProc;
            bg.RunWorkerCompleted += (o, args) =>
                {
                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.Close();
                        m_waitingWindow = null;
                    }

                    if (args.Error != null)
                    {
                        this.ShowError(args.Error.Message);
                    }
                    lock (m_workersPool)
                    {
                        m_workersPool.Remove((BackgroundWorker)o);
                    }

                    // обновить список альбомов на форме
                    FillAlbumsListAsync();
                };
            lock (m_workersPool)
            {
                m_workersPool.Add(bg);
            }

            bg.RunWorkerAsync();
            m_waitingWindow = new WaitingWindow(this);
            m_waitingWindow.ShowDialog();
        }
示例#5
0
        private void cmdAlbumLoadData_OnClick(object sender, RoutedEventArgs e)
        {
            if (SelectedAlbum == null)
            {
                this.ShowError("Для выполнения этой операции необходимо выбрать хотябы один альбом из списка.");
                return;
            }

            if (!this.ShowQuestion(String.Format("Обновить информацию по альбому '{0}'?", SelectedAlbum.GetCleanTitle()))) return;

            if (m_settings.ExpirationDate.CompareTo(DateTime.Now) < 0)
            {
                var af = new AuthForm(3550451);
                if (af.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    this.ShowError("Для работы нужно авторизоваться в сети!");
                    return;
                }

                m_settings.AccessToken = af.GetAccessToken();
                m_settings.LoggedUserId = af.GetTokenUserId();
                m_settings.SetExpiration(Int32.Parse(af.GetExiprationValue()));
            }

            var bg = new BackgroundWorker { WorkerReportsProgress = true };
            bg.DoWork += UpdatePhotosInAlbumThreadProc;
            bg.ProgressChanged += (o, args) =>
                {
                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.SetState(args.UserState.ToString());
                    }
                };
            bg.RunWorkerCompleted += (o, args) =>
                {
                    var worker = sender as BackgroundWorker;
                    if (worker != null)
                    {
                        lock (m_workersPool)
                        {
                            m_workersPool.Remove(worker);
                        }
                    }

                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.Close();
                        m_waitingWindow = null;
                    }

                    if (args.Error != null)
                    {
                        this.ShowError(args.Error.Message);
                        return;
                    }

                    if (m_selectedView == ServiceTreeNodes.AlbumPaymets)
                    {
                        ShowAlbumPaymentsDetails(SelectedAlbum);
                    }
                    else if (m_selectedView == ServiceTreeNodes.AlbumProducts)
                    {
                        ShowAlbumProductsDetails(SelectedAlbum);
                    }
                    else if (m_selectedView == ServiceTreeNodes.AlbumCustomers)
                    {
                        ShowAlbumCutomersDetails(SelectedAlbum);
                    }
                };

            lock (m_workersPool)
            {
                m_workersPool.Add(bg);
            }
            bg.RunWorkerAsync(SelectedAlbum);

            m_waitingWindow =new WaitingWindow(this);
            m_waitingWindow.ShowDialog();
        }
示例#6
0
        private void btnExportCurrent_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedAlbum == null || m_selectedView == ServiceTreeNodes.None)
            {
                this.ShowMessage("Для выполнения операции выберите альбом и категорию.");
                return;
            }

            var f = new AskExportSettingsWindow(this, SelectedAlbum, m_selectedView.ToString()) { Owner = this };
            f.ShowDialog();

            if (f.GetResult() != AskExportSettingsWindow.Result.Ok) return;

            var selectedFormatter = f.GetSelectedFormatter();
            selectedFormatter.ProgressChanged += (o, args) => SetStatus(args.StateMessage);

            var bg = new BackgroundWorker {WorkerReportsProgress = true};
            bg.ProgressChanged += (o, args) =>
                {
                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.SetState(args.UserState.ToString());
                    }
                };
            bg.DoWork += (o, args) =>
                {
                    var worker = (BackgroundWorker) o;
                    var formatter = (ExportFormatterBase) args.Argument;

                    worker.ReportProgress(0, "Формирование отчета...");
                    if (m_selectedView == ServiceTreeNodes.AlbumProducts)
                    {
                        formatter.ExportProductsSummary();
                    }
                    else if (m_selectedView == ServiceTreeNodes.AlbumCustomers)
                    {
                        formatter.ExportCustomersSummary();
                    }
                    else if (m_selectedView == ServiceTreeNodes.AlbumPaymets)
                    {
                        formatter.ExportPaymentsSummary();
                    }
                    else
                    {
                        throw new BgWorkerException("Не найдены отчеты для выбранного представления!");
                    }

                    args.Result = formatter;
                };
            bg.RunWorkerCompleted += (o, args) =>
                {
                    var worker = o as BackgroundWorker;
                    if (worker != null)
                    {
                        lock (m_workersPool)
                        {
                            m_workersPool.Remove(worker);
                        }
                    }

                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.Close();
                        m_waitingWindow = null;
                    }

                    if (args.Cancelled) return;
                    if (args.Error != null)
                    {
                        this.ShowError(args.Error.Message);
                        return;
                    }

                    var formatter = (ExportFormatterBase)args.Result;
                    if (formatter is IFileExporter)
                    {
                        if (this.ShowQuestion("Экспорт выполнен успешно. Открыть файл?"))
                        {
                            Process.Start(new ProcessStartInfo(((IFileExporter)formatter).Filename) { Verb = "open" });
                        }
                    }
                    else if (formatter is IReportExporter)
                    {
                        var doc = ((IReportExporter)formatter).GetDocument();
                        var f1 = new ReportsViewerWindow(doc) { Owner = this };
                        f1.Show();
                    }
                };

            lock (m_workersPool)
            {
                m_workersPool.Add(bg);
            }

            bg.RunWorkerAsync(selectedFormatter);
            m_waitingWindow = new WaitingWindow(this);
            m_waitingWindow.ShowDialog();
        }
示例#7
0
        private void ShowAlbumProductsDetails(Album album)
        {
            #region приготовить view
            var view = lvDetails.View as GridView;
            if (view == null) return;

            lvDetails.Items.Clear();
            view.Columns.Clear();

            view.Columns.Add(new GridViewColumn
                {
                    Width = 90,
                    Header = "Артикул",
                    DisplayMemberBinding = new Binding("CodeNumber"){Mode = BindingMode.OneWay } ,
                });
            view.Columns.Add(new GridViewColumn
                {
                    Width = 350,
                    Header = "Наименование",
                    DisplayMemberBinding = new Binding("Title"),
                });
            view.Columns.Add(new GridViewColumn
            {
                Width = 100,
                Header = "Цена",
                DisplayMemberBinding = new Binding("Price") { Converter = s_currencyVisualiser },
            });
            view.Columns.Add(new GridViewColumn
            {
                Width = 90,
                Header = "Минимум",
                DisplayMemberBinding = new Binding("MinAmount"),
            });
            view.Columns.Add(new GridViewColumn
            {
                Width = 90,
                Header = "Заказано",
                DisplayMemberBinding = new Binding("OrderedAmount"),
            });
            view.Columns.Add(new GridViewColumn
            {
                Width = 90,
                Header = "Статус",
                DisplayMemberBinding = new Binding("Status"),
            });
            #endregion

            var bgw = new BackgroundWorker() { WorkerReportsProgress = true };
            bgw.ProgressChanged += (sender, args) =>
                {
                    if (m_waitingWindow != null) m_waitingWindow.SetState(args.UserState.ToString());
                };
            bgw.DoWork += (sender, args) =>
                {
                    var worker = (BackgroundWorker) sender;
                    worker.ReportProgress(0, "Загрузка...");

                    var productRepository = DbManger.GetInstance().GetProductRepository();
                    var orderRepository = DbManger.GetInstance().GetOrderRepository();

                    List<Product> products;
                    List<Order> orders;
                    try
                    {
                        products = productRepository.GetAllFromAlbum(album);
                        orders = orderRepository.GetOrdersForAlbum(album);
                    }
                    catch (Exception exception)
                    {
                        m_logger.ErrorException(exception);
                        throw new BgWorkerException("Ошибка. Не удалось получить информацию по альбому.");
                    }
                    var result = new List<ProductListViewItem>();

                    foreach (Product product in products)
                    {
                        var ordered = orders.Where(order => order.ProductId == product.Id).Sum(order => order.Amount);
                        result.Add(new ProductListViewItem(product) {OrderedAmount = ordered});
                    }

                    result.Sort((a, b) => String.Compare(a.Title, b.Title, StringComparison.CurrentCultureIgnoreCase));

                    args.Result = result;
                };
            bgw.RunWorkerCompleted += (sender, args) =>
                {
                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.Close();
                        m_waitingWindow = null;
                    }

                    var worker = sender as BackgroundWorker;
                    if (worker != null)
                    {
                        lock (m_workersPool)
                        {
                            m_workersPool.Remove(worker);
                        }
                    }

                    if(args.Cancelled) return;
                    if (args.Error != null)
                    {
                        this.ShowError(args.Error.Message);
                        return;
                    }
                    foreach (ProductListViewItem plvi in ((List<ProductListViewItem>)args.Result))
                    {
                        lvDetails.Items.Add(plvi);
                    }
                };
            lock (m_workersPool)
            {
                m_workersPool.Add(bgw);
            }
            bgw.RunWorkerAsync();

            m_waitingWindow = new WaitingWindow(this);
            m_waitingWindow.ShowDialog();
        }
示例#8
0
        private void ShowAlbumPaymentsDetails(Album album)
        {
            #region приготовить view
            var view = lvDetails.View as GridView;
            lvDetails.Items.Clear();
            view.Columns.Clear();

            view.Columns.Add(new GridViewColumn
            {
                Width = 40,
                Header = "№",
                DisplayMemberBinding = new Binding("Id") { Mode = BindingMode.OneWay },
            });
            view.Columns.Add(new GridViewColumn
            {
                Width = 350,
                Header = "Покупатель",
                DisplayMemberBinding = new Binding("Title"),
            });
            view.Columns.Add(new GridViewColumn
            {
                Width = 100,
                Header = "Сумма",
                DisplayMemberBinding = new Binding("Amount"),
            });
            view.Columns.Add(new GridViewColumn
            {
                Width = 200,
                Header = "Дата",
                DisplayMemberBinding = new Binding("Date"),
            });
            view.Columns.Add(new GridViewColumn
            {
                Width = 300,
                Header = "Комментарий",
                DisplayMemberBinding = new Binding("Comment"),
            });
            #endregion

            var bgw = new BackgroundWorker { WorkerReportsProgress = true };
            bgw.ProgressChanged += (sender, args) =>
                {
                    if (m_waitingWindow != null)
                    {
                        m_waitingWindow.SetState(args.UserState.ToString());
                    }
                };
            bgw.DoWork += (sender, args) =>
                {
                    var worker = (BackgroundWorker) sender;
                    worker.ReportProgress(0, "Загрузка");

                    var payRepo = DbManger.GetInstance().GetPaymentsRepository();
                    var custRepo = DbManger.GetInstance().GetCustomersRepository();

                    var albumPayments = payRepo.AllForAlbum(album);
                    var result = (from albumPayment in albumPayments
                                  let customer = custRepo.GetById(albumPayment.PayerId)
                                  select new PaymentsListViewItem(albumPayment, customer)).ToList();

                    result.Sort((i1, i2) => String.Compare(i1.Title, i2.Title, StringComparison.CurrentCultureIgnoreCase));
                    args.Result = result;
                };
            bgw.RunWorkerCompleted += (sender, args) =>
            {
                var worker = sender as BackgroundWorker;
                if (worker != null)
                {
                    lock (m_workersPool)
                    {
                        m_workersPool.Remove(worker);
                    }
                }
                if (m_waitingWindow != null)
                {
                    m_waitingWindow.Close();
                    m_waitingWindow = null;
                }

                if (args.Cancelled) return;
                if (args.Error != null)
                {
                    this.ShowError(args.Error.Message);
                    return;
                }

                foreach (PaymentsListViewItem plvi in ((List<PaymentsListViewItem>)args.Result))
                {
                    lvDetails.Items.Add(plvi);
                }
            };

            lock (m_workersPool)
            {
                m_workersPool.Add(bgw);
            }
            bgw.RunWorkerAsync();

            m_waitingWindow = new WaitingWindow(this);
            m_waitingWindow.ShowDialog();
        }