Esempio n. 1
0
        protected override void Execute(NativeActivityContext context)
        {
            var mgrReport  = IoC.Instance.Resolve <IReport2EntityManager>();
            var bo         = Source.Get(context);
            var reportcode = ReportCode.Get(context);

            //var result = mgrReport.PrintReport(bo, reportcode, managerInstance == null ? null : managerInstance.GetMandantCode(bo), Barcode.Get(context));
            var result = mgrReport.PrintReport(bo, reportcode, Barcode.Get(context));

            if (result == null)
            {
                throw new DeveloperException("PrintReportStatus is null.");
            }
            var message = string.Format(StringResources.FormatForItem, bo,
                                        result.HasError
                    ? string.Format(StringResources.EpsJobCreateError, result.Error)
                    : string.Format(StringResources.EpsJobCreateOk, result.Job, reportcode, result.Printer));

            if (result.HasError && !string.IsNullOrEmpty(message))
            {
                var viewService = IoC.Instance.Resolve <IViewService>();
                viewService.ShowDialog(StringResources.ActionPrint
                                       , message
                                       , MessageBoxButton.OK
                                       , MessageBoxImage.Information
                                       , MessageBoxResult.Yes);
            }
        }
Esempio n. 2
0
        public FileResult Excel()
        {
            var list = new List <ReportCode>();

            for (var i = 0; i < 10; i++)
            {
                var sg = new ReportCode
                {
                    激活码  = "DY" + DateTime.Now.Ticks.ToString(),
                    生成序号 = "12345",
                    平台名称 = "DY",
                    //服务器名称 = "S0",
                    福利卡类型 = "新手卡"
                };
                list.Add(sg);
            }


            var html = ExcelHelper.ToHtmlTable(list);

            var name = String.Format("{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"));

            //第一种:使用FileContentResult
            byte[] fileContents = Encoding.UTF8.GetBytes(html);
            return(File(fileContents, "application/ms-excel", name));

            //第二种:使用FileStreamResult
            //var fileStream = new MemoryStream(fileContents);
            //return File(fileStream, "application/ms-excel", "excel.xls");
        }
        protected override void FormatExcel(string fileName)
        {
            ExcelHelper.Workbook(fileName, b => {
                var ws          = (_Worksheet)b.Worksheets["rep" + ReportCode.ToString()];
                ws.Name         = GetSheetName();
                var res         = _dsReport.Tables["Results"];
                var columnCount = _dsReport.Tables["Results"].Columns.Count;
                var rowCount    = _dsReport.Tables["Results"].Rows.Count;
                for (var i = 0; i < res.Columns.Count; i++)
                {
                    ws.Cells[1, i + 1] = res.Columns[i].Caption;
                }

                //Код
                ((Range)ws.Columns[1, Type.Missing]).AutoFit();
                //Наименование
                ((Range)ws.Cells[3, 2]).ColumnWidth = 20;
                //Производитель
                ((Range)ws.Cells[3, 3]).ColumnWidth = 10;

                //рисуем границы на всю таблицу
                ws.get_Range(ws.Cells[1, 1], ws.Cells[rowCount + 1, columnCount]).Borders.Weight = XlBorderWeight.xlThin;
                ws.get_Range(ws.Cells[1, 1], ws.Cells[1, columnCount]).Font.Bold = true;

                //Устанавливаем шрифт листа
                ws.Rows.Font.Size = 8;
                ws.Rows.Font.Name = "Arial Narrow";
                ws.Activate();
            });
        }
