示例#1
0
        /// <summary>
        /// The create.
        /// </summary>
        /// <returns>
        /// The <see cref="ResultFieldOptions"/>.
        /// </returns>
        public static SampleFieldOptions Create(PropertyInfo property, IEditableRoot model)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var result = new SampleFieldOptions();

            var settingsString = model.GetValueByPropertyName(string.Format(CultureInfo.InvariantCulture, "{0}{1}", property.Name, Constants.SampleSettingPostfix));
            if (!string.IsNullOrEmpty(settingsString))
            {
                var sampleSettings = XElement.Parse(settingsString);
                SetProperties(result, sampleSettings, model);
            }

            result.IsNewItem = model.Id == 0;

            return result;
        }
示例#2
0
        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="editableRoot">The editable root.</param>
        /// <returns></returns>
        public object GetValue(DetailsSaveFieldModel field, IEditableRoot editableRoot)
        {
            if (field.Settings == null)
                return null;

            var fileFieldOptions = field.Settings.ToObject<FileFieldOptions>();
            if (fileFieldOptions == null)
                return null;

            IFileProcess fileEdit = editableRoot.GetValueByPropertyName(field.SystemName);
            if (fileEdit == null)
                return null;

            fileEdit.FileName = fileFieldOptions.FileName;
            fileEdit.OriginalFileName = fileFieldOptions.OriginalFileName;

            if (!fileFieldOptions.Locked)
            {
                fileEdit.LockedDate = null;
            }
            else if (!fileEdit.Locked.HasValue || !fileEdit.Locked.Value)
            {
                fileEdit.LockedDate = DateTime.Now;
            }
            fileEdit.Locked = fileFieldOptions.Locked;
            fileEdit.LockedByAccountId = fileFieldOptions.LockedByAccountId;
            fileEdit.LockedByAccountName = fileFieldOptions.LockedByAccountName;

            if (fileFieldOptions.AuditLog != null)
            {
                fileEdit.FileChangeInfo = new AuditLogInfo
                {
                    LogType = fileFieldOptions.AuditLog.LogType,
                    ProcessName = fileFieldOptions.AuditLog.ProcessName,
                    ItemId = fileFieldOptions.AuditLog.ItemId,
                    FieldName = fileFieldOptions.AuditLog.FieldName,
                    OldValue = fileFieldOptions.AuditLog.OldValue,
                    NewValue = fileFieldOptions.AuditLog.NewValue,
                    DateUpdated = fileFieldOptions.AuditLog.DateUpdated,
                    User = fileFieldOptions.AuditLog.User
                };
            }

            var newModel = ((IBusinessBase)fileEdit).Save();

            if (fileFieldOptions.FileId == 0)
            {
                editableRoot.SetValueByPropertyName(string.Format("{0}Id", field.SystemName), ((IDynamicObject)newModel).Id);
            }

            return newModel;
        }
示例#3
0
        /// <summary>
        /// Copies the answer data.
        /// </summary>
        /// <param name="answerFieldValues">
        /// The answer field values.
        /// </param>
        /// <param name="answerItem">
        /// The answer item.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="answerFieldValues"/> parameter is null.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="answerItem"/> parameter is null.
        /// </exception>
        public static void CopyAnswerData(ICollection<ChecklistAnswerFieldValue> answerFieldValues, IEditableRoot answerItem)
        {
            if (answerFieldValues == null)
                throw new ArgumentNullException("answerFieldValues");

            if (answerItem == null)
                throw new ArgumentNullException("answerItem");

            using (new ThreadLocalBypassPropertyCheckContext())
            {
                foreach (var fieldValue in answerFieldValues.Where(f => f.Value != null))
                {
                    var answerProperty = answerItem.GetPropertyByName(fieldValue.FieldName);
                    var answerValue = answerItem.GetValueByPropertyName(fieldValue.FieldName);

                    if (fieldValue.Value is ICrossRefItemList && answerValue is ICrossRefItemList)
                    {
                        var qList = (ICrossRefItemList)fieldValue.Value;
                        var aList = (ICrossRefItemList)answerValue;

                        aList.Clear();
                        foreach (var crItem in qList.Cast<ICrossRefItemInfo>())
                        {
#if !SILVERLIGHT
                            aList.Assign(crItem.Id);
#else
                            aList.Assign(crItem.Id, (o, e) => { });
#endif
                        }

                        continue;
                    }

                    if (answerProperty.PropertyType.IsInstanceOfType(fieldValue.Value))
                    {
                        answerItem.SetValueByPropertyName(fieldValue.FieldName, fieldValue.Value);
                    }
                    else
                    {
                        throw new VeyronException(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Cannot assign value of type \"{0}\" to property \"{1}\".",
                                fieldValue.Value.GetType().AssemblyQualifiedName,
                                fieldValue.FieldName));
                    }
                }
            }
        }
        public static IFieldOptions Create(PropertyInfo property, IEditableRoot editableRoot)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            if (editableRoot == null)
            {
                throw new ArgumentNullException("editableRoot");
            }

            var crossRefAttr = property.GetCustomAttributes(typeof(CrossRefFieldAttribute), false).Select(d => d).FirstOrDefault() as CrossRefFieldAttribute;
            if (crossRefAttr == null)
            {
                throw new VeyronException("CrossRef attribute not found on Cross-reference field property");
            }

            string valueAsText = "Unknown";

            var crId = editableRoot.GetValueByPropertyName(property.Name) as int?;

            if (crId.HasValue)
            {
                var ancestor = editableRoot.GetAncestor(property);
                if (ancestor != null)
                {
                    var crItem = DynamicTypeManager.Instance.GetCrossReferenceItem(ancestor.ProcessName, property.Name, crId.Value);
                    if (crItem != null)
                    {
                        valueAsText = crItem.GetValueByPropertyName(crossRefAttr.RefFieldName) == null ? "Unknown" : crItem.GetValueByPropertyName(crossRefAttr.RefFieldName).ToString();
                    }
                }
            }
            
            var result = new SingleCrossRefFieldOptions
            {
                ValueAsText = valueAsText, 
                ProcessSystemName = crossRefAttr.ReferenceTableName, 
                FieldName = crossRefAttr.RefFieldName,
                AllowViewDetail = crossRefAttr.AllowViewDetail,
                AllowClear = crossRefAttr.AllowClear
            };

            return result;
        }
