示例#1
0
        private EpsOutputTask GetEpsPrintTask(EpsOutput epsOutput, string printerName = "some physical printer",
                                              int copies = 1)
        {
            var task = new EpsOutputTask
            {
                Output           = epsOutput,
                OutputTaskCode   = EpsOutputTaskCodes.OTC_PRINT,
                OutputTaskOrder  = 1,
                OutputTaskStatus = OutputStatuses.OS_NEW
            };

            task.OutputTask_EpsOutputParam_List = new Quartz.Collection.HashSet <EpsOutputParam>
            {
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.Copies,
                    OutputParamValue = copies.ToString()
                },
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.PhysicalPrinter,
                    OutputParamValue = printerName
                }
            };
            return(task);
        }
        private void ProcessOutput(EpsOutput output)
        {
            var sw = new Stopwatch();

            sw.Start();
            Log.Debug("Start processing.");
            Exception exception = null;

            try
            {
                IEpsJobConfig config;
                using (var session = SessionFactory.OpenSession())
                {
                    // проверяем
                    CheckOutput(output);

                    // создаем конфигурацию
                    config = EpsJobConfigurator.Configure(output, session, HandleTaskComplete);
                }

                // запускаем
                using (var job = EpsJobFactory.CreateJob(config))
                    job.Execute();
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                sw.Stop();
                HandleComplete(output.OutputID, exception, sw.Elapsed);
            }
        }
示例#3
0
        private EpsOutputTask GetEpsShareTask(EpsOutput epsOutput, string targetFolder,
                                              string exportFormat = "wmsMLC.EPS.wmsEPS.ExportTypes.FRExcel2007")
        {
            var task = new EpsOutputTask
            {
                Output           = epsOutput,
                OutputTaskCode   = EpsOutputTaskCodes.OTC_SHARE,
                OutputTaskOrder  = 1,
                OutputTaskStatus = OutputStatuses.OS_NEW
            };

            task.OutputTask_EpsOutputParam_List = new Quartz.Collection.HashSet <EpsOutputParam>
            {
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.TargetFolder,
                    OutputParamValue = targetFolder
                },
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.FileFormat,
                    OutputParamValue = exportFormat
                }
            };
            return(task);
        }
 private static void CheckOutput(EpsOutput output)
 {
     if (string.IsNullOrEmpty(output.Login_r))
     {
         throw new Exception(string.Format("Output with id {0} has empty Login_r field.", output.OutputID));
     }
 }
示例#5
0
        /// <summary>
        /// Сохранение задания EPS в БД.
        /// </summary>
        public static void SaveEpsOutput(EpsOutput output, ISession session)
        {
            //Сохраняем
            session.Save(output);
            if (output.Output_EpsOutputParam_List != null)
            {
                foreach (var p in output.Output_EpsOutputParam_List)
                {
                    p.Output = output;
                    session.Save(p);
                }
            }

            if (output.Output_EpsOutputTask_List != null)
            {
                foreach (var outputTask in output.Output_EpsOutputTask_List)
                {
                    outputTask.Output = output;
                    session.Save(outputTask);

                    if (outputTask.OutputTask_EpsOutputParam_List == null)
                    {
                        continue;
                    }

                    foreach (var t in outputTask.OutputTask_EpsOutputParam_List)
                    {
                        t.Output = output;
                        session.Save(t);
                    }
                }
            }
        }
 protected static void CheckOutput(EpsOutput output)
 {
     if (output.OutputStatus != OutputStatuses.OS_ON_TRANSFER)
     {
         throw new Exception(string.Format("Output {0} in the wrong state. Waiting state {1} but {2}.",
                                           output.OutputID, OutputStatuses.OS_ON_TRANSFER, output.OutputStatus));
     }
 }