Esempio n. 4
0
        private void RefreshData()
        {
            try
            {
                int cnt = 0;
                if (SelectedUser == null)
                {
                    return;
                }
                if (ReportCode.ToValueAsString().Trim() == "")
                {
                    ShowInformationMessage(PDMsg.NotEmpty("Report Option"));
                    return;
                }

                if (StartDate.ToValueAsString().Trim() == "")
                {
                    ShowInformationMessage(PDMsg.NotEmpty("Start Date"));
                    return;
                }

                if (EndDate.ToValueAsString().Trim() == "")
                {
                    ShowInformationMessage(PDMsg.NotEmpty("End Date"));
                    return;
                }

                if (StartDate > EndDate)
                {
                    ShowInformationMessage("Start Date is Greater than End Date,Please Check it.!");
                    return;
                }

                //ReportData = _flxReportsBll
                if (ReportCode == "PPAP") //PPAP Submitted
                {
                    ReportData = _flxReportsBll.PPAPSubmitted(SelectedUser.USER_NAME.ToUpper().Trim(), Convert.ToDateTime(StartDate).ToString("dd/MM/yyyy"), Convert.ToDateTime(EndDate).ToString("dd/MM/yyyy"));
                }
                else if (ReportCode == "DR") //Document Released
                {
                    ReportData = _flxReportsBll.DocumentReleased(SelectedUser.USER_NAME.ToUpper().Trim(), Convert.ToDateTime(StartDate).ToString("dd/MM/yyyy"), Convert.ToDateTime(EndDate).ToString("dd/MM/yyyy"));
                }
                else if (ReportCode == "PNA") //part Nos Allotted
                {
                    ReportData = _flxReportsBll.PartNoAllotted(SelectedUser.USER_NAME.ToUpper().Trim(), Convert.ToDateTime(StartDate).ToString("dd/MM/yyyy"), Convert.ToDateTime(EndDate).ToString("dd/MM/yyyy"));
                }
                cnt           = ReportData.Count;
                HeaderDetails = "Designers - " + SelectedUser.FULL_NAME + " - " + cnt.ToString() + (cnt > 0 ? " Entries" : " Entry") + " found ";
                //if (ReportData.Count == 0)
                //{
                //    ShowInformationMessage("No Entries Found!");
                //}
            }
            catch (Exception ex)
            {
                throw ex.LogException();
            }
        }