示例#5
0
        /// <summary>
        /// Updates the specified source.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="destination">The destination.</param>
        /// <exception cref="System.InvalidOperationException">
        /// Failed to load system options.
        /// or
        /// Temp document UNC is empty.
        /// </exception>
        public void Update(IDynamicObject source, IEditableRoot destination)
        {
            var fileLocation = ESyncTypeConverter.Convert<string>(_valueCalculator.GetValue(source, _field.MappingKey));

            if (string.IsNullOrWhiteSpace(fileLocation))
                return;

            var systemOptions = SystemOptionsInfo.GetSystemOptionsInfo();

            if (systemOptions == null)
                throw new InvalidOperationException("Failed to load system options.");

            var tempDocumentUnc = systemOptions.TempDocumentUNC;

            if (string.IsNullOrWhiteSpace(tempDocumentUnc))
                throw new InvalidOperationException("Temp document UNC is empty.");

            if (!Directory.Exists(tempDocumentUnc))
                Directory.CreateDirectory(tempDocumentUnc);

            var fileField = (IFileProcess)destination.GetValueByPropertyName(_property.Name);

            if (fileField == null)
                return;

            fileField.OriginalFileName = Path.GetFileName(fileLocation);
            fileField.FileName = Guid.NewGuid() + Path.GetExtension(fileLocation);

            var tempFilePath = Path.Combine(tempDocumentUnc, fileField.FileName);

            using (var client = new WebClient())
            {
                // Copy file to temp directory.
                client.DownloadFile(fileLocation, tempFilePath);
            }

            var convertToPdef = (fileField.ConvertToPdf ?? false) && FileHelper.ConversionToPdfSupported(fileField.FileName);

            if (convertToPdef)
            {
                fileField.ConvertedFileName = FileHelper.GetNewFileNameWithPdfExtension(fileField.FileName);
                var tempPdfFilePath = Path.Combine(tempDocumentUnc, fileField.ConvertedFileName);

                if (!fileField.IsPdfWithReport())
                    FileManager.ConvertToPdf(tempFilePath, tempPdfFilePath);
            }

            // Copy file to final directory.
            fileField.UploadFile();

            if (convertToPdef)
            {
                if (fileField.IsPdfWithReport())
                {
                    (new FileManager()).UpdatePdf(destination, fileField);
                }
                else
                {
                    //When we change IFileProcess, we'll need to add UploadFile(string fileName) method
                    var fileName = fileField.FileName;
                    fileField.FileName = fileField.ConvertedFileName;
                    fileField.UploadFile();
                    fileField.FileName = fileName;
                }
            }
        }
示例#6
0
        /// <summary>
        /// Gets the sample type of the specified sample field.
        /// </summary>
        /// <param name="item">
        /// The editable root item.
        /// </param>
        /// <param name="sampleFieldName">
        /// The sample field name.
        /// </param>
        /// <returns>
        /// The <see cref="SampleTypes"/>.
        /// </returns>
        public SampleTypes GetSampleType(IEditableRoot item, string sampleFieldName)
        {
            var settings = GetSampleSettings(item, sampleFieldName);

            if (!string.IsNullOrEmpty(settings.SampleTypeFieldName))
            {
                SampleTypes sampleType;
                if (Enum.TryParse(item.GetValueByPropertyName(settings.SampleTypeFieldName), out sampleType))
                    return sampleType;
            }

            return SampleTypes.Number;
        }
示例#7
0
        /// <summary>
        /// Gets the settings of the specified sample field.
        /// </summary>
        /// <param name="item">
        /// The editable root item.
        /// </param>
        /// <param name="sampleFieldName">
        /// The sample field name.
        /// </param>
        /// <returns>
        /// The <see cref="SampleSettings"/>.
        /// </returns>
        public SampleSettings GetSampleSettings(IEditableRoot item, string sampleFieldName)
        {
            var xml = item.GetValueByPropertyName(sampleFieldName + Constants.SampleSettingPostfix) as string;

            return SampleSettings.Parse(xml);
        }
        private static ChartPanel GetChartDescriptor(IEditableRoot instance, string exprFieldName, string spcFieldName, ChartTypesEnum chartType, int subgroupSize, int dataPoints = 0)
        {
            ChartPanel chartDescriptor = null;

            MobileDictionary<string, ChartPanel> dict = null;
            if (!exprFieldName.Contains("_Rule"))
            {
                dict = instance.GetValueByPropertyName("ChartDescriptorExp") as MobileDictionary<string, ChartPanel>;
                if (dict != null)
                    dict.TryGetValue(string.Format("{0}{1}", exprFieldName, spcFieldName), out chartDescriptor);
                else
                    dict = new MobileDictionary<string, ChartPanel>();
            }

            if (chartDescriptor == null)
            {
                chartDescriptor = SpcManager.CreateChartDescriptor(chartType);
                chartDescriptor.DataPoints = dataPoints;
                chartDescriptor.SubgroupSize = subgroupSize;

                chartDescriptor = MethodCaller.CallFactoryMethod(instance.GetType(), "GetSampleDataForSPC", spcFieldName, instance, chartType, chartDescriptor, true) as ChartPanel;

                if (!exprFieldName.Contains("_Rule"))
                {
                    ChartPanel chartPanel;
                    if (dict.TryGetValue(string.Format("{0}{1}", exprFieldName, spcFieldName), out chartPanel))
                        dict[string.Format("{0}{1}", exprFieldName, spcFieldName)] = chartDescriptor;
                    else
                        dict.Add(string.Format("{0}{1}", exprFieldName, spcFieldName), chartDescriptor);

                    instance.LoadValueByPropertyName("ChartDescriptorExp", dict);
                }
            }
            else
            {
                chartDescriptor.DataPoints = dataPoints;
                chartDescriptor.SubgroupSize = subgroupSize;

                chartDescriptor = MethodCaller.CallFactoryMethod(instance.GetType(), "GetSampleDataForSPC", spcFieldName, instance, chartType, chartDescriptor, true) as ChartPanel;
            }

            return chartDescriptor;
        }        