示例#7
0
        private EpsOutputTask GetEpsFtpTask(EpsOutput epsOutput, string targetFolder,
                                            string exportFormat = "wmsMLC.EPS.wmsEPS.ExportTypes.FRExcel2007")
        {
            var task = new EpsOutputTask
            {
                Output           = epsOutput,
                OutputTaskCode   = EpsOutputTaskCodes.OTC_FTP,
                OutputTaskOrder  = 1,
                OutputTaskStatus = OutputStatuses.OS_NEW
            };

            task.OutputTask_EpsOutputParam_List = new Quartz.Collection.HashSet <EpsOutputParam>
            {
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.TargetFolder,
                    OutputParamValue = targetFolder
                },
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.FTPServerName,
                    OutputParamValue = "10.0.0.19"
                },
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.FTPServerLogin,
                    OutputParamValue = "ftp_tester"
                },
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.FTPServerPassword,
                    OutputParamValue = "123"
                },
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.FileFormat,
                    OutputParamValue = exportFormat
                }
            };
            return(task);
        }
        public void When_outputtask_has_more_than_one_export_parameter_than_error()
        {
            var epsConfig    = GetEpsConfiguration();
            var configurator = new EpsJobConfigurator(epsConfig, new MacroProcessor());

            var output = new EpsOutput
            {
                OutputID     = -100,
                OutputStatus = OutputStatuses.OS_ON_TRANSFER,
                EpsHandler   = 100,
                Login_r      = "test_user_login"
            };

            output.Output_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType  = EpsParamTypes.EPS,
                OutputParamCode  = EpsTaskParameterTypes.Zip,
                OutputParamValue = "1"
            });
            output.Output_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType  = EpsParamTypes.EPS,
                OutputParamCode  = EpsTaskParameterTypes.ReserveCopy,
                OutputParamValue = "1"
            });

            var emailTask = new EpsOutputTask
            {
                OutputTaskID     = -101,
                OutputTaskCode   = EpsOutputTaskCodes.OTC_MAIL,
                OutputTaskOrder  = 1,
                OutputTaskStatus = OutputStatuses.OS_NEW,
            };

            emailTask.OutputTask_EpsOutputParam_List.Add(new EpsOutputParam()
            {
                OutputParamType  = EpsParamTypes.TSK,
                OutputParamCode  = EpsTaskParameterTypes.FileFormat,
                OutputParamValue = "test1"
            });
            emailTask.OutputTask_EpsOutputParam_List.Add(new EpsOutputParam()
            {
                OutputParamType  = EpsParamTypes.TSK,
                OutputParamCode  = EpsTaskParameterTypes.FileFormat,
                OutputParamValue = "test2"
            });
            output.Output_EpsOutputTask_List.Add(emailTask);

            var session      = new Mock <ISession>();
            var resultConfig = configurator.Configure(output, session.Object, (i, exception, arg3) => { });
        }
示例#9
0
        private EpsOutput GetEpsOutput()
        {
            var res = new EpsOutput
            {
                EpsHandler   = -100,
                Host_r       = Environment.MachineName,
                OutputStatus = OutputStatuses.OS_NEW,
                Login_r      = AutoTestUser
            };

            res.Output_EpsOutputParam_List = new Quartz.Collection.HashSet <EpsOutputParam>
            {
                new EpsOutputParam
                {
                    Output           = res,
                    OutputParamType  = EpsParamTypes.REP,
                    OutputParamCode  = EpsTaskParameterTypes.EpsReport,
                    OutputParamValue = "Test001.frx"
                },
                new EpsOutputParam
                {
                    Output              = res,
                    OutputParamType     = EpsParamTypes.REP,
                    OutputParamCode     = "Parameter1",
                    OutputParamValue    = "test0011",
                    OutputParamSubValue = "Test001.frx"
                },
                new EpsOutputParam
                {
                    Output              = res,
                    OutputParamType     = EpsParamTypes.REP,
                    OutputParamCode     = "Parameter2",
                    OutputParamValue    = "test0012",
                    OutputParamSubValue = "Test001.frx"
                },
                new EpsOutputParam
                {
                    Output           = res,
                    OutputParamType  = EpsParamTypes.REP,
                    OutputParamCode  = EpsTaskParameterTypes.ResultReportFile,
                    OutputParamValue =
                        "${SQL=select 'REPORT_${SYSMACHINENAME}_${UserCode}_${DATE:yyyyMMdd}_${Parameter1}_${Parameter2}' from dual}",
                    OutputParamSubValue = "Test001.frx"
                }
            };

            return(res);
        }
        public void When_Output_login_r_field_is_empty_than_error()
        {
            var epsConfig    = GetEpsConfiguration();
            var configurator = new EpsJobConfigurator(epsConfig, new MacroProcessor());

            var output = new EpsOutput
            {
                OutputID     = -100,
                OutputStatus = OutputStatuses.OS_ON_TRANSFER,
                EpsHandler   = 100,
                Login_r      = null, //"test_user_login",
            };

            var session = new Mock <ISession>();

            configurator.Configure(output, session.Object, (i, exception, arg3) => { });
        }
