private void SetUnitOfWork(NativeActivityContext context, IBaseManager mgr) { var uw = BeginTransactionActivity.GetUnitOfWork(context); if (uw != null) { mgr.SetUnitOfWork(uw); } }
protected override void Execute(NativeActivityContext context) { var bpCtx = Context.Get(context); if (bpCtx == null) { throw new NullReferenceException("BpContext"); } if (bpCtx.Items == null || bpCtx.Items.Length < 1) { var vs = IoC.Instance.Resolve <IViewService>(); vs.ShowDialog(bpCtx.Name, "Входной список пуст", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error, System.Windows.MessageBoxResult.OK); context.ScheduleActivity(_terminateWorkflow); return; } // выбор из коллекции только заданного типа Т var typedItems = bpCtx.Items.Where(i => (i.GetType() == typeof(T)) || (IsAssignableFrom && i is T)).ToArray(); if (typedItems.Length > 1 & !IsMultipleItems) { var vs = IoC.Instance.Resolve <IViewService>(); vs.ShowDialog(bpCtx.Name, "Выбрано более одного объекта", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error, System.Windows.MessageBoxResult.OK); context.ScheduleActivity(_terminateWorkflow); return; } if (typedItems.Length == 0) { Result.Set(context, new T[] {}); return; } // если не надо обновлять список if (bpCtx.DoNotRefresh) { Result.Set(context, typedItems.Cast <T>().ToArray()); return; } var manager = GetBaseManager(); var uow = BeginTransactionActivity.GetUnitOfWork(context); if (uow != null) { manager.SetUnitOfWork(uow); } manager.ClearCache(); var filter = FilterHelper.GetFilterIn(typeof(T), typedItems); var result = manager.GetFiltered(filter).ToArray(); Result.Set(context, result); }
protected override void Execute(NativeActivityContext context) { #region . Fill Header . var eventHeader = new EventHeader { EventKindCode = EventKindCode.Get(context), OperationCode = BillOperationCode.Get(context), ProcessCode = BPProcessCode.Get(context) }; var startDate = StartDate.Get(context); eventHeader.StartTime = startDate.HasValue ? startDate.Value : DateTime.Now; eventHeader.EndTime = EndDate.Get(context); eventHeader.MandantID = MandantId.Get <decimal?>(context); // авто-заполняемые поля eventHeader.Instance = context.WorkflowInstanceId.ToString(); #endregion . Fill Header . #region . Fill Params for Details . var evDetail = new EventDetail(); foreach (var parameter in Parameters) { var value = parameter.Value.Get(context); // пустые значение незачем передавать if (value == null) { continue; } if (evDetail.ContainsProperty(parameter.Key)) { evDetail.SetProperty(parameter.Key, value); } } #endregion . Fill Params for Details . var eventHeaderMgr = IoC.Instance.Resolve <IEventHeaderManager>(); var uw = BeginTransactionActivity.GetUnitOfWork(context); if (uw != null) { eventHeaderMgr.SetUnitOfWork(uw); } eventHeaderMgr.RegEvent(ref eventHeader, evDetail); context.SetValue(Result, eventHeader); }
protected override void Execute(NativeActivityContext context) { Result.Set(context, false); var entity = Entity.Get(context); if (entity == null) { throw new DeveloperException("Неопределен объект валидации."); } var entitykey = entity.GetKey(); if (entitykey == null) { throw new DeveloperException("Неопределен PK у сущности '{0}'.", entity); } var entitySource = SourceNameHelper.Instance.GetSourceName(entity.GetType()); CustomParam[] customParams; using (var managerCustomParam = IoC.Instance.Resolve <IBaseManager <CustomParam> >()) { var uow = BeginTransactionActivity.GetUnitOfWork(context); if (uow != null) { managerCustomParam.SetUnitOfWork(uow); } customParams = ((ICustomParamManager)managerCustomParam).GetCPByInstance(entitySource.ToUpper(), entitykey.To <string>()) .Where(p => p.CustomParamMustSet) .ToArray(); } if (customParams.Length == 0) { Result.Set(context, true); return; } var typeCustomParamValue = typeof(CustomParamValue); var errors = new List <string>(); using (var managerCustomParamValue = IoC.Instance.Resolve <IBaseManager <CustomParamValue> >()) { var uow = BeginTransactionActivity.GetUnitOfWork(context); if (uow != null) { managerCustomParamValue.SetUnitOfWork(uow); } foreach (var customParam in customParams) { var customParamValues = managerCustomParamValue.GetFiltered( string.Format("{0} = '{1}' AND {2} = '{3}' AND {4} = '{5}'", SourceNameHelper.Instance.GetPropertySourceName(typeCustomParamValue, CustomParamValue.CustomParamCodePropertyName), customParam.GetKey(), SourceNameHelper.Instance.GetPropertySourceName(typeCustomParamValue, CustomParamValue.CPV2EntityPropertyName), entitySource, SourceNameHelper.Instance.GetPropertySourceName(typeCustomParamValue, CustomParamValue.CPVKeyPropertyName), entitykey), GetModeEnum.Partial).ToArray(); if (customParamValues.Length == 0) { errors.Add(string.Format("У сущности '{0}' отсутствует обязательный пользовательский параметр '{1}'.", entity, customParam.CustomParamName)); continue; } errors.AddRange(customParamValues.Where(p => string.IsNullOrEmpty(p.CPVValue)) .Select( customParamValue => string.Format( "У сущности '{0}' не заполнено значение обязательного пользовательского параметра '{1}'.", entity, customParam.CustomParamName))); } } if (errors.Count == 0) { Result.Set(context, true); return; } if (ErrorMessage != null) { ErrorMessage.Set(context, string.Join(Environment.NewLine, errors.Distinct())); } }
protected override void Execute(NativeActivityContext context) { // получим все параметры var teCode = TeCode.Get(context); // переведем код ТЕ в верхний регистр if (!string.IsNullOrEmpty(teCode)) { teCode = teCode.ToUpper(); } var placeCode = PlaceCode.Get(context); var isPack = IsPack.Get(context); var length = Length.Get(context); var width = Width.Get(context); var height = Height.Get(context); var tareWeight = TareWeight.Get(context); var weight = Weight.Get(context); var mandants = Mandants.Get(context); var teTypeCode = TeTypeCode.Get(context); var autoTeType = AutoTeType.Get(context); var extFilter = Filter.Get(context); _fontSize = FontSize.Get(context); var suspendNotifyCollectionChanged = SuspendNotifyCollectionChanged.Get(context); var teManager = IoC.Instance.Resolve <IBaseManager <TE> >(); try { if (suspendNotifyCollectionChanged) { teManager.SuspendNotifications(); } // если поле тип ТЕ пустое и не стоит признак пытаться определить тип ТЕ автоматически if (string.IsNullOrEmpty(teTypeCode) && !autoTeType) { throw new OperationException("Не указан тип ТЕ"); } // если поле тип ТЕ заполнено и установлен признак получения автоматически if (!string.IsNullOrEmpty(teTypeCode) && autoTeType) { throw new OperationException("Неверные настройки получения типа ТЕ"); } var uw = BeginTransactionActivity.GetUnitOfWork(context); if (uw != null) { throw new OperationException("Действие в транзакции запрещено"); } // проверим существование ТЕ if (!string.IsNullOrEmpty(teCode)) { var bpManager = IoC.Instance.Resolve <IBPProcessManager>(); var existTe = bpManager.CheckInstanceEntity("TE", teCode); if (existTe == 1) { var existTeObj = teManager.Get(teCode); if (existTeObj == null) { throw new OperationException("Нет прав на ТЕ с кодом {0}", teCode); } ExceptionResult.Set(context, null); TeCode.Set(context, teCode); OutTe.Set(context, existTeObj); Exist.Set(context, true); Result.Set(context, true); return; } } // фильтр на тип ТЕ var filter = string.Empty; // фильтр по мандантам if (!string.IsNullOrEmpty(mandants)) { filter = string.Format( "tetypecode in (select tt2m.tetypecode_r from wmstetype2mandant tt2m where tt2m.partnerid_r in ({0}))", mandants); } // фильтр по упаковкам if (isPack) { filter = string.Format( "{0}tetypecode in (select CUSTOMPARAMVAL.cpvkey from wmscustomparamvalue CUSTOMPARAMVAL where CUSTOMPARAMVAL.CPV2ENTITY = 'TETYPE' and CUSTOMPARAMVAL.CUSTOMPARAMCODE_R = 'TETypeIsPackingL2' and CUSTOMPARAMVAL.CPVVALUE is not null and CUSTOMPARAMVAL.CPVVALUE != '0')", string.IsNullOrEmpty(filter) ? string.Empty : filter + " and "); } // дополнительный фильтр по типам ТЕ if (!string.IsNullOrEmpty(extFilter)) { filter = string.Format( "{0}{1}", string.IsNullOrEmpty(filter) ? string.Empty : filter + " and ", extFilter); } // если надо определить тип ТЕ автоматически if (autoTeType) { teTypeCode = BPH.DetermineTeTypeCodeByTeCode(teCode, filter); } var teTypeObj = GetTeType(teTypeCode, filter); // если не выбрали тип ТЕ if (teTypeObj == null) { ExceptionResult.Set(context, null); TeCode.Set(context, teCode); OutTe.Set(context, null); Exist.Set(context, false); Result.Set(context, false); return; } var teObj = new TE(); teObj.SetKey(teCode); teObj.SetProperty(TE.TETypeCodePropertyName, teTypeObj.GetKey()); teObj.SetProperty(TE.CreatePlacePropertyName, placeCode); teObj.SetProperty(TE.CurrentPlacePropertyName, placeCode); teObj.SetProperty(TE.StatusCodePropertyName, TEStates.TE_FREE.ToString()); teObj.SetProperty(TE.TEPackStatusPropertyName, isPack ? TEPackStatus.TE_PKG_CREATED.ToString() : TEPackStatus.TE_PKG_NONE.ToString()); teObj.SetProperty(TE.TELengthPropertyName, length ?? teTypeObj.GetProperty(TEType.LengthPropertyName)); teObj.SetProperty(TE.TEWidthPropertyName, width ?? teTypeObj.GetProperty(TEType.WidthPropertyName)); teObj.SetProperty(TE.TEHeightPropertyName, height ?? teTypeObj.GetProperty(TEType.HeightPropertyName)); teObj.SetProperty(TE.TETareWeightPropertyName, tareWeight ?? teTypeObj.GetProperty(TEType.TareWeightPropertyName)); teObj.SetProperty(TE.TEMaxWeightPropertyName, tareWeight ?? teTypeObj.GetProperty(TEType.MaxWeightPropertyName)); teObj.SetProperty(TE.TEWeightPropertyName, weight ?? teTypeObj.GetProperty(TEType.TareWeightPropertyName)); ((ISecurityAccess)teManager).SuspendRightChecking(); teManager.Insert(ref teObj); ExceptionResult.Set(context, null); TeCode.Set(context, teCode); OutTe.Set(context, teObj); Exist.Set(context, false); Result.Set(context, true); } catch (Exception ex) { TeCode.Set(context, teCode); ExceptionResult.Set(context, ex); OutTe.Set(context, null); Exist.Set(context, false); Result.Set(context, false); } finally { if (suspendNotifyCollectionChanged) { teManager.ResumeNotifications(); } ((ISecurityAccess)teManager).ResumeRightChecking(); } }
protected override void Execute(NativeActivityContext context) { var methodName = Value.Get(context); if (ActivityHelpers.UseActivityStackTrace(context)) { var tracking = new CustomTrackingRecord(DisplayName); tracking.Data.Add("Value", string.Format("Method='{0}'", methodName)); context.Track(tracking); } IUnitOfWork uow = null; var isNeedDisposeUoW = false; try { // определяем был ли объявлен UoW uow = BeginTransactionActivity.GetUnitOfWork(context); int?timeOut = TimeOut.Get(context); // если не создали - делаем сами if (uow == null) { uow = UnitOfWorkHelper.GetUnit(true); isNeedDisposeUoW = true; } if (timeOut.HasValue) { uow.TimeOut = timeOut; } var mgr = IoC.Instance.Resolve <T>(); if (uow != null) { mgr.SetUnitOfWork(uow); } // вызываем нужный метод var isResultParamExists = Parameters.ContainsKey(ResultParamName); var argsCount = Parameters.Count - (isResultParamExists ? 1 : 0); var args = new object[argsCount]; var methodInfo = mgr.GetType().GetMethod(methodName); var methodParams = methodInfo.GetParameters(); for (var i = 0; i < argsCount; i++) { args[i] = Parameters[methodParams[i].Name].Get(context); } var isNeedResult = methodInfo.ReturnType != typeof(void); if (!isNeedResult && isResultParamExists) { throw new DeveloperException( "Метод {0} не возвращает результат, однако найден параметр с именем {1}", methodName, ResultParamName); } // запускаем метод var resultValue = methodInfo.Invoke(mgr, args); // получаем результаты if (isNeedResult) { Parameters[ResultParamName].Set(context, resultValue); } for (int i = 0; i < args.Length; i++) { var element = Parameters.ElementAt(i); var argument = Parameters.ElementAt(i).Value; if ((argument.Direction == ArgumentDirection.Out || argument.Direction == ArgumentDirection.InOut) & !element.Key.EqIgnoreCase(ResultParamName)) { argument.Set(context, args[i]); } } Result.Set(context, true); } catch (Exception ex) { Result.Set(context, false); Exception.Set(context, ex); _log.Warn("Ошибка запуска метода. Причина: " + ExceptionHelper.GetErrorMessage(ex), ex); } finally { if (isNeedDisposeUoW && uow != null) { try { uow.Dispose(); } catch (Exception ex) { _log.Warn("Не удалось закрыть сессию UoW. Причина: " + ExceptionHelper.GetErrorMessage(ex), ex); } } } }
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); }
private void ProcessCreateProduct(NativeActivityContext context) { #region . Checks&Ini . if (_items == null || _items.Count == 0) { return; } var iwbId = IWBId.Get(context); var placeCode = PlaceCode.Get(context); var operationCode = OperationCode.Get(context); var isMigration = IsMigration.Get(context) ? 1 : 0; var timeOut = TimeOut.Get(context); var wfUow = BeginTransactionActivity.GetUnitOfWork(context); // получаем менеджер приемки Min min = null; using (var mgr = IoC.Instance.Resolve <IBPProcessManager>()) { if (wfUow != null) { mgr.SetUnitOfWork(wfUow); } var minId = mgr.GetDefaultMIN(iwbId); if (minId.HasValue) { using (var mgrIn = IoC.Instance.Resolve <IBaseManager <Min> >()) { if (wfUow != null) { mgr.SetUnitOfWork(wfUow); } min = mgrIn.Get(minId); } } } // определяем параметры приемки var isMinCpvExist = min != null && min.CustomParamVal != null && min.CustomParamVal.Count != 0; var isNeedControlOver = isMinCpvExist && min.CustomParamVal.Any( i => i.CustomParamCode == MinCpv.MINOverEnableCpvName && i.CPVValue == "1"); var isNeedConfirmOver = isNeedControlOver && min.CustomParamVal.Any( i => i.CustomParamCode == MinCpv.MINOverEnableNeedConfirmCpvName && i.CPVValue == "1"); var isMinLimit = isMinCpvExist && min.CustomParamVal.Any(i => i.VCustomParamParent == MinCpv.MinLimitL2CpvName); var itemsToProcess = new List <IWBPosInput>(); #endregion #region . BatchCode&OverCount . foreach (var item in _items) { var itemKey = item.GetKey(); if (!item.IsSelected || itemKey == null) { _failedItems.Enqueue(item); continue; } item.ManageFlag = null; //Ошибки при распознавании batch-кода if (!item.NotCriticalBatchcodeError && !item.IsBpBatchcodeCompleted) { var message = string.IsNullOrEmpty(item.BatchcodeErrorMessage) ? "Ошибка не определена." : item.BatchcodeErrorMessage; SkipItem(item, message); continue; } if (item.RequiredSKUCount < 1) { SkipItem(item, "Некорректно введено 'Количество по факту'"); continue; } // если пытаемся принять с избытком if (isNeedControlOver) { var count = item.ProductCountSKU + (double)item.RequiredSKUCount; var overCount = count - item.IWBPosCount; if (overCount > 0 && isNeedConfirmOver) { var questionMessage = string.Format( "Позиция '{0}' ед.уч. '{1}'.{4}Фактическое кол-во = '{2}'.{4}Излишек составит '{3}'.{4}Принять излишек?", itemKey, item.SKUNAME, count, overCount, Environment.NewLine); var dr = _viewService.ShowDialog( GetDefaultMessageBoxCaption(iwbId), questionMessage, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes, 14); if (dr == MessageBoxResult.Yes) { item.ManageFlag += (!string.IsNullOrEmpty(item.ManageFlag) ? "," : string.Empty) + "OVERASK_OK"; } else { var message = string.Format("Пользователь отказался принимать излишек по позиции '{0}'", itemKey, item.SKUNAME); SkipItem(item, message); continue; } } } itemsToProcess.Add(item); } #endregion // группируем по артикулу var groupItems = itemsToProcess.GroupBy(i => i.ArtCode).ToArray(); //обработка сроков годности if (isMinLimit) { var ret = ProccesExpireDate(itemsToProcess, min, groupItems, wfUow, iwbId); if (!ret) { return; } } var ask = new ConcurrentQueue <IWBPosInput>(); while (true) { RunCreateProduct(itemsToProcess, ref ask, timeOut, wfUow, operationCode, iwbId, isMigration, placeCode, isNeedControlOver); if (ask == null || ask.Count <= 0) { break; } itemsToProcess.Clear(); foreach (var item in ask) { var message = string.Format("Принять излишек по позиции '{0}' ед.уч. '{1}' ?", item.GetKey(), item.SKUNAME); var res = _viewService.ShowDialog(GetDefaultMessageBoxCaption(iwbId), message, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes, 14); if (res != MessageBoxResult.Yes) { SkipItem(item, string.Format("Пользователь отказался принимать излишек по позиции '{0}'", item.GetKey())); continue; } itemsToProcess.Add(item); } while (!ask.IsEmpty) { IWBPosInput someItem; ask.TryDequeue(out someItem); } } }