示例#9
0
 private static bool IsMatch(IEditableRoot answer, IEnumerable<ColumnFilter> filters)
 {
     return filters.All(filter => AreEqual(answer.GetValueByPropertyName(filter.ColumnName), filter.Value));
 }
示例#10
0
        private void SetMultiReferenceValue(DetailsSaveFieldModel field, IEditableRoot editableRoot)
        {
            var currentMcrValue = (ICrossRefItemList)editableRoot.GetValueByPropertyName(field.SystemName);
            if (field.Value == null)
            {
                currentMcrValue.Clear();
                return;
            }

            var mcrContent = JsonConvert.DeserializeObject<List<MultiCrossReferenceModel>>(field.Value.ToString());
            if (mcrContent == null || mcrContent.ToArray().Length == 0)
            {
                if (currentMcrValue != null)
                {
                    currentMcrValue.Clear();
                }
                return;
            }                      

            var newItemsList =  mcrContent
                .Where(mcrItem => !currentMcrValue.Contains(mcrItem.Id))
                .Select(c => (ICrossRefItemInfo)_dynamicTypeManager.GetMultiCrossReferenceItem(editableRoot.ProcessName, field.SystemName, c.Id)).ToList();
            var deletedItems = (from ICrossRefItemInfo item in currentMcrValue where !mcrContent.Select(x=>x.Id).Contains(item.Id) select item).ToList();

            currentMcrValue.RemoveRange(deletedItems);
            currentMcrValue.AddRange(newItemsList);           
        }
        /// <summary>
        /// Updates the specified source.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="destination">The destination.</param>
        public void Update(IDynamicObject source, IEditableRoot destination)
        {
            var filterList = new List<ColumnFilter>();

            foreach (var filterBuilder in _filterBuilders)
            {
                ColumnFilter filter;
                if (!filterBuilder.TryGetFilter(source, out filter))
                    return;
                filterList.Add(filter);
            }

            var itemIds = RuntimeDatabase.FindItems(_referencedProcess, filterList);
            if (itemIds.Count <= 0)
                return;

            if (_allowMultiple)
            {
                var crList = (ICrossRefItemList)destination.GetValueByPropertyName(_property.Name);

                if (crList == null)
                    return;

                foreach (var id in itemIds.Where(id => !crList.Contains(id)))
                {
                    crList.Assign(id);
                }
            }
            else
            {
                destination.SetValueByPropertyName(_property.Name, itemIds[0]);
            }
        }
示例#12
0
        /// <summary>
        /// Updates the field value.
        /// </summary>
        /// <param name="destination">
        /// The destination.
        /// </param>
        public void Update(IEditableRoot destination)
        {
            if (destination == null)
                throw new ArgumentNullException("destination");

            var sampleList = destination.GetValueByPropertyName(FieldName) as ISampleList;
            if (sampleList == null)
                return;

            sampleList.UpdateSampleList(destination);

            var sampleType = SampleUtils.GetSampleType(destination, FieldName);
            var sample = sampleList.OfType<ISampleEdit>().FirstOrDefault(s => IsEmpty(s, sampleType));
            if (sample == null)
            {
                if (SampleUtils.GetSampleSizeType(destination, FieldName) != SampleSizeTypes.Manual)
                    return;

                sample = sampleList.AddSample();
            }

            UpdateSample(sample, sampleType);
        }
        /// <summary>
        /// Updates the items in destination field.
        /// Items are updated for each data set in the source data collection, using key fields to determine which items to update.
        /// </summary>
        /// <param name="destination">The destination item.</param>
        /// <exception cref="System.InvalidOperationException">Destination field is null.</exception>
        private void ExecuteUpdate(IEditableRoot destination)
        {
            var crList = (ICrossRefItemList)destination.GetValueByPropertyName(Property.Name);
            if (crList == null)
                throw new InvalidOperationException("Destination field is null.");

            var destinationItems = GetItems(ReferencedProcessName, crList.OfType<IDynamicObject>().Select(x => x.Id));

            foreach (var sourceItem in SourceData)
            {
                for (var i = 0; i < destinationItems.Count; ++i)
                {
                    if (!AreEqual(sourceItem, destinationItems[i]))
                        continue;

                    UpdateFieldValues(sourceItem, destinationItems[i]);

                    destinationItems[i] = (IEditableRoot)((ISavable)destinationItems[i]).Save();
                }
            }
        }
示例#14
0
        private static void UpdateModelDefaultValues(IEditableRoot model)
        {
            using (new BypassPropertyCheckContext())
            {
                foreach (var prop in model.GetAllPropertiesByFieldType(ColumnTypes.SampleType))
                {
                    var value = model.GetValueByPropertyName(prop.Name);
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        model.SetValueByPropertyName(prop.Name, SampleTypes.Number.ToString());
                    }
                }

                //ELMTSUP 2512
                //foreach (var prop in model.GetAllPropertiesByFieldType(ColumnTypes.SamplingTechnique))
                //{
                //    var value = model.GetValueByPropertyName(prop.Name);
                    //if (string.IsNullOrWhiteSpace(value))
                    //{
                    //    model.SetValueByPropertyName(prop.Name, SampleSizeTypes.Fixed.ToString());
                    //}
                //}
            }
        }