示例#11
0
        public IEpsJobConfig Configure(EpsOutput output, ISession session,
                                       Action <int, Exception, TimeSpan> taskCompleteAction)
        {
            Contract.Requires(output != null);
            Contract.Requires(session != null);
            Contract.Requires(taskCompleteAction != null);

            CheckOutput(output);

            // получаем отдельный инстанс макро-процессора
            var childMacroProcessor = _baseMacroProcessor.GetChildProcessor();

            // добавлем специализированный параметр макроса, который может быть использован далее
            childMacroProcessor.Add(UserNameMacro, output.Login_r);

            // добавляем обработчик для специального макроса SQL
            childMacroProcessor.Add("SQL", macroString => ProcessSqlMacro(macroString, session, null));

            var res = new EpsJobConfig
            {
                JobId      = output.OutputID,
                Parameters = output
                             .Output_EpsOutputParam_List
                             .Where(i => i.OutputParamType == EpsParamTypes.EPS)
                             .Select(i => new EpsJobParameter
                {
                    Code     = i.OutputParamCode,
                    Value    = childMacroProcessor.Process(i.OutputParamValue),
                    Subvalue = childMacroProcessor.Process(i.OutputParamSubValue)
                })
                             .ToArray(),
                Reports = CreateReportConfigs(childMacroProcessor, output, session)
            };

            // добавлем специализированный параметр макроса, который может быть использован далее
            childMacroProcessor.Add(ResultReportFileNameMacro,
                                    string.Join(";",
                                                res.Reports.Where(i => !string.IsNullOrEmpty(i.ReportResultFileName))
                                                .Select(i => i.ReportResultFileName)));
            // конфигурируем задания
            res.Tasks = CreateTaskConfigs(childMacroProcessor, output, taskCompleteAction);

            return(res);
        }
示例#12
0
 private void SaveOutput(EpsOutput epsOutput)
 {
     using (var session = _sessionFactory.OpenSession())
         using (var transaction = session.BeginTransaction())
         {
             session.Save(epsOutput);
             foreach (var epsOutputTask in epsOutput.Output_EpsOutputTask_List)
             {
                 session.Save(epsOutputTask);
                 foreach (var taskParam in epsOutputTask.OutputTask_EpsOutputParam_List)
                 {
                     session.Save(taskParam);
                 }
             }
             foreach (var outputParam in epsOutput.Output_EpsOutputParam_List)
             {
                 session.Save(outputParam);
             }
             transaction.Commit();
         }
 }
示例#13
0
        private EpsOutputTask GetEpsMailTask(EpsOutput epsOutput,
                                             string exportFormat = "wmsMLC.EPS.wmsEPS.ExportTypes.FRText")
        {
            var task = new EpsOutputTask
            {
                Output           = epsOutput,
                OutputTaskCode   = EpsOutputTaskCodes.OTC_MAIL,
                OutputTaskOrder  = 1,
                OutputTaskStatus = OutputStatuses.OS_NEW
            };

            task.OutputTask_EpsOutputParam_List = new Quartz.Collection.HashSet <EpsOutputParam>
            {
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.AsAttachment,
                    OutputParamValue = "1"
                },
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.Email,
                    OutputParamValue = "*****@*****.**"
                },
                new EpsOutputParam
                {
                    Output           = epsOutput,
                    OutputTask       = task,
                    OutputParamCode  = EpsTaskParameterTypes.FileFormat,
                    OutputParamValue = exportFormat
                }
            };
            return(task);
        }