Esempio n. 5
0
        /// <summary>ToReportCode 实体转换</summary>
        public static ReportCode ToReportCode(tgm_goods_code model)
        {
            var report = new ReportCode()
            {
                平台名称  = model.platform_name,
                福利卡类型 = model.GoodsType.name,
                激活码   = model.card_key,
                生成序号  = model.kind,
            };

            return(report);
        }
        public CombToPlainReport(MySqlConnection Conn, DataSet dsProperties)
            : base(Conn, dsProperties)
        {
            if (String.IsNullOrEmpty(Settings.Default.DBDumpPath))
            {
                throw new ReportException("Не установлен параметр DBDumpPath в конфигурационном файле.");
            }
            if (String.IsNullOrEmpty(Settings.Default.IntoOutfilePath))
            {
                throw new ReportException("Не установлен параметр IntoOutfilePath в конфигурационном файле.");
            }

            var name = "ind_r_" + ReportCode.ToString() + ".txt";

            _exportFilename = Path.Combine(Settings.Default.IntoOutfilePath, name).Replace('\\', '/');
            _filename       = Path.Combine(Settings.Default.DBDumpPath, name).Replace('\\', '/');
            if (File.Exists(_filename))
            {
                File.Delete(_filename);
            }
        }
        public async Task <ReportCode> CreateNew(OfficeLocation officeLocation)
        {
            try
            {
                var currentDate = DateTime.Now;
                var date        = new DateTime(currentDate.Year, 1, 1, 0, 0, 0, 0);
                var count       = await _reportCodeDataService.GetCountByDateRange(date, null);

                var reportCode = new ReportCode
                {
                    Location     = officeLocation,
                    Code         = $"{AppId}{officeLocation}{currentDate.Year.ToString().Substring(2, 2)}{(count + 1).ToString().PadLeft(4, '0')}",
                    CreationDate = currentDate
                };

                await _reportCodeDataService.Add(reportCode);

                return(reportCode);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        protected override void FormatExcel(string fileName)
        {
            ExcelHelper.Workbook(fileName, wb => {
                var ws  = (MSExcel._Worksheet)wb.Worksheets["rep" + ReportCode.ToString()];
                ws.Name = GetSheetName();
                ws.Activate();
                var res         = _dsReport.Tables["Results"];
                var columnCount = _dsReport.Tables["Results"].Columns.Count;
                var rowCount    = _dsReport.Tables["Results"].Rows.Count;

                //Код
                ((MSExcel.Range)ws.Columns[1, Type.Missing]).AutoFit();
                //Наименование
                ((MSExcel.Range)ws.Cells[3, 2]).ColumnWidth = 40;
                //Производитель
                ((MSExcel.Range)ws.Cells[3, 3]).ColumnWidth = 20;

                if (_byBaseCosts)
                {
                    reportCaptionPreffix += " по базовым ценам";
                }
                else if (_byWeightCosts)
                {
                    reportCaptionPreffix += " по взвешенным ценам по данным на " + GetStatOffersDate().ToShortDateString();
                }
                if (_reportType < 3)
                {
                    reportCaptionPreffix += " без учета производителя по прайсу " + CustomerFirmName + " создан " + DateTime.Now.ToString();
                }
                else
                {
                    reportCaptionPreffix += " с учетом производителя по прайсу " + CustomerFirmName + " создан " + DateTime.Now.ToString();
                }

                var tableBeginRowIndex = ExcelHelper.PutHeader(ws, 1, columnCount, reportCaptionPreffix);

                if (!String.IsNullOrEmpty(_suppliers))
                {
                    tableBeginRowIndex = ExcelHelper.PutHeader(ws, tableBeginRowIndex, columnCount, String.Format("Список поставщиков: {0}", _suppliers));
                }
                if (!String.IsNullOrEmpty(_ignoredSuppliers))
                {
                    tableBeginRowIndex = ExcelHelper.PutHeader(ws, tableBeginRowIndex, columnCount, String.Format("Игнорируемые поставщики: {0}", _ignoredSuppliers));
                }

                for (var i = 0; i < res.Columns.Count; i++)
                {
                    ws.Cells[tableBeginRowIndex, i + 1] = res.Columns[i].Caption;
                }

                //рисуем границы на всю таблицу
                ws.get_Range(ws.Cells[tableBeginRowIndex, 1], ws.Cells[tableBeginRowIndex + rowCount, columnCount]).Borders.Weight = MSExcel.XlBorderWeight.xlThin;
                ws.get_Range(ws.Cells[tableBeginRowIndex, 1], ws.Cells[tableBeginRowIndex, columnCount]).Font.Bold = true;

                //Устанавливаем АвтоФильтр на все колонки
                ws.Range[ws.Cells[tableBeginRowIndex, 1], ws.Cells[tableBeginRowIndex + rowCount, columnCount]].Select();
                ((MSExcel.Range)wb.Application.Selection).AutoFilter(1, Missing.Value, MSExcel.XlAutoFilterOperator.xlAnd, Missing.Value, true);

                //Устанавливаем шрифт листа
                ws.Rows.Font.Size = 8;
                ws.Rows.Font.Name = "Arial Narrow";
                ws.Activate();
            });
        }
Esempio n. 9
0
        protected override void FormatExcel(string FileName)
        {
            MSExcel.Application exApp = new MSExcel.ApplicationClass();
            try {
                exApp.DisplayAlerts = false;
                MSExcel.Workbook   wb = exApp.Workbooks.Open(FileName, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
                MSExcel._Worksheet ws;
                try {
                    ws = (MSExcel._Worksheet)wb.Worksheets["rep" + ReportCode.ToString()];

                    try {
                        ws.Name = GetSheetName();

                        //Форматируем заголовок отчета
                        ws.Cells[1, 1] = "Код";
                        ((MSExcel.Range)ws.Columns[1, Type.Missing]).AutoFit();

                        ws.Cells[1, 2] = "Наименование";
                        ((MSExcel.Range)ws.Columns[2, Type.Missing]).AutoFit();

                        switch (_reportType)
                        {
                        case DefReportType.ByNameAndForm: {
                            ws.Cells[1, 3] = "Форма выпуска";
                            ((MSExcel.Range)ws.Columns[3, Type.Missing]).AutoFit();
                            break;
                        }

                        case DefReportType.ByNameAndFormAndFirmCr: {
                            ws.Cells[1, 3] = "Форма выпуска";
                            ((MSExcel.Range)ws.Columns[3, Type.Missing]).AutoFit();
                            ws.Cells[1, 4] = "Производитель";
                            ((MSExcel.Range)ws.Columns[4, Type.Missing]).AutoFit();
                            break;
                        }

                        case DefReportType.ByProduct: {
                            ws.Cells[1, 3] = "Форма выпуска";
                            ((MSExcel.Range)ws.Columns[3, Type.Missing]).AutoFit();
                            break;
                        }

                        case DefReportType.ByProductAndFirmCr: {
                            ws.Cells[1, 3] = "Форма выпуска";
                            ((MSExcel.Range)ws.Columns[3, Type.Missing]).AutoFit();
                            ws.Cells[1, 4] = "Производитель";
                            ((MSExcel.Range)ws.Columns[4, Type.Missing]).AutoFit();
                            break;
                        }
                        }

                        //рисуем границы на заголовок таблицы
                        ws.get_Range(ws.Cells[1, 1], ws.Cells[1, _dsReport.Tables["Results"].Columns.Count]).Borders.Weight = MSExcel.XlBorderWeight.xlThick;

                        //рисуем границы на всю таблицу
                        ws.get_Range(ws.Cells[2, 1], ws.Cells[_dsReport.Tables["Results"].Rows.Count + 1, _dsReport.Tables["Results"].Columns.Count]).Borders.Weight = MSExcel.XlBorderWeight.xlThin;

                        //Устанавливаем шрифт листа
                        ws.Rows.Font.Size = 8;
                        ws.Rows.Font.Name = "Arial Narrow";
                        ws.Activate();

                        //Устанавливаем АвтоФильтр на все колонки
                        ((MSExcel.Range)ws.get_Range(ws.Cells[1, 1], ws.Cells[_dsReport.Tables["Results"].Rows.Count + 1, _dsReport.Tables["Results"].Columns.Count])).Select();
                        ((MSExcel.Range)exApp.Selection).AutoFilter(1, System.Reflection.Missing.Value, Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlAnd, System.Reflection.Missing.Value, true);

                        //Замораживаем некоторые колонки и столбцы
                        ((MSExcel.Range)ws.get_Range("A2", System.Reflection.Missing.Value)).Select();
                        exApp.ActiveWindow.FreezePanes = true;
                        MSExcel.Range rng = (MSExcel.Range)ws.Rows[1];
                        rng.Insert();
                        var caption = "Из отчета исключены (в целях повышения удобства его восприятия) товары, относящиеся к так называемой \"парафармацевтике\"";
                        if (_byWeightCosts)
                        {
                            caption += ". Отчет построен по взвешенным ценам";
                        }
                        else if (_byBaseCosts)
                        {
                            caption += ". Отчет построен по базовым ценам";
                        }
                        ws.Cells[1, 1] = caption;
                    }
                    finally {
                        wb.SaveAs(FileName, 56, Type.Missing, Type.Missing, Type.Missing, Type.Missing, MSExcel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    }
                }
                finally {
                    ws = null;
                    wb = null;
                    try {
                        exApp.Workbooks.Close();
                    }
                    catch {
                    }
                }
            }
            finally {
                try {
                    exApp.Quit();
                }
                catch {
                }
                exApp = null;
            }
        }
Esempio n. 10
0
        protected override void Execute(NativeActivityContext context)
        {
            var reportCode = ReportCode.Get(context);

            if (!_oldReportCode.Equals(reportCode) && Parameters.Count < 1)
            {
                if (reportCode != null)
                {
                    var val = reportCode.Replace("\"", string.Empty);
                    var prm = GetParams(val);
                    foreach (var p in prm)
                    {
                        var argument = new InArgument <string> {
                            Expression = p.EpsConfigValue
                        };
                        Parameters.Add(p.EpsConfigParamCode, argument);
                    }
                }
                _oldReportCode = reportCode ?? string.Empty;
            }

            var parameters = new List <NameValueObject>();

            foreach (var p in Parameters)
            {
                parameters.Add(new NameValueObject {
                    Name = p.Key, DisplayName = p.Key, Value = p.Value.Get(context)
                });
            }
            // проверим корректность данных
            if (!CheckParams(parameters))
            {
                // Запрещена ли печать при ошибке
                if (DoNotPrint)
                {
                    return;
                }

                // если нужно спросить пользователя
                if (RequestUser)
                {
                    var fields = new List <ValueDataField>();
                    foreach (var p in parameters)
                    {
                        var name  = p.Name.Replace("{", string.Empty).Replace("}", string.Empty);
                        var field = new ValueDataField
                        {
                            Name       = name,
                            SourceName = name,
                            Caption    = p.DisplayName,
                            FieldName  = name,
                            FieldType  = typeof(string),
                            Value      = p.Value
                        };
                        fields.Add(field);
                    }

                    var model = new ExpandoObjectViewModelBase();
                    model.Fields       = new ObservableCollection <ValueDataField>(fields);
                    model.PanelCaption = DialogCaption;
                    if (!ShowDialog(model))
                    {
                        return;
                    }

                    foreach (var p in parameters)
                    {
                        p.Value = model[p.Name.Replace("{", string.Empty).Replace("}", string.Empty)].ToString();
                    }

                    // проверяем последний раз
                    if (!CheckParams(parameters))
                    {
                        // игнорировать ошибки
                        if (!IgnoreErrors)
                        {
                            return;
                        }
                    }
                }
                // если не игнорируем ошибки
                else if (!IgnoreErrors)
                {
                    return;
                }
            }

            // заполняем параметры отчета
            var outputParams = new List <OutputParam>();

            foreach (var p in parameters)
            {
                outputParams.Add(new OutputParam
                {
                    OutputParamCode  = p.Name,
                    OutputParamType  = string.Empty,    // заполнится в менеджере
                    OutputParamValue = p.Value != null ? p.Value.ToString() : null
                });
            }

            // определяем id манданта по коду
            decimal?mandantId = null;

            if (!string.IsNullOrEmpty(MandantCode))
            {
                var mandantMgr     = IoC.Instance.Resolve <IBaseManager <Mandant> >();
                var codeFilterName = SourceNameHelper.Instance.GetPropertySourceName(typeof(Mandant), Mandant.MANDANTCODEPropertyName);
                var filter         = string.Format("{0} = '{1}'", codeFilterName, MandantCode);
                var mandants       = mandantMgr.GetFiltered(filter).ToArray();
                if (mandants.Length > 1)
                {
                    throw new DeveloperException("Получено более одного Манданта с кодом " + MandantCode);
                }

                if (mandants.Length == 1)
                {
                    mandantId = mandants[0].MandantId;
                }
            }

            // поехали!
            var reportMgr = IoC.Instance.Resolve <Report2EntityManager>();
            var uow       = BeginTransactionActivity.GetUnitOfWork(context);

            if (uow != null)
            {
                reportMgr.SetUnitOfWork(uow);
            }
            var result = reportMgr.PrintReport(mandantId, reportCode.Replace("\"", string.Empty), Barcode, outputParams);

            // возвращает статус задания
            Result.Set(context, result);

            // возвращает код задания
            //Result.Set(context, result.Job);
        }
Esempio n. 11
0
        protected override void FormatExcel(string fileName)
        {
            int i = 0;

            if (!String.IsNullOrEmpty(_clientsNames))             // Добавляем строку чтобы вставить выбранные аптеки
            {
                i++;
            }
            if (!String.IsNullOrEmpty(_suppliersNames))
            {
                i += 4;
            }

            ExcelHelper.Workbook(fileName, b => {
                var exApp = b.Application;
                var ws    = (_Worksheet)b.Worksheets["rep" + ReportCode.ToString()];
                ws.Name   = GetSheetName();

                var table = _dsReport.Tables["Results"];
                ExcelHelper.FormatHeader(ws, i + 2, table);

                var rowCount             = table.Rows.Count;
                var columnCount          = table.Columns.Count;
                var captionedColumnCount = table.Columns.Cast <DataColumn>().TakeWhile(c => !c.Caption.StartsWith("F")).Count();

                //Форматируем колонку "Лидер" и шапку для фирм
                FormatLeaderAndPrices(ws, captionedColumnCount + 1);

                //рисуем границы на всю таблицу
                ws.get_Range(ws.Cells[1, 1], ws.Cells[rowCount + 1, columnCount]).Borders.Weight = XlBorderWeight.xlThin;

                //Устанавливаем шрифт листа
                ws.Rows.Font.Size = 8;
                ws.Rows.Font.Name = "Arial Narrow";
                ws.Activate();

                //Устанавливаем АвтоФильтр на все колонки
                ws.get_Range(ws.Cells[i + 2, 1], ws.Cells[rowCount, columnCount]).Select();
                ((Range)exApp.Selection).AutoFilter(1, Missing.Value, XlAutoFilterOperator.xlAnd, Missing.Value, true);

                //Объединяем несколько ячеек, чтобы в них написать текст
                ws.get_Range(ws.Cells[1, 1], ws.Cells[1, captionedColumnCount]).Select();
                ((Range)exApp.Selection).Merge(null);
                if (_byBaseCosts)
                {
                    reportCaptionPreffix += " по базовым ценам";
                }
                else if (_byWeightCosts)
                {
                    reportCaptionPreffix += " по взвешенным ценам";
                }
                if (ReportType < 3)
                {
                    exApp.ActiveCell.FormulaR1C1 = reportCaptionPreffix + " без учета производителя создан " + DateTime.Now;
                }
                else
                {
                    exApp.ActiveCell.FormulaR1C1 = reportCaptionPreffix + " с учетом производителя создан " + DateTime.Now;
                }

                // Выводим список выбранных аптек
                if (!String.IsNullOrEmpty(_clientsNames))
                {
                    ws.get_Range(ws.Cells[2, 1], ws.Cells[2, captionedColumnCount]).Select();
                    ((Range)exApp.Selection).Merge(null);

                    exApp.ActiveCell.FormulaR1C1 = "Выбранные аптеки: " + _clientsNames;
                }

                // Выводим список участвовавших поставщиков
                if (!String.IsNullOrEmpty(_suppliersNames))
                {
                    var tmp = (i > 1) ? 3 : 2;
                    ws.get_Range(
                        String.Format("A{0}:K{1}", tmp, tmp + 3), Missing.Value).Select();
                    ((Range)exApp.Selection).Merge(null);

                    exApp.ActiveCell.FormulaR1C1         = "Список поставщиков: " + _suppliersNames;
                    exApp.ActiveCell.WrapText            = true;
                    exApp.ActiveCell.HorizontalAlignment = XlHAlign.xlHAlignLeft;
                    exApp.ActiveCell.VerticalAlignment   = XlVAlign.xlVAlignTop;
                }
            });
        }
Esempio n. 12
0
 protected Report(ReportCode code)
 {
     MonitoringObjects = new List <MonitoringObject>();
     Code = code;
 }