示例#15
0
        /// <summary>
        /// Compares current field value with the value returned by the mapping.
        /// </summary>
        /// <param name="sourceData">The source data set.</param>
        /// <param name="destination">The destination item.</param>
        /// <returns>Returns true if field value is equal to the new value.</returns>
        public bool AreEqual(DataTriggerSourceData sourceData, IEditableRoot destination)
        {
            if (sourceData == null)
                throw new ArgumentNullException("sourceData");

            if (destination == null)
                throw new ArgumentNullException("destination");

            var oldValue = destination.GetValueByPropertyName(FieldName);
            var newValue = GetValue(sourceData, destination, DefaultCultureName);

            return oldValue != null ? oldValue.Equals(SafeTypeConverter.Convert(newValue, oldValue.GetType())) : newValue == null;
        }
        private void ExecuteUnlink(IEditableRoot source, IEditableRoot destination)
        {
            var currentId = destination.GetValueByPropertyName(Property.Name) as int?;
            if (currentId == null)
                return;

            var item = GetSourceItem(CreateLinkedItemFilter(currentId.Value), CreateSourceDataFilter(source));
            if (item == null)
                return;

            var ancestor = item.GetAncestorByProcessName(ReferencedProcessName);
            if (ancestor == null || ancestor.Id != currentId)
                return;

            destination.SetValueByPropertyName(Property.Name, null);
        }
        private void ExecuteLink(IEditableRoot source, IEditableRoot destination)
        {
            var infoItem = GetSourceItem(CreateSourceDataFilter(source));
            if (infoItem == null)
                return;

            var ancestor = infoItem.GetAncestorByProcessName(ReferencedProcessName);
            if (ancestor == null)
                return;

            if (destination.GetValueByPropertyName(Property.Name) == ancestor.Id)
                return;

            destination.SetValueByPropertyName(Property.Name, ancestor.Id);

            if (FieldUpdaters.Count == 0)
                return;

            var criteria = new DetailCriteria(infoItem.Id) { AllowLazyLoading = true };
            var editItem = DynamicTypeManager.GetEditableRoot<IEditableRoot>(SourceDataProcessName, criteria);
            if (editItem == null || editItem.Id <= 0)
                return;

            var sourceData = new DataTriggerSourceData();
            sourceData.SourceItems[DataTriggerFieldMappingExpressionNames.SourceDataProcess] = editItem;

            UpdateFieldValues(sourceData, editItem);
            ((ISavable)editItem).Save();
        }
        /// <summary>
        /// Gets all emails.
        /// </summary>
        /// <param name="sourceItem">
        /// The source item.
        /// </param>
        /// <returns>
        /// The collection of emails.
        /// </returns>
        public override IEnumerable<string> GetAllEmails(IEditableRoot sourceItem)
        {
            if (sourceItem == null)
                throw new ArgumentNullException("sourceItem");

            using (new BypassPropertyCheckContext())
            {
                var emailList = new List<string>();
                if (!string.IsNullOrEmpty(EmailFieldName))
                {
                    var email = sourceItem.GetValueByPropertyName(EmailFieldName);
                    if (!string.IsNullOrWhiteSpace(email))
                        emailList.Add(email);
                }

                if (!string.IsNullOrEmpty(ApprovalFieldName))
                {
                    var personIds = new List<int>();

                    // Add all approvers.
                    var approvalValue = (IApprovalEdit)sourceItem.GetValueByPropertyName(ApprovalFieldName);

                    foreach (var memberResult in approvalValue.MemberResults)
                    {
                        var personId = memberResult.Person;
                        if (personId.HasValue)
                            personIds.Add(personId.Value);
                    }

                    // Add override members.
                    personIds.AddRange(approvalValue.OverrideMembers.Select(overrideMember => overrideMember.Person.Id));

                    var resultColumns = new MobileList<string> { ReflectionHelper.GetPropertyName<IPersonInfo>(p => p.Email) };
                    var pagedCriteria = new PagedCriteria
                                            {
                                                ProcessName = Constants.BasePersonProcessName,
                                                PageNumber = 0,
                                                PageSize = int.MaxValue,
                                                LimitResultColumns = true,
                                                ResultColumns = resultColumns,
                                                ItemsToLoad = new MobileList<int>(personIds.Distinct())
                                            };

                    var personList = DynamicTypeManager.GetInfoList<IPersonInfo>(pagedCriteria);
                    emailList.AddRange(personList.Select(p => p.Email).Where(email => !string.IsNullOrWhiteSpace(email)));
                }

                return emailList.Where(email => !string.IsNullOrWhiteSpace(email)).Distinct();
            }
        }