示例#14
0
        private static IEpsTaskConfig[] CreateTaskConfigs(IMacroProcessor macroProcessor, EpsOutput output,
                                                          Action <int, Exception, TimeSpan> taskCompleteAction)
        {
            var jobParameters =
                output.Output_EpsOutputParam_List.Where(i => i.OutputParamType == EpsParamTypes.EPS).ToArray();

            //TODO: выяснить почему это праметры Job-а, а не Task-а
            var isNeedZip =
                jobParameters.Any(i => i.OutputParamCode == EpsTaskParameterTypes.Zip && Equals(i.OutputParamValue, "1"));
            var isNeedReserveCopy =
                jobParameters.Any(
                    i => i.OutputParamCode == EpsTaskParameterTypes.ReserveCopy && Equals(i.OutputParamValue, "1"));

            var res = new List <IEpsTaskConfig>();

            foreach (var task in output.Output_EpsOutputTask_List)
            {
//                var childMacroProcessor = _macroProcessor.GetChildProcessor();
//                foreach (var taskParam in task.OutputTask_EpsOutputParam_List.Where(i => !EpsTaskParameterTypes.IsKnownParameter(i.OutputParamCode)))
//                    childMacroProcessor.Add(taskParam.OutputParamCode, taskParam.OutputParamValue);
                var taskConfig = CreateTaskConfig(task, macroProcessor, isNeedZip, isNeedReserveCopy, taskCompleteAction);
                res.Add(taskConfig);
            }
            return(res.ToArray());
        }