示例#19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FieldReadModel"/> class.
        /// </summary>
        /// <param name="baseModel">
        ///     The base model.
        /// </param>
        /// <param name="property">
        ///     The property.
        /// </param>
        public FieldReadModel(IEditableRoot baseModel, PropertyInfo property)
        {
            if (baseModel == null)
            {
                throw new ArgumentNullException("baseModel");
            }

            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            Ioc.SatisfyImportsOnce(this);

            SystemName = property.Name;

            var commonSettingsAttr = property.GetCustomAttributes(typeof(CommonSettingsAttribute), false).Select(d => d).FirstOrDefault() as CommonSettingsAttribute;
            Name = commonSettingsAttr == null ? property.Name : commonSettingsAttr.Name;
            SectionName = commonSettingsAttr == null ? string.Empty : commonSettingsAttr.Section;

            var fieldTypeAttr = property.GetCustomAttributes(typeof(FieldTypeAttribute), false).Select(d => d).FirstOrDefault() as FieldTypeAttribute;
            FieldType = fieldTypeAttr == null ? ColumnTypes.String : fieldTypeAttr.ColumnType;

            var hasCalculatedAttr = property.GetCustomAttributes(typeof(CalculatedAttribute), false).Any();
            CanWrite = baseModel.CanWriteProperty(property.Name) && !hasCalculatedAttr;

            CanRead = baseModel.CanReadProperty(property.Name);
            BackColor = GetBackColor(baseModel, property);
            HideFromDetails = commonSettingsAttr != null && commonSettingsAttr.HideFromDetails;

            bool valueObtained = false;

            switch (this.FieldType)
            {
                case ColumnTypes.String:
                    var testFieldAttr = property.GetCustomAttributes(typeof(TextFieldAttribute), false).Select(d => d).FirstOrDefault() as TextFieldAttribute;
                    var stringLengthAttr = property.GetCustomAttributes(typeof(StringLengthAttribute), false).Select(d => d).FirstOrDefault() as StringLengthAttribute;
                    var richTextAttr = property.GetCustomAttributes(typeof(RichTextAttribute), false).Select(d => d).FirstOrDefault() as RichTextAttribute;
                    this.Options = StringFieldOptions.Create(testFieldAttr, stringLengthAttr, richTextAttr);
                    break;

                case ColumnTypes.Integer:
                case ColumnTypes.Numeric:
                case ColumnTypes.Double:
                    var numericOptionsAttr = property.GetCustomAttributes(typeof(NumericAttribute), false).Select(d => d).FirstOrDefault() as NumericAttribute;
                    var rangeAttr = property.GetCustomAttributes(typeof(RangeAttribute), false).Select(d => d).FirstOrDefault() as RangeAttribute;
                    this.Options = NumericFieldOptions.Create(numericOptionsAttr, rangeAttr);
                    break;

                case ColumnTypes.DateTime:
                    var dateTimeAttr = property.GetCustomAttributes(typeof(DateTimeFormatAttribute), false).Select(d => d).FirstOrDefault() as DateTimeFormatAttribute;
                    this.Options = DateTimeFieldOptions.Create(dateTimeAttr);
                    if (CanRead)
                    {
                        Value = string.Format(CultureInfo.InvariantCulture, "{0:yyyy-MM-ddTHH:mm:ss}", property.GetValue(baseModel));
                    }

                    valueObtained = true;
                    break;

                case ColumnTypes.Boolean:
                    this.Options = BooleanFieldOptions.Create(property);
                    break;

                case ColumnTypes.Reference:
                    this.Options = SingleCrossRefFieldOptions.Create(property, baseModel);
                    break;

                case ColumnTypes.File:break;
                case ColumnTypes.DisplayList:
                    if (CanRead)
                    {
                        var displayItemList = (IDisplayListItemList) baseModel.GetValueByPropertyName(property.Name); 
                        Options = DisplayListFieldOptions.Create(property, displayItemList);

                        var displayListFieldOptions = (DisplayListFieldOptions) Options;                       
                        if (displayListFieldOptions != null)
                        {
                            var baseType = displayItemList.GetType().BaseType;
                            if (baseType != null)
                            {
                                var itemType = baseType.GetGenericArguments()[1];

                                var columns = displayListFieldOptions.Columns;
                                var displayListModels = new List<DisplayListItemModel>();

                                foreach (var displayItem in displayItemList)
                                {
                                    var item = new DisplayListItemModel
                                    {
                                        Id = (int) displayItem.GetType().GetProperty(Constants.IdColumnName).GetValue(displayItem)
                                    };

                                    foreach (var column in columns)
                                    {
                                        var propertyInfo = itemType.GetPropertyByFullName(column.SystemName);
                                        if (propertyInfo == null) continue;

                                        var columnValue = FieldValueExtractor.GetPropertyStringValue(propertyInfo, propertyInfo.GetValue(displayItem), column.ColumnType);

                                        item.Values[column.ColumnName] = columnValue;
                                    }

                                    displayListModels.Add(item);
                                }

                                Value = displayListModels;
                            }
                        }
                    }

                    valueObtained = true;
                    break;
                case ColumnTypes.MultiReference:
                    this.Options = MultiCrossRefFieldOptions.Create(property, baseModel);
                    if (CanRead)
                    {
                        if (baseModel.GetValueByPropertyName(property.Name) is ICrossRefItemList)
                        {
                        var list = (ICrossRefItemList)baseModel.GetValueByPropertyName(property.Name);

                        var values = new List<MultiCrossRefItemModel>();
                        foreach (var l in list)
                        {
                            var id = (int)l.GetType().GetProperty(Constants.IdColumnName).GetValue(l);
                            var value = SafeTypeConverter.Convert<string>(l.GetType().GetProperty(((MultiCrossRefFieldOptions)Options).FieldName).GetValue(l));
                            values.Add(new MultiCrossRefItemModel { Id = id, DisplayText = value, ProcessName = ((MultiCrossRefFieldOptions)Options).ProcessSystemName, FieldName = property.Name });
                        }
                        Value = values;  // JsonConvert.SerializeObject(values);
                    }
                    }

                    valueObtained = true;
                    break;

                case ColumnTypes.Image:
                    this.Options = ImageFieldOptions.Create(property);
                    if (CanRead)
                    {
                        var imageBytes = property.GetValue(baseModel) as byte[];
                        if (imageBytes == null || imageBytes.Length == 0)
                        {
                            return;
                        }

                        using (var sourceStream = new MemoryStream(imageBytes))
                        {
                            using (var image = Image.FromStream(sourceStream))
                            {
                                var size = CommonHelper.GetThumbnailSize(image);
                                using (var thumb = image.GetThumbnailImage(size.Width, size.Height, () => false, IntPtr.Zero))
                                {
                                    using (var thumbStream = new MemoryStream())
                                    {
                                        thumb.Save(thumbStream, ImageFormat.Png);

                                        Value = Convert.ToBase64String(thumbStream.GetBuffer());
                                    }
                                }
                            }
                        }
                    }

                    valueObtained = true;
                    break;

                case ColumnTypes.Result:
                    this.Options = ResultFieldOptions.Create(property, baseModel);
                    break;

                case ColumnTypes.Checklist:
                    this.Options = ChecklistFieldOptions.Create(property, baseModel);
                    if (CanRead)
                    {
                        var checklist = property.GetValue(baseModel) as ChecklistEdit;
                        if (checklist == null || string.IsNullOrEmpty(checklist.AnswerProcessSystemName))
                        {
                            return;
                        }

                        var answerDetails = new List<DetailsReadModel>();
                        for (int index = 0; index < checklist.AnswerProcessList.Count; index++)
                        {
                            var answer = (IEditableRoot)checklist.AnswerProcessList[index];
                            answerDetails.Add(ProcessController.CreateDetailsReadModel(answer, index));
                        }

                        Value = answerDetails;
                    }

                    valueObtained = true;
                    break;

                case ColumnTypes.Sample:
                    SampleFieldOptions sampleOptions = SampleFieldOptions.Create(property, baseModel);
                    this.Options = sampleOptions;
                    if (CanRead)
                    {
                        var value = property.GetValue(baseModel);
                        if (value != null)
                        {
                            var val = (ISampleList)value;

                            if (string.IsNullOrEmpty(val.SampleType))
                            {
                                val.SampleType = SampleTypes.Number.ToString();
                            }

                            foreach (ISampleEdit sample in val)
                            {
                                sample.LowerSpecLimit = sampleOptions.LowerSpecLimit;
                                sample.UpperSpecLimit = sampleOptions.UpperSpecLimit;
                            }

                            sampleOptions.SamplesAreGenerated = val.Count > 0 || sampleOptions.SampleSizeType == SampleSizeTypes.Manual;

                            var index = 0;
                            Value = val.Cast<ISampleEdit>().Select(v => new SampleModel
                            {
                                Id = v.Id,
                                ItemId = v.ItemId,
                                Label = v.Label,
                                SampleNumeric = v.SampleNumeric,
                                SampleBoolean = v.SampleBoolean,
                                SampleAlphanumeric = v.SampleAlphanumeric,
                                SampleType = v.SampleType,
                                LowerSpecLimit = v.LowerSpecLimit,
                                UpperSpecLimit = v.UpperSpecLimit,
                                ChildIndex = index++
                            });
                        }

                        valueObtained = true;
                    }

                    break;

                case ColumnTypes.SampleType:
                    this.Options = SampleTypeFieldOptions.Create(property, baseModel);

                    if (CanRead)
                    {
                        var value = property.GetValue(baseModel);
                        Value = SafeTypeConverter.Convert<string>(value);

                        if (string.IsNullOrEmpty((string)Value))
                        {
                            Value = SampleTypes.Number.ToString();
                        }
                    }

                    break;

                case ColumnTypes.SamplingTechnique:
                    this.Options = SamplingTechniqueFieldOptions.Create(property, baseModel);

                    if (CanRead)
                    {
                        var value = property.GetValue(baseModel);
                        Value = SafeTypeConverter.Convert<string>(value);
                        //ELMTSUP 2512
                        //if (string.IsNullOrEmpty((string)Value))
                        //{
                        //   Value = SampleSizeTypes.Fixed.ToString();
                        //}
                    }

                    break;
            }

            if (!valueObtained)
            {
                if (CanRead)
                {
                    var value = property.GetValue(baseModel);
                    Value = SafeTypeConverter.Convert<string>(value);
                }
            }
        }
        /// <summary>
        /// Links items to destination field.
        /// </summary>
        /// <param name="source">
        /// The source item.
        /// </param>
        /// <param name="destination">
        /// The destination item.
        /// </param>
        private void ExecuteLink(IEditableRoot source, IEditableRoot destination)
        {
            var crList = (ICrossRefItemList)destination.GetValueByPropertyName(Property.Name);
            if (crList == null)
            {
                throw new InvalidOperationException("Destination field is null.");
            }

            var filterList = new FilterList();
            if (crList.Count > 0)
            {
                // Exclude items that are already linked.
                filterList.Add(CreateLinkedItemsFilter(FilterOperator.NotIn, crList.Cast<ICrossRefItemInfo>().Select(x => x.Id)));
            }

            if (!string.IsNullOrEmpty(SourceDataFilterDefinition))
            {
                filterList.Add(CreateSourceDataFilter(source));
            }

            foreach (var infoItem in GetSourceItems(filterList))
            {
                var ancestor = infoItem.GetAncestorByProcessName(ReferencedProcessName);
                if (ancestor == null || crList.Contains(ancestor.Id))
                    continue;

                crList.Assign(ancestor.Id);

                if (FieldUpdaters.Count == 0)
                    continue;

                var criteria = new DetailCriteria(infoItem.Id) { AllowLazyLoading = true };
                var editItem = DynamicTypeManager.GetEditableRoot<IEditableRoot>(SourceDataProcessName, criteria);
                if (editItem == null || editItem.Id <= 0)
                    continue;

                var sourceData = new DataTriggerSourceData();
                sourceData.SourceItems[DataTriggerFieldMappingExpressionNames.SourceDataProcess] = editItem;

                UpdateFieldValues(sourceData, editItem);

                ((ISavable)editItem).Save();
            }
        }
        /// <summary>
        /// Compares current field value with the value returned by the mapping.
        /// </summary>
        /// <param name="sourceData">The source data set.</param>
        /// <param name="destination">The destination item.</param>
        /// <returns>Returns true if field value is equal to the new value.</returns>
        public bool AreEqual(DataTriggerSourceData sourceData, IEditableRoot destination)
        {
            if (sourceData == null)
                throw new ArgumentNullException("sourceData");

            if (destination == null)
                throw new ArgumentNullException("destination");

            var oldValue = SafeTypeConverter.Convert<int?>(destination.GetValueByPropertyName(FieldName));
            var newValue = GetValue(sourceData, destination);

            return oldValue == newValue;
        }
        /// <summary>
        /// Updates the specified item.
        /// </summary>
        /// <param name="dataContext">
        /// The data context.
        /// </param>
        /// <param name="item">
        /// The destination item.
        /// </param>
        public void Update(IDataContext dataContext, IEditableRoot item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            UpdateInternal(dataContext, item);

            if (IsKey)
            {
                var itemId = item.GetValueByPropertyName(Property.Name) as int?;
                if (itemId == null)
                {
                    throw new InvalidOperationException(
                        string.Format(CultureInfo.InvariantCulture, "The key field \"{0}\" in process \"{1}\" is null.", DisplayName, item.ProcessDisplayName));
                }
            }
        }
        /// <summary>
        /// Creates a new item for each data set in the source data collection and links it to the destination field .
        /// If destination field contains an item with the same key values as the new item, the new item is ignored.
        /// </summary>
        /// <param name="destination">The destination item.</param>
        /// <exception cref="System.InvalidOperationException">Destination field is null.</exception>
        private void ExecuteInsert(IEditableRoot destination)
        {
            var crList = (ICrossRefItemList)destination.GetValueByPropertyName(Property.Name);
            if (crList == null)
                throw new InvalidOperationException("Destination field is null.");

            var tempSourceDataList = new List<DataTriggerSourceData>(SourceData);
            var processIds = crList.OfType<IDynamicObject>().Select(x => x.Id).ToList();

            foreach (var destItem in IterateItems(ReferencedProcessName, processIds))
            {
                var matchList = tempSourceDataList.Where(x => AreEqual(x, destItem)).ToList();
                foreach (var match in matchList)
                    tempSourceDataList.Remove(match);

                if (tempSourceDataList.Count == 0) break;
            }

            foreach (var sourceData in tempSourceDataList)
            {
                var newItem = DynamicTypeManager.NewEditableRoot<IEditableRoot>(ReferencedProcessName);
                newItem.AllowLazyLoading = true;

                UpdateFieldValues(sourceData, newItem);

                if (!string.IsNullOrEmpty(LinkFieldSystemName) && destination.Id > 0)
                    newItem.SetValueByPropertyName(LinkFieldSystemName, destination.Id);

                newItem = (IEditableRoot)((ISavable)newItem).Save();
                crList.Assign(newItem.Id);
            }
        }