示例#15
0
        /// <summary>
        /// Печать отчёта.
        /// </summary>
        public void PrintReport(string reportCode, string executor, Dictionary <string, object> parameters, int?timeoutms)
        {
            Contract.Requires(!string.IsNullOrEmpty(reportCode));
            Contract.Requires(!string.IsNullOrEmpty(executor));

            WmsReport         report;
            EpsPrinterLogical logicalPrinter;
            var reportCodeInternal       = reportCode;
            var reportRedefinitionCopies = 1;
            int copies;

            using (var session = SessionFactory.OpenSession())
            {
                report = session.Get <WmsReport>(reportCode);
                if (report == null)
                {
                    throw new Exception(string.Format("Не найден отчёт '{0}'.", reportCodeInternal));
                }

                if (report.ReportFile_r == null)
                {
                    throw new Exception(string.Format("Отсутствует файл отчёта у отчета '{0}'.", reportCodeInternal));
                }

                //Определяем отчет
                var tlist = new List <string>
                {
                    CreateTparam("REPORT_R", report.ReportFile_r.ReportFileName),
                    CreateTparam("HOST_R", null),
                    CreateTparam("PARTNERID", null)
                };
                var reportRedefinition = GetDefaultReport(CreateTListParams(tlist));

                if (reportRedefinition != null && !reportRedefinition.ReportRedefinitionLocked &&
                    !string.IsNullOrEmpty(reportRedefinition.ReportRedefinition))
                {
                    reportCodeInternal       = reportRedefinition.ReportRedefinition;
                    reportRedefinitionCopies = reportRedefinition.ReportRedefinitionCopies;

                    report = session.Get <WmsReport>(reportCodeInternal);
                    if (report == null)
                    {
                        throw new Exception(string.Format("Не найден отчёт '{0}' после переопределения.",
                                                          reportCodeInternal));
                    }
                }

                if (report.ReportLocked)
                {
                    throw new Exception(string.Format("Отчёт '{0}' заблокирован.", reportCodeInternal));
                }

                //Определяем принтер
                tlist = new List <string>
                {
                    CreateTparam("REPORT_R", report.Report),
                    CreateTparam("HOST_R", null),
                    CreateTparam("LOGIN_R", executor),
                    CreateTparam("MANDANTID", null),
                    CreateTparam("CHECKTIME", DateTime.Now.ToString(Converter.DefaultDateTimeStringFormat)),
                    CreateTparam("EVENTKINDCODE_R", null),
                    CreateTparam("FACTORYID_R", null)
                };
                var printStreamConfig = GetDefaultPrinter(CreateTListParams(tlist));
                if (printStreamConfig == null || printStreamConfig.PrintStreamLocked ||
                    printStreamConfig.LogicalPrinter_r == null)
                {
                    throw new Exception(string.Format("Не найден логический принтер для отчёта '{0}'.",
                                                      reportCodeInternal));
                }

                //Получаем логический принтер
                logicalPrinter = session.Get <EpsPrinterLogical>(printStreamConfig.LogicalPrinter_r.LogicalPrinter);
                if (logicalPrinter == null || logicalPrinter.LogicalPrinterLocked)
                {
                    throw new Exception(string.Format("Не найден логический принтер для отчёта '{0}'.",
                                                      reportCodeInternal));
                }

                if (logicalPrinter.PhysicalPrinter_r == null || logicalPrinter.PhysicalPrinter_r == null ||
                    logicalPrinter.PhysicalPrinter_r.PhysicalPrinterLocked)
                {
                    throw new Exception(string.Format("Не найден физический принтер для отчёта '{0}'.",
                                                      reportCodeInternal));
                }

                var printStreamConfigCopies = printStreamConfig.PrintStreamCopies;
                copies = report.ReportCopies * reportRedefinitionCopies * printStreamConfigCopies *
                         logicalPrinter.LogicalPrinterCopies;
            }

            //Формируем EpsOutput
            var output = new EpsOutput
            {
                Login_r = executor,
                ReportFileSubFolder_r      = report.ReportFile_r.ReportFileSubFolder,
                Output_EpsOutputParam_List = new HashSet <EpsOutputParam>
                {
                    new EpsOutputParam
                    {
                        OutputParamCode  = EpsTaskParameterTypes.EpsReport,
                        OutputParamValue = report.ReportFile_r.ReportFile,
                        OutputParamType  = EpsParamTypes.REP
                    }
                }
            };

            if (parameters != null)
            {
                foreach (var pair in parameters)
                {
                    output.Output_EpsOutputParam_List.Add(new EpsOutputParam
                    {
                        OutputParamCode     = pair.Key,
                        OutputParamValue    = Convert.ToString(pair.Value),
                        OutputParamSubValue = report.ReportFile_r.ReportFile,
                        OutputParamType     = EpsParamTypes.REP
                    });
                }
            }

            output.Output_EpsOutputTask_List = new HashSet <EpsOutputTask>
            {
                new EpsOutputTask
                {
                    OutputTaskCode = EpsOutputTaskCodes.OTC_PRINT,
                    OutputTask_EpsOutputParam_List = new HashSet <EpsOutputParam>
                    {
                        new EpsOutputParam
                        {
                            OutputParamCode  = EpsTaskParameterTypes.PhysicalPrinter,
                            OutputParamValue = logicalPrinter.PhysicalPrinter_r.PhysicalPrinter,
                            OutputParamType  = EpsParamTypes.TSK
                        },
                        new EpsOutputParam
                        {
                            OutputParamCode  = EpsTaskParameterTypes.Copies,
                            OutputParamValue = copies.ToString(),
                            OutputParamType  = EpsParamTypes.TSK
                        }
                    }
                }
            };

            var context = SerializeEpsOutputToDto(new[] { output });

            if (string.IsNullOrEmpty(context))
            {
                return;
            }

            Post("print", context, timeoutms);
        }
示例#16
0
        private IEpsReportConfig[] CreateReportConfigs(IMacroProcessor macroProcessor, EpsOutput output,
                                                       ISession session)
        {
            var reportParams =
                output.Output_EpsOutputParam_List.Where(i => i.OutputParamType == EpsParamTypes.REP).ToArray();
            var reports = reportParams.Where(i => i.OutputParamCode == EpsTaskParameterTypes.EpsReport).ToArray();
            var res     = new List <IEpsReportConfig>();

            foreach (var report in reports)
            {
                var reportName = report.OutputParamValue;
                // проверяем не задали ли один отчет несколько раз
                if (res.Any(i => i.ReportName == reportName))
                {
                    throw new Exception(
                              string.Format(
                                  "Report {0} in output {1} was configured more than once. Please, check the settings.",
                                  report.OutputParamValue, output.OutputID));
                }

                // вычленяем параметры
                var currentReportParams = reportParams.Where(i => i.OutputParamSubValue == reportName).ToArray();

                // заполняем макросы
                var childMacroProcessor = macroProcessor.GetChildProcessor();
                foreach (
                    var taskParam in
                    currentReportParams.Where(i => !EpsTaskParameterTypes.IsKnownParameter(i.OutputParamCode)))
                {
                    childMacroProcessor.Add(taskParam.OutputParamCode, taskParam.OutputParamValue);
                }
                // безусловно добавляем пользователя
                childMacroProcessor.Add(EpsReportParameterTypes.UserCode, output.Login_r);

                var reportConfig = CreateReportConfig(output, childMacroProcessor, report, currentReportParams, session);
                res.Add(reportConfig);
            }
            return(res.ToArray());
        }
示例#17
0
        /// <summary>
        /// Создание задачи.
        /// </summary>
        public static EpsOutput CreateEpsOutput(string executor, EpsJob job, IEnumerable <EpsOutputTask> outputTasks,
                                                IEnumerable <WmsReport> reports, IEnumerable <EpsOutputParam> parameters,
                                                Dictionary <string, object> additionalParameters, ILog log)
        {
            var output = new EpsOutput
            {
                Login_r      = executor,
                Host_r       = Environment.MachineName,
                OutputStatus = OutputStatuses.OS_NEW,
                EpsHandler   = job.JobHandler ?? 20160614
            };

            if (parameters != null)
            {
                foreach (var p in parameters)
                {
                    p.Output = output;
                    output.Output_EpsOutputParam_List.Add(p);
                }
            }

            //TODO: тут нужно переделывать. если в задании 2 отчета из разных subfolder-ов, то в output попадет subfolder последнего
            if (reports != null && reports.Any())
            {
                var subFolders =
                    reports.Where(i => i.ReportFile_r != null)
                    .Select(i => i.ReportFile_r.ReportFileSubFolder)
                    .Distinct()
                    .ToArray();
                if (subFolders.Length > 1)
                {
                    throw new Exception(
                              string.Format("Job '{0}' has more than one reports from different sub folders '{1}'.",
                                            job.JobCode, string.Join("','", subFolders)));
                }

                output.ReportFileSubFolder_r = subFolders[0];
            }

            // задачи
            if (outputTasks != null)
            {
                foreach (var outputTask in outputTasks)
                {
                    outputTask.Output = output;
                    output.Output_EpsOutputTask_List.Add(outputTask);

                    if (outputTask.OutputTask_EpsOutputParam_List == null)
                    {
                        continue;
                    }

                    foreach (var t in outputTask.OutputTask_EpsOutputParam_List)
                    {
                        t.Output = output;
                    }
                }
            }

            if (log != null)
            {
                log.InfoFormat("Create new EpsOutput '{0}' from Executor '{1}'.", output.OutputID, executor);
            }

            return(output);
        }