示例#24
0
        /// <summary>
        /// Updates destination field.
        /// </summary>
        /// <param name="destination">The destination item.</param>
        /// <exception cref="System.InvalidOperationException">
        /// Could not load system options.
        /// or
        /// Temp document UNC is not set.
        /// or
        /// File processor URI is not set.
        /// or
        /// Destination field is null.
        /// </exception>
        /// <exception cref="Cebos.Veyron.SharedTypes.VeyronException">Could not get response stream.</exception>
        public void Update(IEditableRoot destination)
        {
            if (NewValue == null || string.IsNullOrEmpty(NewValue.FileName))
                return;

            var systemOptions = SystemOptionsRetriever.GetSystemOptions();
            if (systemOptions == null)
                throw new InvalidOperationException("Could not load system options.");

            var tempPath = systemOptions.TempDocumentUNC;
            if (string.IsNullOrEmpty(tempPath))
                throw new InvalidOperationException("Temp document UNC is not set.");

            var fileProcessorUri = systemOptions.FileProcessorURI;
            if (string.IsNullOrEmpty(fileProcessorUri))
                throw new InvalidOperationException("File processor URI is not set.");

            var destinationField = (IFileProcess)destination.GetValueByPropertyName(FieldName);
            if (destinationField == null)
                throw new InvalidOperationException("Destination field is null.");

            if (ReferenceEquals(NewValue, destinationField))
            {
                // Destination field is mapped to itself. Don't copy.
                return;
            }

            // Copy source file to temp folder.
            var fileName = Guid.NewGuid() + Path.GetExtension(NewValue.FileName);
            var filePath = Path.Combine(tempPath, fileName);
            var url = string.Format(CultureInfo.InvariantCulture, "{0}?fileName={1}&isOfficial=True", fileProcessorUri, NewValue.FileName);
            var request = (HttpWebRequest)WebRequest.Create(new Uri(url));

            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (stream == null)
                        throw new VeyronException("Could not get response stream.");

                    using (var outputStream = File.OpenWrite(filePath))
                        stream.CopyTo(outputStream, 1024 * 10);

                    destinationField.OriginalFileName = NewValue.OriginalFileName;
                    destinationField.FileName = fileName;

                    destinationField.UploadFile();
                }
            }
        }
        /// <summary>
        /// Removes items from destination field.
        /// Items are removed for each data set in the source data collection, using key fields to determine which items to remove.
        /// </summary>
        /// <param name="destination">The destination item.</param>
        /// <exception cref="System.InvalidOperationException">Destination field is null.</exception>
        private void ExecuteRemove(IEditableRoot destination)
        {
            var crList = (ICrossRefItemList)destination.GetValueByPropertyName(Property.Name);
            if (crList == null)
                throw new InvalidOperationException("Destination field is null.");

            var destinationItems = GetItems(ReferencedProcessName, crList.OfType<IDynamicObject>().Select(x => x.Id));

            foreach (var sourceData in SourceData)
            {
                for (var i = destinationItems.Count - 1; i >= 0; --i)
                {
                    if (!AreEqual(sourceData, destinationItems[i]))
                        continue;

                    crList.Remove(destinationItems[i].Id);
                    destinationItems.RemoveAt(i);
                }
            }
        }
        /// <summary>
        /// Gets the cross reference list.
        /// </summary>
        /// <param name="item">The source item.</param>
        /// <returns>Returns the cross reference list.</returns>
        /// <exception cref="System.InvalidOperationException">Source field is null.</exception>
        private ICrossRefItemList GetCrossRefList(IEditableRoot item)
        {
            var crList = (ICrossRefItemList)item.GetValueByPropertyName(FieldName);

            if (crList == null)
                throw new InvalidOperationException("Source field is null.");

            return crList;
        }
        private void ExecuteUnlink(IEditableRoot source, IEditableRoot destination)
        {
            var crList = (ICrossRefItemList)destination.GetValueByPropertyName(Property.Name);
            if (crList == null)
            {
                throw new InvalidOperationException("Destination field is null.");
            }

            var filterList = new FilterList();
            if (crList.Count > 0)
            {
                // Include only items that are linked to MCR.
                filterList.Add(CreateLinkedItemsFilter(FilterOperator.In, crList.Cast<ICrossRefItemInfo>().Select(x => x.Id)));
            }

            if (!string.IsNullOrEmpty(SourceDataFilterDefinition))
            {
                filterList.Add(CreateSourceDataFilter(source));
            }

            foreach (var infoItem in GetSourceItems(filterList))
            {
                var ancestor = infoItem.GetAncestorByProcessName(ReferencedProcessName);
                if (ancestor == null)
                    continue;

                crList.Remove(ancestor.Id);
            }
        }