示例#18
0
        private IEpsReportConfig CreateReportConfig(EpsOutput output, IMacroProcessor macroProcessor,
                                                    EpsOutputParam report, EpsOutputParam[] reportParams, ISession session)
        {
            var res = new EpsReportConfig();

            // добавляем параметры этого отчета
            res.Parameters = reportParams
                             .Where(p => !EpsTaskParameterTypes.IsKnownParameter(p.OutputParamCode))
                             .ToDictionary(i => i.OutputParamCode, i => macroProcessor.Process(i.OutputParamValue));
            // добавляем в отчет обязательный параметр UserCode
            res.Parameters.Add(EpsReportParameterTypes.UserCode, output.Login_r);

            // определяем имя файла отчета (оно же subvalue для параметров)
            res.ReportName = macroProcessor.Process(report.OutputParamValue);
            if (string.IsNullOrEmpty(res.ReportName))
            {
                throw new Exception(string.Format("Empty report file name in output {0}. Check the settings.",
                                                  output.OutputID));
            }

            //TODO: Нужно бы переделать алгоритм определения кода отчета. Фиг знает почему так.
            res.ReportCode = Path.GetFileNameWithoutExtension(res.ReportName);

            macroProcessor.AddOrReplace("SQL", macroString => ProcessSqlMacro(macroString, session, reportParams));

            //определяем имя выгрузки отчета (итоговое имя)
            var resultReportFile = GetParamValue(reportParams, macroProcessor, EpsTaskParameterTypes.ResultReportFile,
                                                 res.ReportName);

            // если ничего не задано - то берем имя файла отчета
            // иначе вычисляем результируещее имя с учетом макросов
            res.ReportResultFileName = IsNullOrEmptyAfterTrim(resultReportFile)
                ? res.ReportName
                : resultReportFile;
            //    : ProcessReportFileName(session, resultReportFile, reportParams);

            //получаем параметр типа EpsTaskParams.ChangeODBC. 0 - строку переопределять (переопределяет все подключения в отчете), 1 - строку не переопределять.
            var changeOdbcStr = GetParamValue(reportParams, macroProcessor, EpsTaskParameterTypes.ChangeODBC,
                                              res.ReportName);

            res.ConnectionString = changeOdbcStr == "1" ? null : EpsConfig.OdbcConnectionString;

            //получим пользовательский параметр ReportUseODAC
            //var wmsReport = session.Get<WmsReport>(res.ReportCode);
            //var reportUseOdac = wmsReport.CPV_List.FirstOrDefault(i => i.CustomParam.CustomParamCode == WmsReportCPV.ReportUseODACParameter);
            //TODO: исправить на вариант выше (когда Виталик починит метаданные)
            var reportUseOdac = session
                                .Query <WmsReportCPV>()
                                .Any(
                i =>
                i.CustomParam.CustomParamCode == WmsReportCPV.ReportUseODACParameter &&
                i.REPORT.Report == res.ReportCode && i.CPVValue == "1");

            //параметр ReportUseODAC в приоритете
            if (reportUseOdac)
            {
                res.ConnectionString = EpsConfig.OdacConnectionString;
            }

            //вычисляем полное имя к файлу отчета
            res.ReportFullFileName = (output.ReportFileSubFolder_r != null)
                ? Path.Combine(EpsConfig.ReportPath, output.ReportFileSubFolder_r, res.ReportName)
                : Path.Combine(EpsConfig.ReportPath, res.ReportName);

            return(res);
        }
        public void When_parameters_is_pased_than_its_recognized()
        {
            var epsConfig    = GetEpsConfiguration();
            var configurator = new EpsJobConfigurator(epsConfig, new MacroProcessor());

            var output = new EpsOutput
            {
                OutputID              = -100,
                OutputStatus          = OutputStatuses.OS_ON_TRANSFER,
                EpsHandler            = 100,
                Login_r               = "test_user_login",
                ReportFileSubFolder_r = "TST"
            };

            output.Output_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType  = EpsParamTypes.EPS,
                OutputParamCode  = EpsTaskParameterTypes.Zip,
                OutputParamValue = "1"
            });
            output.Output_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType  = EpsParamTypes.EPS,
                OutputParamCode  = EpsTaskParameterTypes.ReserveCopy,
                OutputParamValue = "1"
            });

            var emailTask = new EpsOutputTask
            {
                OutputTaskID     = -101,
                OutputTaskCode   = EpsOutputTaskCodes.OTC_MAIL,
                OutputTaskOrder  = 1,
                OutputTaskStatus = OutputStatuses.OS_NEW,
            };

            output.Output_EpsOutputTask_List.Add(emailTask);

            emailTask.OutputTask_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType  = EpsParamTypes.TSK,
                OutputParamCode  = EpsTaskParameterTypes.FileFormat,
                OutputParamValue = "wmsMLC.EPS.wmsEPS.ExportTypes.FRExcel2007"
            });

            emailTask.OutputTask_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType  = EpsParamTypes.TSK,
                OutputParamCode  = EpsTaskParameterTypes.Conversion,
                OutputParamValue = "UTF-32"
            });

            emailTask.OutputTask_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType  = EpsParamTypes.TSK,
                OutputParamCode  = EpsTaskParameterTypes.Spacelife,
                OutputParamValue = "1"
            });

            var reportParam = new EpsOutputParam
            {
                OutputParamType  = EpsParamTypes.REP,
                OutputParamCode  = EpsTaskParameterTypes.EpsReport,
                OutputParamValue = "Test001.frx"
            };

            output.Output_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType     = EpsParamTypes.REP,
                OutputParamCode     = "Parameter1",
                OutputParamValue    = "value1",
                OutputParamSubValue = "Test001.frx"
            });
            output.Output_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType     = EpsParamTypes.REP,
                OutputParamCode     = "Parameter2",
                OutputParamValue    = "value2",
                OutputParamSubValue = "Test001.frx"
            });
            output.Output_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType     = EpsParamTypes.REP,
                OutputParamCode     = EpsTaskParameterTypes.ResultReportFile,
                OutputParamValue    = "${SQL=select REPORT_${SYSMACHINENAME}_${UserCode}_${DATE:yyyyMMdd}_${Parameter1}_${Parameter2}.txt from dual}",
                OutputParamSubValue = "Test001.frx"
            });
            output.Output_EpsOutputParam_List.Add(new EpsOutputParam
            {
                OutputParamType  = EpsParamTypes.REP,
                OutputParamCode  = EpsTaskParameterTypes.ChangeODBC,
                OutputParamValue = "1"
            });

            output.Output_EpsOutputParam_List.Add(reportParam);
            var resultReportName = string.Format("REPORT_{0}_{1}_{2:yyyyMMdd}_value1_value2.txt", Environment.MachineName, output.Login_r, DateTime.Now);

            var sqlQuery = new Mock <ISQLQuery>();

            sqlQuery.Setup(i => i.UniqueResult <string>()).Returns(resultReportName);

            var session = new Mock <ISession>();

            session.Setup(i => i.CreateSQLQuery(It.IsAny <string>())).Returns(sqlQuery.Object);
            var reportUseODACCpv = new WmsReportCPV
            {
                CPVValue    = "1",
                CustomParam = new WmsCustomParam {
                    CustomParamCode = WmsReportCPV.ReportUseODACParameter
                },
                REPORT = new WmsReport {
                    Report = Path.GetFileNameWithoutExtension(reportParam.OutputParamValue)
                }
            };

            using (ShimsContext.Create())
            {
                ShimLinqExtensionMethods.QueryOf1ISession(s => new[] { reportUseODACCpv }.AsQueryable());

                var resultConfig = configurator.Configure(output, session.Object, (i, exception, arg3) => { });

                resultConfig.JobId.Should().Be(output.OutputID);
                resultConfig.Tasks.Should().HaveCount(1);
                resultConfig.Reports.Should().HaveCount(1);

                var resultEmailTask = resultConfig.Tasks.Single(i => i.TaskId == emailTask.OutputTaskID);
                ("OTC_" + resultEmailTask.TaskExecutorType).Should().Be(emailTask.OutputTaskCode.ToString());
                resultEmailTask.IsNeedZip.Should().BeTrue();
                resultEmailTask.IsNeedReserveCopy.Should().BeTrue();
                resultEmailTask.ExportType.Should().NotBeNull();
                resultEmailTask.ExportType.Encoding.Should().Be(Encoding.UTF32);
                resultEmailTask.ExportType.Spacelife.Should().BeTrue();
                resultEmailTask.ExportType.Format.Should().Be("wmsMLC.EPS.wmsEPS.ExportTypes.FRExcel2007");
                resultEmailTask.HandleTaskComplete.Should().NotBeNull();

                var resultReport = resultConfig.Reports.Single(i => i.ReportName == reportParam.OutputParamValue);
                resultReport.ReportCode.Should().Be(Path.GetFileNameWithoutExtension(reportParam.OutputParamValue));
                resultReport.ConnectionString.Should().Be(epsConfig.OdacConnectionString);
                resultReport.ReportFullFileName.Should().Be(Path.Combine(epsConfig.ReportPath, output.ReportFileSubFolder_r, reportParam.OutputParamValue));
                resultReport.Parameters.Should().Contain("Parameter1", "value1");
                resultReport.Parameters.Should().Contain("Parameter2", "value2");
                resultReport.Parameters.Should().Contain(EpsReportParameterTypes.UserCode, output.Login_r);
                resultReport.ReportResultFileName.Should().Be(resultReportName);
            }
        }