示例#28
0
        /// <summary>
        /// Copies a checklist field.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="destination">
        /// The destination.
        /// </param>
        /// <param name="fieldName">
        /// The field name.
        /// </param>
        public void CopyChecklistField(IEditableRoot source, IEditableRoot destination, string fieldName)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            if (destination == null)
                throw new ArgumentNullException("destination");

            var destinationChecklist = destination.GetValueByPropertyName(fieldName) as ChecklistEdit;
            if (destinationChecklist == null || destinationChecklist.AnswerProcessList == null)
                return;

            destinationChecklist.AnswerProcessList.Clear();

            var sourceChecklist = source.GetValueByPropertyName(fieldName) as ChecklistEdit;
            if (sourceChecklist == null || sourceChecklist.AnswerProcessList == null)
                return;

            // Modify the QA map to copy from one answer to another.
            var qaMap = ChecklistQAMap.Parse(destinationChecklist.QuestionAnswerMap);
            foreach (var qaMapElement in qaMap.Elements)
            {
                qaMapElement.QuestionFieldSystemName = qaMapElement.AnswerFieldSystemName;
                qaMapElement.QuestionFieldSource = ChecklistQuestionFieldSource.QuestionProcess;
            }

            var answerToAnswerMap = qaMap.ToXml();

            foreach (var sourceAnswer in sourceChecklist.AnswerProcessList.OfType<IEditableRoot>())
            {
                var destinationAnswer = TheDynamicTypeManager.NewEditableChild<IEditableRoot>(destinationChecklist.AnswerProcessSystemName);
                var questionData = new ChecklistQuestionData { QuestionItem = sourceAnswer };

                ChecklistHelper.CopyQuestionData(questionData, destinationAnswer, answerToAnswerMap);

                destinationChecklist.AnswerProcessList.Add(destinationAnswer);
            }
        }
        /// <summary>
        /// Updates the specified item.
        /// </summary>
        /// <param name="dataContext">
        /// The data context.
        /// </param>
        /// <param name="item">
        /// The destination item.
        /// </param>
        public void Update(IDataContext dataContext, IEditableRoot item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            var crList = (ICrossRefItemList)item.GetValueByPropertyName(Property.Name);
            if (crList == null)
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Cross reference field \"{0}\" is null.", Property.Name), "item");

            try
            {
            if (ValueExpression != null)
            {
                var items = ValueExpression(dataContext) as IEnumerable;

                if (items != null)
                {
                    var enumerator = items.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        InsertOrUpdateChildren(dataContext, crList);
                    }
                }
            }
            else
            {
                InsertOrUpdateChildren(dataContext, crList);
            }
        }
            catch (Exception ex)
            {
                var message = new StringBuilder();
                message.AppendFormat(CultureInfo.InvariantCulture, "Could not update the field \"{0}\" in process \"{1}\".", DisplayName, item.ProcessDisplayName);

                throw new InvalidOperationException(message.ToString(), ex);
            }
        }
示例#30
0
        /// <summary>
        /// Updates the specified item.
        /// </summary>
        /// <param name="dataContext">
        /// The data context.
        /// </param>
        /// <param name="item">
        /// The destination item.
        /// </param>
        public void Update(IDataContext dataContext, IEditableRoot item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            try
            {
                var checklist = (ChecklistEdit)item.GetValueByPropertyName(FieldName);
                if (checklist == null || checklist.AnswerProcessList == null)
                {
                    checklist = CreateNewChecklist();
                    item.SetValueByPropertyName(FieldName, checklist);
                }

                if (ValueExpression != null)
                {
                    var items = ValueExpression(dataContext) as IEnumerable;

                    if (items != null)
                    {
                        var enumerator = items.GetEnumerator();

                        while (enumerator.MoveNext())
                        {
                            InsertOrUpdateChildren(dataContext, checklist);
                        }
                    }
                }
                else
                {
                    InsertOrUpdateChildren(dataContext, checklist);
                }
            }
            catch (Exception ex)
            {
                var message = new StringBuilder();
                message.AppendFormat(CultureInfo.InvariantCulture, "Could not update the field \"{0}\" in process \"{1}\".", DisplayName, item.ProcessDisplayName);

                throw new InvalidOperationException(message.ToString(), ex);
            }
        }