Esempio n. 1
0
 public Criterion(string fieldName, string parameterName, object parameterValue, CriteriaOperator criterriaOperator)
 {
     _fieldName = fieldName;
     _parameterName = parameterName;
     _parameterValue = parameterValue;
     _criteriaOperator = criterriaOperator;
 }
 public CriteriaOperator PrepareCriteria(CriteriaOperator op)
 {
     if (op is FunctionOperator)
     {
         var funcOp = new FunctionOperator();
         for (int i = 0; i < (op as FunctionOperator).Operands.Count; i++)
             funcOp.Operands.Add(PrepareCriteria((op as FunctionOperator).Operands[i]));
         return funcOp;
     }
     else if (op is ConstantValue)
     {
         var cnst = new ConstantValue((op as ConstantValue).Value);
         if (String.Concat((op as ConstantValue).Value).ToLower().IndexOf("@this") > -1)
         {
             IMemberInfo info;
             cnst.Value = ObjectFormatValues.GetValueRecursive((op as ConstantValue).Value.ToString().Replace("@This.", "").Replace("@This", "").Replace("@this.", "").Replace("@this", ""), CurrentObject, out info);
         }
         return cnst;
     }
     else if (op is BinaryOperator)
     {
         var binary = new BinaryOperator();
         binary.LeftOperand = PrepareCriteria((op as BinaryOperator).LeftOperand);
         binary.RightOperand = PrepareCriteria((op as BinaryOperator).RightOperand);
         return binary;
     }
     else
     {
         return op;
     }
 }
Esempio n. 3
0
 public Criteria(String propertyName, String value, CriteriaOperator criteriaOperator, LogicalOperation logicalOperation = Core.Query.LogicalOperation.And)
 {
     this.PropertyName = propertyName;
     this.Value = value;
     this.Operator = criteriaOperator;
     this.LogicalOperation = logicalOperation;
 }
Esempio n. 4
0
        private void ApplyCustomFilter()
        {
            if (Frame.View == null)
                return;

            switch (Frame.View.Id)
            {
                case "WHHistory_ListView_ThisMonth":
                    DateTime thisMonth;
                    thisMonth = DateTime.Today;
                    thisMonth = thisMonth.AddDays((thisMonth.Day -1) * -1);

                    criteria = CriteriaOperator.Parse(string.Format("Date >= '{0}'", thisMonth));
                    break;
                case "WHHistory_ListView_ThisWeek":
                    criteria = CriteriaOperator.Parse(string.Format("Date >= '{0}'", DateTime.Today.AddDays(-7)));
                    break;
                case "WHHistory_ListView_ThisYear":
                    DateTime thisYear;
                    thisYear = DateTime.Today;
                    thisYear = thisYear.AddMonths((thisYear.Month - 1) * -1);
                    thisYear = thisYear.AddDays((thisYear.Day -1 )* -1);
                    criteria = CriteriaOperator.Parse(string.Format("Date >= '{0}'", thisYear));
                    break;
                case "WHHistory_ListView":
                    criteria = null;
                    break;
            }

            ((ListView)Frame.View).CollectionSource.Criteria["MyFilter"] = criteria;
        }
Esempio n. 5
0
 public MasterDetailRuleInfo(IModelListView childListView, IModelMember collectionMember, ITypeInfo typeInfo, CriteriaOperator criteria, bool synchronizeActions) {
     ChildListView = childListView;
     CollectionMember = collectionMember;
     TypeInfo = typeInfo;
     _criteria = criteria;
     _synchronizeActions = synchronizeActions;
 }
Esempio n. 6
0
 /// <summary>
 /// Initializes a new instance of the Idiorm.Criterion class that uses the property name, the value and the operator of the new Idiorm.Criterion.
 /// </summary>
 /// <param name="propertyName">The name of the property to map.</param>
 /// <param name="operator">The operator of the new Idiorm.Criterion object.</param>
 /// <param name="value">The value of the new Idiorm.Criterion object.</param>
 public Criterion(string propertyName, CriteriaOperator @operator, object value)
     : this()
 {
     this.propertyName = propertyName;
     this.value = value;
     this.@operator = @operator;
 }
        public static string TranslateCriteriaOperator(CriteriaOperator criteriaOperator)
        {
            if (criteriaOperator == CriteriaOperator.Equal)
                return "=";
            if (criteriaOperator == CriteriaOperator.NotEqual)
                return "<>";
            if (criteriaOperator == CriteriaOperator.GreaterThan)
                return ">";
            if (criteriaOperator == CriteriaOperator.GreaterThanOrEqual)
                return ">=";
            if (criteriaOperator == CriteriaOperator.LesserThan)
                return "<";
            if (criteriaOperator == CriteriaOperator.LesserThanOrEqual)
                return "<=";
            if (criteriaOperator == CriteriaOperator.Like)
                return " LIKE ";
            if (criteriaOperator == CriteriaOperator.NotLike)
                return " NOT LIKE ";
            if (criteriaOperator == CriteriaOperator.IsNull)
                return " IS NULL ";
            if (criteriaOperator == CriteriaOperator.IsNotNull)
                return " IS NOT NULL ";

            throw new ArgumentException("CriteriaOperator not supported", "criteriaOperator");
        }
Esempio n. 8
0
        CriteriaOperator CreateFilterCriteria()
        {
            if (!Filter_words)
            { // точное совпадение
                CriteriaOperator[] operators = new CriteriaOperator[_View.VisibleColumns.Count];
                for (int i = 0; i < _View.VisibleColumns.Count; i++)
                {
                    if (Filter_Plus)
                        operators[i] = new BinaryOperator(_View.VisibleColumns[i].FieldName, String.Format("%{0}%", _ActiveFilter), BinaryOperatorType.Like);
                    else
                        operators[i] = new BinaryOperator(_View.VisibleColumns[i].FieldName, String.Format("{0}%", _ActiveFilter), BinaryOperatorType.Like);
                }
                return new GroupOperator(GroupOperatorType.Or, operators);
            }
            else
            { // любое слово
                CriteriaOperator[] levels = new CriteriaOperator[FilterText.Length];

                for (int i = 0; i < FilterText.Length; i++)
                {
                    CriteriaOperator[] operators = new CriteriaOperator[_View.VisibleColumns.Count + 1]; // Тэги + 1
                    for (int j = 0; j < _View.VisibleColumns.Count; j++)
                    {
                        operators[j] = new BinaryOperator(_View.VisibleColumns[j].FieldName, String.Format("%{0}%", FilterText[i]), BinaryOperatorType.Like);
                    }
                    // Тэги
                    operators[_View.VisibleColumns.Count] = new BinaryOperator("TagComments", String.Format("%{0}%", FilterText[i]), BinaryOperatorType.Like);

                    levels[i] = new GroupOperator(GroupOperatorType.Or, operators);
                }
                return new GroupOperator(GroupOperatorType.And, levels);
            }
        }
 private static BinaryOperator getGroupOperator(out BinaryOperator binaryOperator2,
                                                out CriteriaOperator groupOperator)
 {
     var binaryOperator = new BinaryOperator("dfs", 324);
     binaryOperator2 = new BinaryOperator("sdfs", 3455);
     groupOperator = new GroupOperator(binaryOperator, binaryOperator2);
     return binaryOperator;
 }
 private bool IsFullIndexed(CriteriaOperator theOperator){
     var queryOperand = theOperator as QueryOperand;
     if (!ReferenceEquals(queryOperand, null)){
         return IsFullIndexedCore(queryOperand.ColumnName);
     }
     var operandProperty = theOperator as OperandProperty;
     return !ReferenceEquals(operandProperty, null) && IsFullIndexedCore(operandProperty.PropertyName);
 }
Esempio n. 11
0
 public void Remove(ref CriteriaOperator criteriaOperator, string removeString)
 {
     if (criteriaOperator.ToString() == removeString)
     {
         criteriaOperator = null;
         return;
     }
     Extract(criteriaOperator, removeString);
 }
Esempio n. 12
0
 public void Replace(ref CriteriaOperator criteriaOperator, string matchString, CriteriaOperator replaceOperator)
 {
     if (criteriaOperator.ToString() == matchString)
     {
         criteriaOperator = replaceOperator;
         return;
     }
     Extract(criteriaOperator, matchString, replaceOperator);
 }
Esempio n. 13
0
        private CriteriaOperator Extract(CriteriaOperator criteriaOperator, string matchString,
                                         CriteriaOperator replaceOperator)
        {
            if (criteriaOperator is BinaryOperator)
            {
                var binaryOperator = (BinaryOperator) criteriaOperator;
                binaryOperators.Add(binaryOperator);

                return binaryOperator;
            }
            if (criteriaOperator is NullOperator)
            {
                nullOperators.Add((NullOperator) criteriaOperator);
                return criteriaOperator;
            }
            if (criteriaOperator is NotOperator)
            {
                var notOperator = (NotOperator) criteriaOperator;
                notOperators.Add(notOperator);
                Extract(notOperator.Operand);
            }
            else if (criteriaOperator is UnaryOperator)
            {
                unaryOperators.Add((UnaryOperator) criteriaOperator);
                return criteriaOperator;
            }

            else if (criteriaOperator is GroupOperator)
            {
                var groupOperator = (GroupOperator) criteriaOperator;
                CriteriaOperatorCollection operands = groupOperator.Operands;
                var indexesToremove = new List<int>();
                for (int i = 0; i < operands.Count; i++){
                    CriteriaOperator operand = operands[i];
                    if (operand.ToString() == matchString){
                        if (ReferenceEquals(replaceOperator,null))
                            indexesToremove.Add(i);
                        else
                            operands[i] = replaceOperator;
                    }
                    else{
                        CriteriaOperator extract = Extract(operand);
                        operands.RemoveAt(i);
                        operands.Insert(i, extract);
                    }
                }
                foreach (int i in indexesToremove)
                    operands.RemoveAt(i);
            }
            else if (criteriaOperator is ContainsOperator)
            {
                var containsOperator = (ContainsOperator) criteriaOperator;
                CriteriaOperator condition = containsOperator.Condition;
                Extract(condition);
            }
            return criteriaOperator;
        }
Esempio n. 14
0
 XPBaseObject CreateObject(XElement element, UnitOfWork nestedUnitOfWork, ITypeInfo typeInfo, CriteriaOperator objectKeyCriteria){
     XPBaseObject xpBaseObject = GetObject(nestedUnitOfWork, typeInfo,objectKeyCriteria) ;
     var keyValuePair = new KeyValuePair<ITypeInfo, CriteriaOperator>(typeInfo, objectKeyCriteria);
     if (!importedObjecs.ContainsKey(keyValuePair)) {
         importedObjecs.Add(keyValuePair, null);
         ImportProperties(nestedUnitOfWork, xpBaseObject, element);
     }
     return xpBaseObject;
 }
Esempio n. 15
0
 public Criterion(string propertyName, CriteriaOperator @operator, object value,
     StringMatchMode matchMode, bool caseInsensitive)
     : this(propertyName, @operator, value)
 {
     if (@operator != CriteriaOperator.Like && @operator != CriteriaOperator.NotLike)
         throw new ArgumentException();
     this.matchMode = matchMode;
     this.caseInsensitive = caseInsensitive;
 }
 private ExpressionEvaluator GetExpressionEvaluator(CriteriaOperator criteria)
 {
     if (criteria.ToString() == lastCriteria)
         return lastEvaluator;
     lastCriteria = criteria.ToString();
     PropertyDescriptorCollection pdc = ((ITypedList)_View.DataSource).GetItemProperties(null);
     lastEvaluator = new ExpressionEvaluator(pdc, criteria, false);
     return lastEvaluator;
 }
Esempio n. 17
0
 public void Process(CriteriaOperator operand, bool mustBeLogical)
 {
     if (ReferenceEquals(operand, null)) return;
     if (mustBeLogical) {
         if ((BooleanCriteriaState)operand.Accept(this) == BooleanCriteriaState.Value) throw new ArgumentException(MustBeLogical);
     } else {
         if ((BooleanCriteriaState)operand.Accept(this) == BooleanCriteriaState.Logical) throw new ArgumentException(MustBeArithmetical);
     }
 }
        private static string CalculateKeyPart(CriteriaOperator source)
        {
            var operandProperty = source as OperandProperty;

            if (operandProperty != null)
            {
                return operandProperty.PropertyName;
            }

            throw new NotSupportedException("Не поддерживаем CriteriaOperator отличный от 'OperandProperty'. Переданное значение CriteriaOperator: '{0}'".FillWith(source.TypeName()));
        }
Esempio n. 19
0
        public FilterEvaluator(EvaluatorContextDescriptor descriptor, CriteriaOperator filterCriteria)
        {
            this.evaluatorCore = new ExpressionEvaluatorCore(true);
            this.descriptor = descriptor;
            this.filterCriteria = filterCriteria;

            this.contexts = typeof (ExpressionEvaluatorCore).GetField("contexts", BindingFlags.Instance | BindingFlags.NonPublic);

            FieldInfo fieldInfo = typeof(ExpressionEvaluatorCore).GetField("LikeDataCache", BindingFlags.Instance | BindingFlags.NonPublic);
            likeDataCache = (LikeDataCache) fieldInfo.GetValue(this.evaluatorCore);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="objectSpace"></param>
 /// <param name="type">数据源的数据类型</param>
 /// <param name="mode"></param>
 /// <param name="source">数据源</param>
 public NonPersistentCollectionSource(IObjectSpace objectSpace, Type type, CollectionSourceMode mode, object source)
     : base(objectSpace, mode)
 {
     typeInfo = XafTypesInfo.Instance.FindTypeInfo(type);
     var s = source as XPBaseCollection;
     if (s != null)
     {
         SourceCriteria = s.Filter;
     }
     this.source = source;
 }
Esempio n. 21
0
 XPBaseObject createObject(XElement element, UnitOfWork nestedUnitOfWork, ITypeInfo typeInfo, CriteriaOperator objectKeyCriteria)
 {
     XPBaseObject xpBaseObject = findObject(nestedUnitOfWork, typeInfo,objectKeyCriteria) ??
                                 (XPBaseObject) Activator.CreateInstance(typeInfo.Type, nestedUnitOfWork);
     if (!importingObjecs.Contains(xpBaseObject)) {
         importingObjecs.Add(xpBaseObject);
         importProperties(nestedUnitOfWork, xpBaseObject, element);
         importingObjecs.Remove(xpBaseObject);
     }
     return xpBaseObject;
 }
Esempio n. 22
0
        public UnaryCriteria(CriteriaOperator op, BaseCriteria operand)
        {
            if (Object.ReferenceEquals(operand, null))
                throw new ArgumentNullException("operand");

            if (op < CriteriaOperator.Paren || op > CriteriaOperator.Exists)
                throw new ArgumentOutOfRangeException("op");

            this.op = op;
            this.operand = operand;
        }
 private static string FindSQLOperatorFor(CriteriaOperator criteriaOperator)
 {
     switch (criteriaOperator)
     {
         case CriteriaOperator.Equal:
             return "=";
         case CriteriaOperator.LessThanOrEqual:
             return "<=";
         default:
             throw new ApplicationException("No operator defined.");
     }
 }
 public static CriteriaOperator ReplaceFilterCriteria(CriteriaOperator source, CriteriaOperator prevOperand, CriteriaOperator newOperand)
 {
     GroupOperator groupOperand = source as GroupOperator;
     if (ReferenceEquals(groupOperand, null))
         return newOperand;
     GroupOperator clone = groupOperand.Clone();
     clone.Operands.Remove(prevOperand);
     if (clone.Equals(source))
         return newOperand;
     clone.Operands.Add(newOperand);
     return clone;
 }
Esempio n. 25
0
        private ITypeInfo GetPersistentTypeInfo(CriteriaOperator op)
        {
            OperandValue theOperand = op as OperandValue;
            if (!ReferenceEquals(null, theOperand) && !ReferenceEquals(null, theOperand.Value))
            {
                var ti = typesInfo.FindTypeInfo(theOperand.Value.GetType());
                if (ti != null && ti.IsPersistent && ti.KeyMember != null)
                    return ti;
            }

            return null;
        }
 public void JsonCriteriaConverter_DeserializesComparisonCriteriasProperly(string opStr,
     CriteriaOperator op)
 {
     var actual = JSON.Parse<BaseCriteria>("[[\"a\"],\"" + opStr + "\",[\"b\"]]");
     Assert.NotNull(actual);
     var criteria = Assert.IsType<BinaryCriteria>(actual);
     Assert.Equal(op, criteria.Operator);
     var left = Assert.IsType<Criteria>(criteria.LeftOperand);
     var right = Assert.IsType<Criteria>(criteria.RightOperand);
     Assert.Equal("a", left.Expression);
     Assert.Equal("b", right.Expression);
 }
Esempio n. 27
0
 public NHServerCollection(NHObjectSpace objectSpace, Type objectType, CriteriaOperator criteria, IList<SortProperty> sorting)
 {
     this.objectSpace = objectSpace;
     this.objectType = objectType;
     this.criteria = criteria;
     this.defaultSorting = BaseObjectSpace.ConvertSortingToString(sorting);
     keyExpression = objectSpace.GetKeyPropertyName(objectType);
     ITypeInfo typeInfo = objectSpace.TypesInfo.FindTypeInfo(objectType);
     entityServerModeFrontEnd = new EntityServerModeFrontEnd(this);
     serverModeSourceAdderRemover = new NHServerModeSourceAdderRemover(entityServerModeFrontEnd, objectSpace, objectType);
     InitQueryableSource();
     entityServerModeFrontEnd.CatchUp();
 }
        /// <summary>
        /// Показать окно предпросмотра отчета
        /// </summary>
        /// <param name="reportController">Контроллер</param>
        /// <param name="reportContainerHandle">Дескриптор</param>
        /// <param name="parametersObject">Объект параметров</param>
        /// <param name="criteria">Критерий</param>
        /// <param name="canApplyCriteria">Можно ли применить критерий</param>
        /// <param name="sortProperty">Сортировка</param>
        /// <param name="canApplySortProperty">Можно ли применить сортировку</param>
        /// <param name="showViewParameters">Объект DevExpress.ExpressApp.ShowViewParameters</param>
        public static void ShowPreview(this ReportServiceController reportController, string reportContainerHandle, ReportParametersObjectBase parametersObject, CriteriaOperator criteria, bool canApplyCriteria, SortProperty[] sortProperty, bool canApplySortProperty, ShowViewParameters showViewParameters)
        {
            var objectSpace = ReportDataProvider.ReportObjectSpaceProvider.CreateObjectSpace(typeof(ReportDataV2));
            Audit.ReportTrail.LogOperation(objectSpace, reportContainerHandle, parametersObject);

            var type = reportController.GetType().BaseType;
            var method = type.GetMethod("ShowReportPreview", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[] { typeof(string), typeof(ReportParametersObjectBase), typeof(CriteriaOperator), typeof(bool), typeof(SortProperty[]), typeof(bool), typeof(ShowViewParameters) }, null);

            if (method != null)
            {
                method.Invoke(reportController, new object[] { reportContainerHandle, parametersObject, criteria, canApplyCriteria, sortProperty, canApplySortProperty, showViewParameters });
            }
        }
Esempio n. 29
0
        public static CriteriaOperator Parse(string propertyPath, CriteriaOperator criteriaOperator) {
            while (propertyPath.IndexOf(".", StringComparison.Ordinal) > -1) {
                propertyPath = propertyPath.Substring(0, propertyPath.IndexOf(".", StringComparison.Ordinal)) + "[" +
                               propertyPath.Substring(propertyPath.IndexOf(".", StringComparison.Ordinal) + 1) + "]";
            }
            for (int i = propertyPath.Length - 1; i > -1; i--)
                if (propertyPath[i] != ']') {
                    propertyPath = propertyPath.Substring(0, i + 1) + "[" + criteriaOperator.ToString() + "]" +
                                   new string(']', propertyPath.Length - i - 1);
                    break;
                }

            return CriteriaOperator.Parse(propertyPath);
        }
Esempio n. 30
0
        public BinaryCriteria(BaseCriteria left, CriteriaOperator op, BaseCriteria right)
        {
            if (ReferenceEquals(left, null))
                throw new ArgumentNullException("left");

            if (ReferenceEquals(right, null))
                throw new ArgumentNullException("right");

            if (op < CriteriaOperator.AND || op > CriteriaOperator.NotLike)
                throw new ArgumentOutOfRangeException("op");

            this.left = left;
            this.right = right;
            this.op = op;
        }
Esempio n. 31
0
        public IHttpActionResult SupplierUseAnimalProductDetail()
        {
            try
            {
                string QuotaType    = HttpContext.Current.Request.Form["QuotaType"].ToString();
                string BudgetSource = HttpContext.Current.Request.Form["BudgetSource"].ToString();

                XpoTypesInfoHelper.GetXpoTypeInfoSource();
                XPObjectSpaceProvider directProvider = new XPObjectSpaceProvider(scc, null);
                IObjectSpace          ObjectSpace    = directProvider.CreateObjectSpace();
                XafTypesInfo.Instance.RegisterEntity(typeof(SupplierUseAnimalProductDetail));

                IList <SupplierUseAnimalProductDetail>      collection  = ObjectSpace.GetObjects <SupplierUseAnimalProductDetail>(CriteriaOperator.Parse(" BudgetSourceOid.Oid = '" + BudgetSource + "' and GCRecord is null and QuotaTypeOid.Oid = ?", QuotaType));
                List <SupplierUseAnimalProductDetail_Model> list_detail = new List <SupplierUseAnimalProductDetail_Model>();
                if (collection.Count > 0)
                {
                    //  SupplierUseAnimalProductDetail ObjMaster;

                    foreach (SupplierUseAnimalProductDetail row in collection)
                    {
                        SupplierUseAnimalProductDetail_Model Model = new SupplierUseAnimalProductDetail_Model();
                        Model.BudgetSource      = row.BudgetSourceOid.BudgetName;
                        Model.AnimalSupplie     = row.AnimalSupplieOid.AnimalSupplieName;
                        Model.QuotaType         = row.QuotaTypeOid.QuotaName;
                        Model.AnimalSupplieType = row.AnimalSupplieTypeOid.SupplietypeName;
                        Model.AnimalSeed        = "";
                        Model.StockUsed         = row.StockUsed;
                        Model.StockLimit        = row.StockLimit;
                        Model.QuotaQTY          = row.QuotaQTY;
                        Model.Amount            = row.Amount;
                        list_detail.Add(Model);
                    }
                    return(Ok(list_detail));
                }
                else
                {
                    return(BadRequest("NoData"));
                }
            }
            catch (Exception ex)
            {                      //Error case เกิดข้อผิดพลาด
                UserError err = new UserError();
                err.code    = "6"; // error จากสาเหตุอื่นๆ จะมีรายละเอียดจาก system แจ้งกลับ
                err.message = ex.Message;
                //  Return resual
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 32
0
 private Department FindDepartment(string departmentTitle) => ObjectSpace.FindObject <Department>(CriteriaOperator.Parse("Title=?", departmentTitle), true);
Esempio n. 33
0
 private Contact FindContact(string firstName, string lastName) => ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse($"FirstName == '{firstName}' && LastName == '{lastName}'"));
Esempio n. 34
0
        private static ExpressionEvaluator GetExpressionEvaluator(IModelNode dataSourceNode, CriteriaOperator criteriaOperator)
        {
            var typeInfo                   = dataSourceNode.GetGenericListArgument();
            var descendants                = ReflectionHelper.FindTypeDescendants(typeInfo);
            var propertyDescriptors        = descendants.SelectMany(info => info.Members).DistinctBy(info => info.Name).Select(info => new XafPropertyDescriptor(info, info.Name)).Cast <PropertyDescriptor>().ToArray();
            var evaluatorContextDescriptor = new EvaluatorContextDescriptorDefault(new PropertyDescriptorCollection(propertyDescriptors));

            return(new ExpressionEvaluator(evaluatorContextDescriptor, criteriaOperator, false,
                                           ((TypesInfo)XafTypesInfo.Instance).EntityStores.OfType <XpoTypeInfoSource>().First().XPDictionary.CustomFunctionOperators));
        }
Esempio n. 35
0
        private Contact GetContact(DataRow employee)
        {
            string  email   = Convert.ToString(employee["EmailAddress"]);
            Contact contact = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("Email=?", email));

            if (contact == null)
            {
                contact           = ObjectSpace.CreateObject <Contact>();
                contact.Email     = email;
                contact.FirstName = Convert.ToString(employee["FirstName"]);
                contact.LastName  = Convert.ToString(employee["LastName"]);
                contact.Birthday  = Convert.ToDateTime(employee["BirthDate"]);
                contact.Photo     = Convert.FromBase64String(Convert.ToString(employee["ImageData"]));
                string titleOfCourtesyText = Convert.ToString(employee["Title"]).ToLower();
                if (!string.IsNullOrEmpty(titleOfCourtesyText))
                {
                    titleOfCourtesyText = titleOfCourtesyText.Replace(".", "");
                    TitleOfCourtesy titleOfCourtesy;
                    if (Enum.TryParse <TitleOfCourtesy>(titleOfCourtesyText, true, out titleOfCourtesy))
                    {
                        contact.TitleOfCourtesy = titleOfCourtesy;
                    }
                }
                PhoneNumber phoneNumber = ObjectSpace.CreateObject <PhoneNumber>();
                phoneNumber.Party     = contact;
                phoneNumber.Number    = Convert.ToString(employee["Phone"]);
                phoneNumber.PhoneType = "Work";

                Address address = ObjectSpace.CreateObject <Address>();
                contact.Address1      = address;
                address.ZipPostal     = Convert.ToString(employee["PostalCode"]);
                address.Street        = Convert.ToString(employee["AddressLine1"]);
                address.City          = Convert.ToString(employee["City"]);
                address.StateProvince = Convert.ToString(employee["StateProvinceName"]);
                string  countryName = Convert.ToString(employee["CountryRegionName"]);
                Country country     = ObjectSpace.FindObject <Country>(CriteriaOperator.Parse("Name=?", countryName), true);
                if (country == null)
                {
                    country      = ObjectSpace.CreateObject <Country>();
                    country.Name = countryName;
                }
                address.Country = country;

                string departmentTitle = Convert.ToString(employee["GroupName"]);
                contact.Department = FindDepartment(departmentTitle);

                string   positionTitle = Convert.ToString(employee["JobTitle"]);
                Position position      = FindPosition(positionTitle);
                if (position == null)
                {
                    position       = ObjectSpace.CreateObject <Position>();
                    position.Title = positionTitle;
                    if (contact.Department != null)
                    {
                        position.Departments.Add(contact.Department);
                        contact.Department.Positions.Add(position);
                    }
                }
                contact.Position = position;
            }
            return(contact);
        }
Esempio n. 36
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return(CriteriaOperator.Parse("[FilterType] == ?", value));
 }
 private void simpleButton_imprimir_Click(object sender, EventArgs e)
 {
     //
     llview_tot_fec  = (checkButton_view_tot_fechas.Checked);
     llview_gran_tot = (checkButton_view_gran_total.Checked);
     //
     if (this.checkEdit_todosfecha.CheckState == CheckState.Unchecked)
     {
         lfecha_desde = ((DateTime)dateTime_fecha_desde.EditValue).Date.ToShortDateString();
         lfecha_hasta = ((DateTime)dateTime_fecha_hasta.EditValue).Date.ToShortDateString();
         string lfecha_desde1 = lfecha_desde.Substring(6, 4) + lfecha_desde.Substring(3, 2) + lfecha_desde.Substring(0, 2);
         string lfecha_hasta1 = lfecha_hasta.Substring(6, 4) + lfecha_hasta.Substring(3, 2) + lfecha_hasta.Substring(0, 2);
         lfiltro_report = string.Format("ToStr(GetYear(fecha_hora))+PadLeft(ToStr(GetMonth(fecha_hora)),2,'0')+PadLeft(ToStr(GetDay(fecha_hora)),2,'0') >= '{0}' and ToStr(GetYear(fecha_hora))+PadLeft(ToStr(GetMonth(fecha_hora)),2,'0')+PadLeft(ToStr(GetDay(fecha_hora)),2,'0') <= '{1}'", lfecha_desde1, lfecha_hasta1);
         //
         //lfecha_desde = ((DateTime)dateTime_fecha_desde.EditValue).Date.ToShortDateString();
         //lfecha_hasta = ((DateTime)dateTime_fecha_hasta.EditValue).Date.ToShortDateString();
         //lfiltro_report = string.Format("GetDate(fecha_hora) >= '{0}' and GetDate(fecha_hora) <= '{1}'", ((DateTime)dateTime_fecha_desde.EditValue).Date, ((DateTime)dateTime_fecha_hasta.EditValue).Date);
     }
     else
     {
         lfecha_desde   = "Todas";
         lfecha_hasta   = "Todas";
         lfiltro_report = "1 = 1";
     }
     //
     if (this.textEdit_codigointegrado.Text.Trim() != string.Empty)
     {
         lcodigointegrado = this.textEdit_codigointegrado.Text.Trim();
         lfiltro_report   = lfiltro_report + " and " + string.Format("trim(tostr(sucursal))+trim(banco_cuenta.codigo_cuenta)+trim(nro_deposito) = '{0}'", lcodigointegrado);
     }
     else
     {
         lcodigointegrado = "Todos";
     }
     //
     if (this.checkEdit_todossucursal.CheckState == CheckState.Unchecked)
     {
         lsucursal      = this.lookUpEdit_sucursal.Text;
         lnsucursal     = (int)this.lookUpEdit_sucursal.EditValue;
         lfiltro_report = lfiltro_report + " and " + string.Format("sucursal = {0}", lnsucursal);
     }
     else
     {
         lsucursal = "Todas";
     }
     //
     if (this.checkEdit_todosbanco.CheckState == CheckState.Unchecked)
     {
         lbanco         = this.lookUpEdit_banco.Text;
         loid_banco     = (Guid)this.lookUpEdit_banco.EditValue;
         lfiltro_report = lfiltro_report + " and " + string.Format("banco_cuenta.banco.oid = '{0}'", loid_banco);
     }
     else
     {
         lbanco = "Todos";
     }
     //
     if (this.checkEdit_todoscuenta.CheckState == CheckState.Unchecked)
     {
         lcuenta        = this.lookUpEdit_cuenta.Text;
         loid_cuenta    = (Guid)this.lookUpEdit_cuenta.EditValue;
         lfiltro_report = lfiltro_report + " and " + string.Format("banco_cuenta.oid = '{0}'", loid_cuenta);
     }
     else
     {
         lcuenta = "Todas";
     }
     //
     if (this.checkEdit_todosresponsable.CheckState == CheckState.Unchecked)
     {
         lresponsable     = this.lookUpEdit_responsable.Text;
         loid_responsable = (Guid)this.lookUpEdit_responsable.EditValue;
         lfiltro_report   = lfiltro_report + " and " + string.Format("responsable_deposito.oid = '{0}'", loid_responsable);
     }
     else
     {
         lresponsable = "Todos";
     }
     //
     if (this.checkEdit_todoselaborado.CheckState == CheckState.Unchecked)
     {
         lelaborado     = this.lookUpEdit_elaborado.Text;
         loid_elaborado = (Guid)this.lookUpEdit_elaborado.EditValue;
         lfiltro_report = lfiltro_report + " and " + string.Format("elaborado.oid = '{0}'", loid_elaborado);
     }
     else
     {
         lelaborado = "Todos";
     }
     //
     if (this.checkEdit_todosrevisado.CheckState == CheckState.Unchecked)
     {
         lrevisado      = this.lookUpEdit_revisado.Text;
         loid_revisado  = (Guid)this.lookUpEdit_revisado.EditValue;
         lfiltro_report = lfiltro_report + " and " + string.Format("revisado.oid = '{0}'", loid_revisado);
     }
     else
     {
         lrevisado = "Todos";
     }
     //
     if (this.checkEdit_todosndepositos.CheckState == CheckState.Unchecked & this.textEdit_ndeposito.Text.Trim() != string.Empty)
     {
         lndeposito     = this.textEdit_ndeposito.Text.Trim();
         nro_deposito   = this.textEdit_ndeposito.Text.Trim();
         lfiltro_report = lfiltro_report + " and " + string.Format("nro_deposito = '{0}'", nro_deposito);
     }
     else
     {
         lndeposito = "Todos";
     }
     //
     if (this.checkEdit_todosncataporte.CheckState == CheckState.Unchecked & this.textEdit_ncataporte.Text.Trim() != string.Empty)
     {
         lncataporte    = this.textEdit_ncataporte.Text.Trim();
         nro_cataporte  = this.textEdit_ncataporte.Text.Trim();
         lfiltro_report = lfiltro_report + " and " + string.Format("nro_cataporte = '{0}'", nro_cataporte);
     }
     else
     {
         lncataporte = "Todos";
     }
     //
     if (this.checkEdit_todosstatus.CheckState == CheckState.Unchecked)
     {
         lstatus        = this.lookUpEdit_status.Text;
         lnstatus       = (int)this.lookUpEdit_status.EditValue;
         lfiltro_report = lfiltro_report + " and " + string.Format("status = '{0}'", lnstatus);
     }
     else
     {
         lstatus = "Todos";
     }
     //
     if (checkButton_order_fecha_ascendente.Checked == true)
     {
         ln_ordenfecha     = 1;
         depositos.Sorting = orden_fecha_ascendente_depositos;
     }
     else
     {
         ln_ordenfecha     = 2;
         depositos.Sorting = orden_fecha_descendente_depositos;
     }
     //
     depositos.Criteria = CriteriaOperator.Parse(lfiltro_report);
     //
     if (lookUpEdit_modeloreport.EditValue.ToString().Trim() == "0")
     {
         XtraReport_Depositos1 report_depositos = new XtraReport_Depositos1(lfecha_desde, lfecha_hasta, lbanco, lcuenta, lresponsable, lelaborado, lrevisado, lndeposito, lncataporte, lstatus, llview_tot_fec, llview_gran_tot, ln_ordenfecha, lsucursal);
         report_depositos.Landscape  = false;
         report_depositos.DataSource = depositos;
         report_depositos.ShowRibbonPreviewDialog();
     }
     else
     {
         XtraReport_Depositos report_depositos = new XtraReport_Depositos(lfecha_desde, lfecha_hasta, lbanco, lcuenta, lresponsable, lelaborado, lrevisado, lndeposito, lncataporte, lstatus, llview_tot_fec, llview_gran_tot, ln_ordenfecha, lsucursal);
         report_depositos.Landscape  = true;
         report_depositos.DataSource = depositos;
         report_depositos.ShowRibbonPreviewDialog();
     }
 }
Esempio n. 38
0
        private void InitUI()
        {
            try
            {
                //Init Local Vars
                _configurationCountry = (_dataSourceRow as erp_customer).Country;
                /* When customers already have a document issued to them, edit Fiscal Number field is not allowed */
                if (_dialogMode != DialogMode.Insert)
                {
                    _customer = (_dataSourceRow as erp_customer);

                    /* IN009249 - begin */
                    string customerFiscalNumberCrypto = GlobalFramework.PluginSoftwareVendor.Encrypt(_customer.FiscalNumber);
                    string countSQL = string.Format("EntityFiscalNumber = '{0}'", customerFiscalNumberCrypto);

                    var countResult = GlobalFramework.SessionXpo.Evaluate(typeof(fin_documentfinancemaster), CriteriaOperator.Parse("Count()"), CriteriaOperator.Parse(countSQL));
                    _totalNumberOfFinanceDocuments = Convert.ToUInt16(countResult);
                    /* IN009249 - end */

                    if (_customer.Oid == SettingsApp.XpoOidDocumentFinanceMasterFinalConsumerEntity)
                    {
                        _isFinalConsumerEntity = true;
                    }
                }

                //erp_customer customers = null;
                SortingCollection sortCollection = new SortingCollection();
                sortCollection.Add(new SortProperty("Code", DevExpress.Xpo.DB.SortingDirection.Ascending));
                CriteriaOperator criteria            = CriteriaOperator.Parse(string.Format("(Disabled = 0 OR Disabled IS NULL)"));
                ICollection      collectionCustomers = GlobalFramework.SessionXpo.GetObjects(GlobalFramework.SessionXpo.GetClassInfo(typeof(erp_customer)), criteria, sortCollection, int.MaxValue, false, true);

                //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
                //Tab1
                VBox vboxTab1 = new VBox(false, _boxSpacing)
                {
                    BorderWidth = (uint)_boxSpacing
                };

                //Ord
                Entry       entryOrd = new Entry();
                BOWidgetBox boxLabel = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_record_order"), entryOrd);
                vboxTab1.PackStart(boxLabel, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxLabel, _dataSourceRow, "Ord", SettingsApp.RegexIntegerGreaterThanZero, true));

                //Code
                Entry       entryCode = new Entry();
                BOWidgetBox boxCode   = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_record_code"), entryCode);
                vboxTab1.PackStart(boxCode, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxCode, _dataSourceRow, "Code", SettingsApp.RegexIntegerGreaterThanZero, true));

                //FiscalNumber
                _entryFiscalNumber = new Entry();
                BOWidgetBox boxFiscalNumber = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_fiscal_number"), _entryFiscalNumber);
                vboxTab1.PackStart(boxFiscalNumber, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxFiscalNumber, _dataSourceRow, "FiscalNumber", _configurationCountry.RegExFiscalNumber, true));/* IN009061 */

                //Name
                _entryName = new Entry();
                BOWidgetBox boxName = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_name"), _entryName);
                vboxTab1.PackStart(boxName, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxName, _dataSourceRow, "Name", SettingsApp.RegexAlfaNumericPlus, true));/* IN009253 */

                //Discount
                Entry       entryDiscount = new Entry();
                BOWidgetBox boxDiscount   = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_discount"), entryDiscount);
                vboxTab1.PackStart(boxDiscount, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxDiscount, _dataSourceRow, "Discount", SettingsApp.RegexPercentage, true));

                //PriceType IN:009261
                XPOComboBox xpoComboBoxPriceType = new XPOComboBox(DataSourceRow.Session, typeof(fin_configurationpricetype), (DataSourceRow as erp_customer).PriceType, "Designation", null, null, 1);
                BOWidgetBox boxPriceType         = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_price_type"), xpoComboBoxPriceType);
                vboxTab1.PackStart(boxPriceType, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxPriceType, DataSourceRow, "PriceType", SettingsApp.RegexGuid, true));

                //CustomerType IN009261
                SortProperty[] sortPropertyCostumerType = new SortProperty[1];
                sortPropertyCostumerType[0] = new SortProperty("Designation", SortingDirection.Descending);

                _xpoComboBoxCustomerType = new XPOComboBox(DataSourceRow.Session, typeof(erp_customertype), (DataSourceRow as erp_customer).CustomerType, "Designation", null, sortPropertyCostumerType, 1);
                BOWidgetBox boxCustomerType = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_customer_types"), _xpoComboBoxCustomerType);
                vboxTab1.PackStart(boxCustomerType, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxCustomerType, DataSourceRow, "CustomerType", SettingsApp.RegexGuid, true));

                ////DISABLED : DiscountGroup
                //XPOComboBox xpoComboBoxDiscountGroup = new XPOComboBox(DataSourceRow.Session, typeof(erp_customerdiscountgroup), (DataSourceRow as erp_customer).DiscountGroup, "Designation");
                //BOWidgetBox boxDiscountGroup = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_discount_group, xpoComboBoxDiscountGroup);
                //vboxTab1.PackStart(boxDiscountGroup, false, false, 0);
                //_crudWidgetList.Add(new GenericCRUDWidgetXPO(boxDiscountGroup, DataSourceRow, "DiscountGroup", SettingsApp.RegexGuid, true));

                //Supplier
                CheckButton checkButtonSupplier = new CheckButton(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_supplier"));
                vboxTab1.PackStart(checkButtonSupplier, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(checkButtonSupplier, _dataSourceRow, "Supplier"));

                //Disabled
                CheckButton checkButtonDisabled = new CheckButton(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_record_disabled"));
                if (_dialogMode == DialogMode.Insert)
                {
                    checkButtonDisabled.Active = SettingsApp.BOXPOObjectsStartDisabled;
                }
                vboxTab1.PackStart(checkButtonDisabled, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(checkButtonDisabled, _dataSourceRow, "Disabled"));

                //Append Tab
                _notebook.AppendPage(vboxTab1, new Label(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_record_main_detail")));

                //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
                //Tab2

                VBox vboxTab2 = new VBox(false, _boxSpacing)
                {
                    BorderWidth = (uint)_boxSpacing
                };

                //Address
                _entryAddress = new Entry();
                BOWidgetBox boxAddress = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_address"), _entryAddress);
                vboxTab2.PackStart(boxAddress, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxAddress, _dataSourceRow, "Address", SettingsApp.RegexAlfaNumericPlus, false));/* IN009253 */

                //Locality
                _entryLocality = new Entry();
                BOWidgetBox boxLocality = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_locality"), _entryLocality);
                vboxTab2.PackStart(boxLocality, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxLocality, _dataSourceRow, "Locality", SettingsApp.RegexAlfaNumericPlus, false));/* IN009253 */

                //ZipCode
                _entryZipCode = new Entry()
                {
                    WidthRequest = 100
                };;
                BOWidgetBox boxZipCode = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_zipcode"), _entryZipCode);
                vboxTab2.PackStart(boxZipCode, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxZipCode, _dataSourceRow, "ZipCode", _configurationCountry.RegExZipCode, false));

                //City
                _entryCity = new Entry();
                BOWidgetBox boxCity = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_city"), _entryCity);
                vboxTab2.PackStart(boxCity, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxCity, _dataSourceRow, "City", SettingsApp.RegexAlfaNumericPlus, false)); /* IN009176, IN009253 */

                //Hbox ZipCode and City
                HBox hboxZipCodeAndCity = new HBox(false, _boxSpacing);
                hboxZipCodeAndCity.PackStart(boxZipCode, true, true, 0);
                hboxZipCodeAndCity.PackStart(boxCity, true, true, 0);
                vboxTab2.PackStart(hboxZipCodeAndCity, false, false, 0);

                //CountrySortProperty
                SortProperty[] sortPropertyCountry = new SortProperty[1];
                sortPropertyCountry[0] = new SortProperty("Designation", SortingDirection.Ascending);
                //Country
                _xpoComboBoxCountry = new XPOComboBox(DataSourceRow.Session, typeof(cfg_configurationcountry), (DataSourceRow as erp_customer).Country, "Designation", null, sortPropertyCountry);
                BOWidgetBox boxCountry = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_country"), _xpoComboBoxCountry);
                vboxTab2.PackStart(boxCountry, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxCountry, DataSourceRow, "Country", SettingsApp.RegexGuid, true));

                //Phone
                Entry       entryPhone = new Entry();
                BOWidgetBox boxPhone   = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_phone"), entryPhone);
                vboxTab2.PackStart(boxPhone, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxPhone, _dataSourceRow, "Phone", SettingsApp.RegexAlfaNumericExtended, false));

                //MobilePhone
                Entry       entryMobilePhone = new Entry();
                BOWidgetBox boxMobilePhone   = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_mobile_phone"), entryMobilePhone);
                vboxTab2.PackStart(boxMobilePhone, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxMobilePhone, _dataSourceRow, "MobilePhone", SettingsApp.RegexAlfaNumericExtended, false));

                //Hbox Phone and MobilePhone
                HBox hboxPhoneAndMobilePhone = new HBox(false, _boxSpacing);
                hboxPhoneAndMobilePhone.PackStart(boxPhone, true, true, 0);
                hboxPhoneAndMobilePhone.PackStart(boxMobilePhone, true, true, 0);
                vboxTab2.PackStart(hboxPhoneAndMobilePhone, false, false, 0);

                //Fax
                Entry       entryFax = new Entry();
                BOWidgetBox boxFax   = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_fax"), entryFax);
                vboxTab2.PackStart(boxFax, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxFax, _dataSourceRow, "Fax", SettingsApp.RegexAlfaNumericExtended, false));

                //Email
                Entry       entryEmail = new Entry();
                BOWidgetBox boxEmail   = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_email"), entryEmail);
                vboxTab2.PackStart(boxEmail, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxEmail, _dataSourceRow, "Email", SettingsApp.RegexEmail, false));

                //Hbox Fax and Email
                HBox hboxFaxAndEmail = new HBox(false, _boxSpacing);
                hboxFaxAndEmail.PackStart(boxFax, true, true, 0);
                hboxFaxAndEmail.PackStart(boxEmail, true, true, 0);
                vboxTab2.PackStart(hboxFaxAndEmail, false, false, 0);

                //Append Tab
                _notebook.AppendPage(vboxTab2, new Label(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_contacts")));

                //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
                //Tab3

                VBox vboxTab3 = new VBox(false, _boxSpacing)
                {
                    BorderWidth = (uint)_boxSpacing
                };

                //CardNumber
                Entry       entryCardNumber = new Entry();
                BOWidgetBox boxCardNumber   = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_card_number"), entryCardNumber);
                vboxTab3.PackStart(boxCardNumber, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxCardNumber, _dataSourceRow, "CardNumber", SettingsApp.RegexAlfaNumericExtended, false));

                //CardCredit
                Entry       entryCardCredit = new Entry();
                BOWidgetBox boxCardCredit   = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_card_credit_amount"), entryCardCredit);
                vboxTab3.PackStart(boxCardCredit, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxCardCredit, _dataSourceRow, "CardCredit", SettingsApp.RegexDecimalGreaterEqualThanZero, false));

                //DateOfBirth
                Entry       entryDateOfBirth = new Entry();
                BOWidgetBox boxDateOfBirth   = new BOWidgetBox(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_dob"), entryDateOfBirth);
                vboxTab3.PackStart(boxDateOfBirth, false, false, 0);
                _crudWidgetList.Add(new GenericCRUDWidgetXPO(boxDateOfBirth, _dataSourceRow, "DateOfBirth", SettingsApp.RegexDate, false));

                //Append Tab
                _notebook.AppendPage(vboxTab3, new Label(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_others")));

                //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

                //Disable Components
                _entryName.Sensitive          = GetEntryNameSensitiveValue();
                entryCardCredit.Sensitive     = false;
                _entryFiscalNumber.Sensitive  = GetEntryFiscalNumberSensitiveValue();
                _xpoComboBoxCountry.Sensitive = GetEntryFiscalNumberSensitiveValue();

                //Get References to GenericCRUDWidgetXPO
                _genericCRUDWidgetXPOFiscalNumber = (_crudWidgetList.GetFieldWidget("FiscalNumber") as GenericCRUDWidgetXPO);
                _genericCRUDWidgetXPOZipCode      = (_crudWidgetList.GetFieldWidget("ZipCode") as GenericCRUDWidgetXPO);
                //Call Validation
                _genericCRUDWidgetXPOFiscalNumber.ValidateField(ValidateFiscalNumberFunc);

                //Update Components
                UpdateCountryRegExComponents();
                //string teste = (DataSourceRow as erp_customer).CustomerType.Designation;
                //Events
                _entryFiscalNumber.Changed  += delegate { ValidateFiscalNumber(); };
                _xpoComboBoxCountry.Changed += delegate { UpdateCountryRegExComponents(); };
                //IN009260 Inserir Cliente permite código já inserido
                entryCode.Changed += delegate
                {
                    foreach (erp_customer item in collectionCustomers)
                    {
                        if (entryCode.Text == item.Code.ToString())
                        {
                            Utils.ShowMessageTouch(GlobalApp.WindowBackOffice, DialogFlags.DestroyWithParent | DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "window_title_dialog_validation_error"), resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message_code_number_exists"));
                            entryCode.Text = "";
                        }
                    }
                };

                entryOrd.Changed += delegate
                {
                    foreach (erp_customer item in collectionCustomers)
                    {
                        if (entryOrd.Text == item.Code.ToString())
                        {
                            Utils.ShowMessageTouch(GlobalApp.WindowBackOffice, DialogFlags.DestroyWithParent | DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "window_title_dialog_validation_error"), resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message_code_number_exists"));
                            entryOrd.Text = "";
                        }
                    }
                };
            }
            catch (System.Exception ex)
            {
                _log.Error("void DialogCustomer.InitUI(): " + ex.Message, ex);
            }
        }
Esempio n. 39
0
        private void GenerateData()
        {
            BetweenOperator  BetweenFechas = new BetweenOperator("FechaEntrada", FechaDesde, FechaHasta);
            CriteriaOperator criteria      = CriteriaOperator.And(BetweenFechas);
            ICollection <SolicitudReparacion> ListadoDeSolicitudes = ObjectSpace.GetObjects <SolicitudReparacion>(criteria);

            int     NoAplica = 0; int Ingresada = 0; int Enviada = 0; int Autorizada = 0; int DiagnosticoRealizado = 0; int ObtencionAlmacen = 0;
            int     ObtencionCajaChica = 0; int ObtencionUACI = 0; int Reparacion = 0; int Finalizada = 0; int Anulada = 0;
            decimal totalNoAplica = 0; decimal totalIngresada = 0; decimal totalEnviada = 0; decimal totalAutorizada = 0; decimal totalDiagnosticoRealizado = 0;
            decimal totalObtencionAlmacen = 0; decimal totalObtencionCajaChica = 0; decimal totalObtencionUACI = 0; decimal totalReparacion = 0;
            decimal totalFinalizada = 0; decimal totalAnulada = 0; decimal CostoProyectado = 0; decimal CostoReal = 0;

            int Servicio = 0; decimal totalServicio = 0; int Preventivo = 0; decimal TotalPreventivo = 0; int Correctivo = 0; decimal totalCorrectivo = 0;


            foreach (SolicitudReparacion SolicitudList in ListadoDeSolicitudes)
            {
                decimal total = 0;

                BinaryOperator               BinaryCompra   = new BinaryOperator("CompraRepuestos", SolicitudList);
                CriteriaOperator             criteriaCompra = CriteriaOperator.And(BinaryCompra);
                ICollection <CompraRepuesto> ListadoCompras = ObjectSpace.GetObjects <CompraRepuesto>(criteriaCompra);

                if (!ReferenceEquals(ListadoCompras, null))
                {
                    foreach (CompraRepuesto ComprasList in ListadoCompras)
                    {
                        total = total + ComprasList.Total;
                    }
                }


                if (SolicitudList.EstadoSolicitud == EstadoSolicitud.NoAplica)
                {
                    NoAplica++;
                    totalNoAplica = totalNoAplica + total;
                }
                else if (SolicitudList.EstadoSolicitud == EstadoSolicitud.Ingresada)
                {
                    Ingresada++;
                    totalIngresada = totalIngresada + total;
                }
                else if (SolicitudList.EstadoSolicitud == EstadoSolicitud.Enviada)
                {
                    Enviada++;
                    totalEnviada = totalEnviada + total;
                }
                else if (SolicitudList.EstadoSolicitud == EstadoSolicitud.Autorizada)
                {
                    Autorizada++;
                    totalAutorizada = totalAutorizada + total;
                }
                else if (SolicitudList.EstadoSolicitud == EstadoSolicitud.DiagnosticoRealizado)
                {
                    DiagnosticoRealizado++;
                    totalDiagnosticoRealizado = totalDiagnosticoRealizado + total;
                }
                else if (SolicitudList.EstadoSolicitud == EstadoSolicitud.ObtencionAlmacen)
                {
                    ObtencionAlmacen++;
                    totalObtencionAlmacen = totalObtencionAlmacen + total;
                }
                else if (SolicitudList.EstadoSolicitud == EstadoSolicitud.ObtencionCajaChica)
                {
                    ObtencionCajaChica++;
                    totalObtencionCajaChica = totalObtencionCajaChica + total;
                }
                else if (SolicitudList.EstadoSolicitud == EstadoSolicitud.ObtencionUACI)
                {
                    ObtencionUACI++;
                    totalObtencionUACI = totalObtencionUACI + total;
                }
                else if (SolicitudList.EstadoSolicitud == EstadoSolicitud.Reparacion)
                {
                    Reparacion++;
                    totalReparacion = totalReparacion + total;
                }
                else if (SolicitudList.EstadoSolicitud == EstadoSolicitud.Finalizada)
                {
                    Finalizada++;
                    totalFinalizada = totalFinalizada + total;
                }
                else if (SolicitudList.EstadoSolicitud == EstadoSolicitud.Anulada)
                {
                    Anulada++;
                    totalAnulada = totalAnulada + total;
                }



                if (!ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Anulada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Autorizada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Enviada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Ingresada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.NoAplica))
                {
                    int              mantenimiento       = 0;
                    BinaryOperator   BinaryDiagnostico   = new BinaryOperator("DiagnosticoSolicitud", SolicitudList);
                    CriteriaOperator criteriaDiagnostico = CriteriaOperator.And(BinaryDiagnostico);
                    ICollection <SolicitudDiagnostico> ListadoDiagnostico = ObjectSpace.GetObjects <SolicitudDiagnostico>(criteriaDiagnostico);

                    if (!ReferenceEquals(ListadoDiagnostico, null))
                    {
                        foreach (SolicitudDiagnostico DiagnosticoList in ListadoDiagnostico)
                        {
                            if (DiagnosticoList.TipoMantenimiento == TipoMantenimiento.Servicio)
                            {
                                Servicio++;
                                mantenimiento = 1;
                            }
                            else if (DiagnosticoList.TipoMantenimiento == TipoMantenimiento.Preventivo)
                            {
                                Preventivo++;
                                mantenimiento = 2;
                            }
                            else if (DiagnosticoList.TipoMantenimiento == TipoMantenimiento.Correctivo)
                            {
                                Correctivo++;
                                mantenimiento = 3;
                            }
                        }

                        BinaryOperator               BinaryCompras   = new BinaryOperator("CompraRepuestos", SolicitudList);
                        CriteriaOperator             criteriaCompras = CriteriaOperator.And(BinaryCompras);
                        ICollection <CompraRepuesto> ListadoCompra   = ObjectSpace.GetObjects <CompraRepuesto>(criteriaCompras);

                        total = 0;

                        if (!ReferenceEquals(ListadoCompra, null))
                        {
                            foreach (CompraRepuesto ComprasList in ListadoCompra)
                            {
                                total = total + ComprasList.Total;
                            }
                        }

                        if (mantenimiento == 1)
                        {
                            totalServicio = totalServicio + total;
                        }
                        else if (mantenimiento == 2)
                        {
                            TotalPreventivo = TotalPreventivo + total;
                        }
                        else if (mantenimiento == 3)
                        {
                            totalCorrectivo = totalCorrectivo + total;
                        }
                    }
                }

                CostoReal = totalServicio + TotalPreventivo + totalCorrectivo;
            }
            var newListadoDeSolicitudes = ListadoDeSolicitudes.OrderBy(o => o.CodSolicitud);

            foreach (SolicitudReparacion SolicitudList in newListadoDeSolicitudes)
            {
                if (!ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Anulada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Autorizada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Enviada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Ingresada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.NoAplica))
                {
                    decimal          total = 0; int codigo = 0;
                    BinaryOperator   BinaryAlmacen   = new BinaryOperator("SolicitudRepuesto", SolicitudList);
                    CriteriaOperator criteriaAlmacen = CriteriaOperator.And(BinaryAlmacen);
                    ICollection <SolicitudRepuestos> ListadoRepuesto = ObjectSpace.GetObjects <SolicitudRepuestos>(criteriaAlmacen);

                    if (!ReferenceEquals(ListadoRepuesto, null))
                    {
                        foreach (SolicitudRepuestos ComprasList in ListadoRepuesto)
                        {
                            codigo = SolicitudList.CodSolicitud;
                            total  = total + ComprasList.Total;
                        }
                    }

                    SolicitudList.CostoEjecucionAproximado = total;
                    //CostoProyectado = CostoProyectado + total;
                }
            }

            this.ObjectSpace.CommitChanges();

            foreach (SolicitudReparacion SolicitudList in newListadoDeSolicitudes)
            {
                if (!ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Anulada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Autorizada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Enviada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.Ingresada) && !ReferenceEquals(SolicitudList.EstadoSolicitud, EstadoSolicitud.NoAplica))
                {
                    CostoProyectado = CostoProyectado + SolicitudList.CostoEjecucionAproximado;
                }
            }



            //creando registros para estados de solicitud
            ReporteGeneral reporte0 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte0.Numero          = 0;
            reporte0.Descripcion     = "NoAplica";
            reporte0.Total           = NoAplica;
            reporte0.Eliminar        = true;
            reporte0.Tipo            = "ESTADO SOLICITUD";
            reporte0.Costo           = totalNoAplica;
            reporte0.FechaInicio     = FechaDesde;
            reporte0.FechaFin        = FechaHasta;
            reporte0.CostoProyectado = CostoProyectado;
            reporte0.CostoReal       = CostoReal;

            //creando registros
            ReporteGeneral reporte1 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte1.Numero          = 1;
            reporte1.Descripcion     = "Ingresada";
            reporte1.Total           = Ingresada;
            reporte1.Eliminar        = true;
            reporte1.Tipo            = "ESTADO SOLICITUD";
            reporte1.Costo           = totalIngresada;
            reporte1.FechaInicio     = FechaDesde;
            reporte1.FechaFin        = FechaHasta;
            reporte1.CostoProyectado = CostoProyectado;
            reporte1.CostoReal       = CostoReal;

            //creando registros
            ReporteGeneral reporte2 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte2.Numero          = 2;
            reporte2.Descripcion     = "Enviada";
            reporte2.Total           = Enviada;
            reporte2.Eliminar        = true;
            reporte2.Tipo            = "ESTADO SOLICITUD";
            reporte2.Costo           = totalEnviada;
            reporte2.FechaInicio     = FechaDesde;
            reporte2.FechaFin        = FechaHasta;
            reporte2.CostoProyectado = CostoProyectado;
            reporte2.CostoReal       = CostoReal;

            //creando registros
            ReporteGeneral reporte3 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte3.Numero          = 3;
            reporte3.Descripcion     = "Autorizada";
            reporte3.Total           = Autorizada;
            reporte3.Eliminar        = true;
            reporte3.Tipo            = "ESTADO SOLICITUD";
            reporte3.Costo           = totalAutorizada;
            reporte3.FechaInicio     = FechaDesde;
            reporte3.FechaFin        = FechaHasta;
            reporte3.CostoProyectado = CostoProyectado;
            reporte3.CostoReal       = CostoReal;

            //creando registros
            ReporteGeneral reporte4 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte4.Numero          = 4;
            reporte4.Descripcion     = "DiagnosticoRealizado";
            reporte4.Total           = DiagnosticoRealizado;
            reporte4.Eliminar        = true;
            reporte4.Tipo            = "ESTADO SOLICITUD";
            reporte4.Costo           = totalDiagnosticoRealizado;
            reporte4.FechaInicio     = FechaDesde;
            reporte4.FechaFin        = FechaHasta;
            reporte4.CostoProyectado = CostoProyectado;
            reporte4.CostoReal       = CostoReal;

            //creando registros
            ReporteGeneral reporte5 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte5.Numero          = 5;
            reporte5.Descripcion     = "ObtencionAlmacen";
            reporte5.Total           = ObtencionAlmacen;
            reporte5.Eliminar        = true;
            reporte5.Tipo            = "ESTADO SOLICITUD";
            reporte5.Costo           = totalObtencionAlmacen;
            reporte5.FechaInicio     = FechaDesde;
            reporte5.FechaFin        = FechaHasta;
            reporte5.CostoProyectado = CostoProyectado;
            reporte5.CostoReal       = CostoReal;

            //creando registros
            ReporteGeneral reporte6 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte6.Numero          = 6;
            reporte6.Descripcion     = "ObtencionCajaChica";
            reporte6.Total           = ObtencionCajaChica;
            reporte6.Eliminar        = true;
            reporte6.Tipo            = "ESTADO SOLICITUD";
            reporte6.Costo           = totalObtencionCajaChica;
            reporte6.FechaInicio     = FechaDesde;
            reporte6.FechaFin        = FechaHasta;
            reporte6.CostoProyectado = CostoProyectado;
            reporte6.CostoReal       = CostoReal;

            //creando registros
            ReporteGeneral reporte7 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte7.Numero          = 7;
            reporte7.Descripcion     = "ObtencionUACI";
            reporte7.Total           = ObtencionUACI;
            reporte7.Eliminar        = true;
            reporte7.Tipo            = "ESTADO SOLICITUD";
            reporte7.Costo           = totalObtencionUACI;
            reporte7.FechaInicio     = FechaDesde;
            reporte7.FechaFin        = FechaHasta;
            reporte7.CostoProyectado = CostoProyectado;
            reporte7.CostoReal       = CostoReal;

            //creando registros
            ReporteGeneral reporte8 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte8.Numero          = 8;
            reporte8.Descripcion     = "Reparacion";
            reporte8.Total           = Reparacion;
            reporte8.Eliminar        = true;
            reporte8.Tipo            = "ESTADO SOLICITUD";
            reporte8.Costo           = totalReparacion;
            reporte8.FechaInicio     = FechaDesde;
            reporte8.FechaFin        = FechaHasta;
            reporte8.CostoProyectado = CostoProyectado;
            reporte8.CostoReal       = CostoReal;

            //creando registros
            ReporteGeneral reporte9 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte9.Numero          = 9;
            reporte9.Descripcion     = "Finalizada";
            reporte9.Total           = Finalizada;
            reporte9.Eliminar        = true;
            reporte9.Tipo            = "ESTADO SOLICITUD";
            reporte9.Costo           = totalFinalizada;
            reporte9.FechaInicio     = FechaDesde;
            reporte9.FechaFin        = FechaHasta;
            reporte9.CostoProyectado = CostoProyectado;
            reporte9.CostoReal       = CostoReal;

            //creando registros
            ReporteGeneral reporte10 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte10.Numero          = 10;
            reporte10.Descripcion     = "Anulada";
            reporte10.Total           = Anulada;
            reporte10.Eliminar        = true;
            reporte10.Tipo            = "ESTADO SOLICITUD";
            reporte10.Costo           = totalAnulada;
            reporte10.FechaInicio     = FechaDesde;
            reporte10.FechaFin        = FechaHasta;
            reporte10.CostoProyectado = CostoProyectado;
            reporte10.CostoReal       = CostoReal;

            //creando registros para tipos de mantenimiento
            ReporteGeneral reporte11 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte11.Numero          = 1;
            reporte11.Descripcion     = "Solicitud de servicio";
            reporte11.Total           = Servicio;
            reporte11.Eliminar        = true;
            reporte11.Tipo            = "TIPO DE MANTENIMIENTO";
            reporte11.Costo           = totalServicio;
            reporte11.FechaInicio     = FechaDesde;
            reporte11.FechaFin        = FechaHasta;
            reporte11.CostoProyectado = CostoProyectado;
            reporte11.CostoReal       = CostoReal;

            ReporteGeneral reporte12 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte12.Numero          = 2;
            reporte12.Descripcion     = "Mantenimiento Preventivo";
            reporte12.Total           = Preventivo;
            reporte12.Eliminar        = true;
            reporte12.Tipo            = "TIPO DE MANTENIMIENTO";
            reporte12.Costo           = TotalPreventivo;
            reporte12.FechaInicio     = FechaDesde;
            reporte12.FechaFin        = FechaHasta;
            reporte12.CostoProyectado = CostoProyectado;
            reporte12.CostoReal       = CostoReal;

            ReporteGeneral reporte13 = this.ObjectSpace.CreateObject <ReporteGeneral>();

            reporte13.Numero          = 3;
            reporte13.Descripcion     = "Mantenimiento Correctivo";
            reporte13.Total           = Correctivo;
            reporte13.Eliminar        = true;
            reporte13.Tipo            = "TIPO DE MANTENIMIENTO";
            reporte13.Costo           = totalCorrectivo;
            reporte13.FechaInicio     = FechaDesde;
            reporte13.FechaFin        = FechaHasta;
            reporte13.CostoProyectado = CostoProyectado;
            reporte13.CostoReal       = CostoReal;

            //guardando la data
            this.ObjectSpace.CommitChanges();
        }
Esempio n. 40
0
 // take current condition from fields and save it in criteria string
 public void SaveToAdvancedCriteria()
 {
     _advancedCriteria = GetCriteriaOperator();
     _changed          = true;
 }
Esempio n. 41
0
        public override bool Save(
            DevExpress.Xpo.Session session,
            Guid billId,
            string billCode,
            DateTime issuedDate,
            DAL.Nomenclature.Organization.Organization sourceOrganizationBill,
            DAL.Nomenclature.Organization.Person targetOrganizationBill)
        {
            try
            {
                //Get bill by ID
                NAS.DAL.Invoice.PurchaseInvoice bill =
                    session.GetObjectByKey <NAS.DAL.Invoice.PurchaseInvoice>(billId);
                if (bill == null)
                {
                    throw new Exception("Could not found bill");
                }

                bill.Code                 = billCode;
                bill.IssuedDate           = issuedDate;
                bill.SourceOrganizationId = sourceOrganizationBill;
                bill.TargetOrganizationId = targetOrganizationBill;
                bill.RowStatus            = Utility.Constant.ROWSTATUS_ACTIVE;

                bill.Save();

                //Create default actual transaction
                CriteriaOperator criteria = CriteriaOperator.And(
                    new BinaryOperator("RowStatus", Utility.Constant.ROWSTATUS_ACTIVE, BinaryOperatorType.GreaterOrEqual),
                    CriteriaOperator.Or(
                        new ContainsOperator("GeneralJournals",
                                             new BinaryOperator("JournalType", JounalTypeConstant.ACTUAL)
                                             ),
                        new BinaryOperator(new AggregateOperand("GeneralJournals", Aggregate.Count), 0, BinaryOperatorType.Equal)
                        )
                    );

                var actualPurchaseInvoiceTransactions = bill.PurchaseInvoiceTransactions;

                actualPurchaseInvoiceTransactions.Criteria = criteria;

                if (actualPurchaseInvoiceTransactions == null ||
                    actualPurchaseInvoiceTransactions.Count == 0)
                {
                    PurchaseInvoiceTransaction purchaseInvoiceTransaction
                        = new PurchaseInvoiceTransaction(session)
                        {
                        Code              = "BT_" + bill.Code,
                        CreateDate        = DateTime.Now,
                        Description       = "BT_" + bill.Code,
                        IssueDate         = issuedDate,
                        RowStatus         = Utility.Constant.ROWSTATUS_ACTIVE,
                        UpdateDate        = DateTime.Now,
                        PurchaseInvoiceId = bill
                        };
                    purchaseInvoiceTransaction.Save();

                    ObjectBO objectBO = new ObjectBO();
                    NAS.DAL.CMS.ObjectDocument.Object cmsObject =
                        objectBO.CreateCMSObject(session, DAL.CMS.ObjectDocument.ObjectTypeEnum.INVOICE_PURCHASE);

                    TransactionObject transactionObject = new TransactionObject(session)
                    {
                        ObjectId      = cmsObject,
                        TransactionId = purchaseInvoiceTransaction
                    };

                    transactionObject.Save();
                }

                return(true);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 42
0
 public CriteriaOperator GetCondition()
 {
     //return _data.Count > 0 ? new ContainsOperator(GetFullFieldName(), CriteriaOperator.And(_data.Select(o => o.GetCondition()).AsEnumerable())) : null;
     return(_data.Count > 0 ? CriteriaOperator.And(_data.Select(o => new ContainsOperator(GetFullFieldName(), o.GetCondition())).AsEnumerable()) : null);
 }
Esempio n. 43
0
        public void ExecutarCalculo(IProgress <ImportProgressReport> progress)
        {
            var        session = ((XPObjectSpace)_objectSpace).Session;
            UnitOfWork uow     = new UnitOfWork(session.ObjectLayer);

            var spools            = new XPCollection <Spool>(PersistentCriteriaEvaluationBehavior.InTransaction, uow, null);
            var QuantidadeDeSpool = spools.Count;

            progress.Report(new ImportProgressReport
            {
                TotalRows     = QuantidadeDeSpool,
                CurrentRow    = 0,
                MessageImport = "Inicializando Fechamento"
            });

            uow.BeginTransaction();
            var medicaoAnterior = uow.FindObject <MedicaoTubulacao>(CriteriaOperator.Parse("DataFechamentoMedicao = [<MedicaoTubulacao>].Max(DataFechamentoMedicao)"));
            var medicao         = new MedicaoTubulacao(uow);

            medicao.DataFechamentoMedicao = DateTime.Now;
            medicao.Save();

            for (int i = 0; i < QuantidadeDeSpool; i++)
            {
                var spool = spools[i];
                var detalheMedicaoAnterior = medicaoAnterior is null ? null : uow.FindObject <MedicaoTubulacaoDetalhe>(CriteriaOperator.Parse("Spool.Oid = ? And MedicaoTubulacao.Oid = ?", spool.Oid, medicaoAnterior.Oid));
                var eap     = session.FindObject <TabEAPPipe>(new BinaryOperator("Contrato.Oid", spool.Contrato.Oid));
                var detalhe = new MedicaoTubulacaoDetalhe(uow);

                //var testeLogica = spool.DataCorte;

                var QtdJuntaPipe = Utils.ConvertINT(spool.Evaluate(CriteriaOperator.Parse("Juntas[CampoOuPipe == 'PIPE'].Count()")));
                var QtdJuntaMont = Utils.ConvertINT(spool.Evaluate(CriteriaOperator.Parse("Juntas[CampoOuPipe == 'CAMPO'].Count()")));


                //Cálculo de Montagem (Memória de Cálculo)
                var WdiJuntaTotalMont = Utils.ConvertDouble(spool.Evaluate(CriteriaOperator.Parse("Juntas[CampoOuPipe == 'CAMPO'].Sum(TabDiametro.Wdi)")));
                var WdiJuntaVAMont    = Utils.ConvertDouble(spool.Evaluate(CriteriaOperator.Parse("Juntas[Not IsNullorEmpty(DataVa) And CampoOuPipe == 'CAMPO'].Sum(TabDiametro.Wdi)")));

                var WdiJuntaVANaMontPrev = Utils.ConvertDouble(spool.Evaluate(CriteriaOperator.Parse("Juntas[statusVa == 'N' And CampoOuPipe == 'CAMPO'].Sum(TabDiametro.Wdi)")));
                var WdiJuntaVAApMontPrev = Utils.ConvertDouble(spool.Evaluate(CriteriaOperator.Parse("Juntas[statusVa <> 'N' And CampoOuPipe == 'CAMPO'].Sum(TabDiametro.Wdi)")));
                var WdiJuntaVAApMontExec = Utils.ConvertDouble(spool.Evaluate(CriteriaOperator.Parse("Juntas[Not IsNullorEmpty(DataVa) And statusVa <> 'N' And CampoOuPipe == 'CAMPO'].Sum(TabDiametro.Wdi)")));


                var WdiJuntaSoldMont = Utils.ConvertDouble(spool.Evaluate(CriteriaOperator.Parse("Juntas[Not IsNullorEmpty(DataSoldagem) And CampoOuPipe == 'CAMPO'].Sum(TabDiametro.Wdi)")));
                var WdiJuntaENDMont  = Utils.ConvertDouble(spool.Evaluate(CriteriaOperator.Parse("Juntas[Not IsNullorEmpty(DataLiberacaoJunta) And CampoOuPipe == 'CAMPO'].Sum(TabDiametro.Wdi)")));

                //Avanço de Fabricação (Memória de Cálculo)
                var ExecutadoSpoolDFFab = (Boolean)spool.Evaluate(CriteriaOperator.Parse("Not IsNullorEmpty(DataDfFab)"));
                var AvancoSpoolCorteFab = (Boolean)spool.Evaluate(CriteriaOperator.Parse("Not IsNullorEmpty(DataCorte)"));
                var AvancoSpoolVAFab    = (Boolean)spool.Evaluate(CriteriaOperator.Parse("Not IsNullorEmpty(DataVaFab)"));
                var AvancoSpoolSoldFab  = (Boolean)spool.Evaluate(CriteriaOperator.Parse("Not IsNullorEmpty(DataSoldaFab)"));
                var AvancoSpoolENDFab   = (Boolean)spool.Evaluate(CriteriaOperator.Parse("Not IsNullorEmpty(DataEndFab)"));

                //Avanço de Montagem (Memória de Cálculo)
                var ExecutadoSpoolPosiMont      = (Boolean)spool.Evaluate(CriteriaOperator.Parse("Not IsNullorEmpty(DataPreMontagem)"));
                var ExecutadoSpoolDIMont        = (Boolean)spool.Evaluate(CriteriaOperator.Parse("Not IsNullorEmpty(DataDiMontagem)"));
                var ExecutadoSpoolLineCheckMont = (Boolean)spool.Evaluate(CriteriaOperator.Parse("Not IsNullorEmpty(DataLineCheck)"));

                var AvancoJuntaVAMont   = Utils.CalculoPercentual(WdiJuntaVAMont, WdiJuntaTotalMont);
                var AvancoJuntaSoldMont = Utils.CalculoPercentual(WdiJuntaSoldMont, WdiJuntaTotalMont);
                var AvancoJuntaENDMont  = Utils.CalculoPercentual(WdiJuntaENDMont, WdiJuntaTotalMont);

                detalhe.MedicaoTubulacao  = medicao;
                detalhe.Spool             = spool;
                detalhe.WdiJuntaTotalMont = WdiJuntaTotalMont;

                //Gravar Cálculo de Montagem
                detalhe.WdiJuntaVAMont   = WdiJuntaVAMont;
                detalhe.WdiJuntaSoldMont = WdiJuntaSoldMont;
                detalhe.WdiJuntaENDMont  = WdiJuntaENDMont;

                //Cálculo Fabricação
                var AvancarTrechoRetoFab     = QtdJuntaPipe == 0 && ExecutadoSpoolDFFab;
                var LogicAvancoSpoolENDFab   = AvancoSpoolENDFab || AvancarTrechoRetoFab;
                var LogicAvancoSpoolSoldFab  = AvancoSpoolSoldFab || LogicAvancoSpoolENDFab;
                var LogicAvancoSpoolVAFab    = AvancoSpoolVAFab || LogicAvancoSpoolSoldFab;
                var LogicAvancoSpoolCorteFab = AvancoSpoolCorteFab || LogicAvancoSpoolVAFab;

                //Gravar Avanço de Fabricação
                detalhe.AvancoSpoolCorteFab = LogicAvancoSpoolCorteFab ? 1 : 0;
                detalhe.AvancoSpoolVAFab    = LogicAvancoSpoolVAFab ? 1 : 0;
                detalhe.AvancoSpoolSoldFab  = LogicAvancoSpoolSoldFab ? 1 : 0;
                detalhe.AvancoSpoolENDFab   = LogicAvancoSpoolENDFab ? 1 : 0;


                //Aplicar EAP no Avanço de Fabricação
                detalhe.PesoSpoolCorteFab = (spool.PesoFabricacao * detalhe.AvancoSpoolCorteFab) * eap.AvancoSpoolCorteFab;
                detalhe.PesoSpoolVAFab    = (spool.PesoFabricacao * detalhe.AvancoSpoolVAFab) * eap.AvancoSpoolVAFab;
                detalhe.PesoSpoolSoldFab  = (spool.PesoFabricacao * detalhe.AvancoSpoolSoldFab) * eap.AvancoSpoolSoldaFab;
                detalhe.PesoSpoolENDFab   = (spool.PesoFabricacao * detalhe.AvancoSpoolENDFab) * eap.AvancoSpoolENDFab;

                //Cálculo Montagem
                var AvancarTrechoRetoPosiMont = QtdJuntaMont == 0 && ExecutadoSpoolPosiMont;
                var AvancarTrechoRetoDIMont   = QtdJuntaMont == 0 && ExecutadoSpoolDIMont;

                var LogicAvancoJuntaENDMont  = 0D;
                var LogicAvancoJuntaSoldMont = 0D;
                var LogicAvancoJuntaVAMont   = 0D;
                var LogicAvancoSpoolPosiMont = 0D;

                //Verificar trecho reto
                if (QtdJuntaMont > 0)
                {
                    // Avanço das juntas de VA "NA" quando todas as juntas forem NA com posicionamento
                    if (WdiJuntaVANaMontPrev == WdiJuntaTotalMont && ExecutadoSpoolPosiMont)
                    {
                        AvancoJuntaVAMont = 1;
                    }

                    //Avanço das juntas de VA "NA" quando tiverem juntas NA e AP com posicionamento
                    if (WdiJuntaVANaMontPrev > 0 && WdiJuntaVAApMontPrev > 0 && ExecutadoSpoolPosiMont)
                    {
                        AvancoJuntaVAMont = Utils.CalculoPercentual(WdiJuntaVANaMontPrev + WdiJuntaVAApMontExec, WdiJuntaTotalMont);
                        //AvancoJuntaVAMont = WdiJuntaVANaMontPrev + WdiJuntaVAApMontExec;
                    }



                    LogicAvancoJuntaENDMont = AvancoJuntaENDMont;

                    LogicAvancoJuntaSoldMont = LogicAvancoJuntaENDMont > AvancoJuntaSoldMont
                        ? LogicAvancoJuntaENDMont
                        : AvancoJuntaSoldMont;

                    LogicAvancoJuntaVAMont = LogicAvancoJuntaSoldMont > AvancoJuntaVAMont
                        ? LogicAvancoJuntaSoldMont
                        : AvancoJuntaVAMont;

                    LogicAvancoSpoolPosiMont = LogicAvancoJuntaVAMont > (ExecutadoSpoolPosiMont ? 1 : 0)
                        ? LogicAvancoJuntaVAMont
                        : (ExecutadoSpoolPosiMont ? 1 : 0);
                }
                else
                {
                    if (AvancarTrechoRetoPosiMont)
                    {
                        LogicAvancoSpoolPosiMont = 1;
                        LogicAvancoJuntaVAMont   = 1;
                    }

                    if (AvancarTrechoRetoDIMont)
                    {
                        LogicAvancoSpoolPosiMont = 1;
                        LogicAvancoJuntaVAMont   = 1;
                        LogicAvancoJuntaSoldMont = 1;
                        LogicAvancoJuntaENDMont  = 1;
                    }
                }


                //Gravar Avanço de Montagem
                detalhe.AvancoSpoolPosiMont      = LogicAvancoSpoolPosiMont;
                detalhe.AvancoJuntaVAMont        = LogicAvancoJuntaVAMont;
                detalhe.AvancoJuntaSoldMont      = LogicAvancoJuntaSoldMont;
                detalhe.AvancoJuntaENDMont       = LogicAvancoJuntaENDMont;
                detalhe.AvancoSpoolLineCheckMont = ExecutadoSpoolLineCheckMont ? 1 : 0;

                //Aplicar EAP no Avanço de Montagem
                detalhe.PesoSpoolPosiMont      = (spool.PesoMontagem * detalhe.AvancoSpoolPosiMont) * eap.AvancoSpoolPosicionamento;
                detalhe.PesoJuntaVAMont        = (spool.PesoMontagem * detalhe.AvancoJuntaVAMont) * eap.AvancoJuntaVAMont;
                detalhe.PesoJuntaSoldMont      = (spool.PesoMontagem * detalhe.AvancoJuntaSoldMont) * eap.AvancoJuntaSoldMont;
                detalhe.PesoJuntaENDMont       = (spool.PesoMontagem * detalhe.AvancoJuntaENDMont) * eap.AvancoJuntaENDMont;
                detalhe.PesoSpoolLineCheckMont = (spool.PesoMontagem * detalhe.AvancoSpoolLineCheckMont) * eap.AvancoSpoolLineCheck;
                detalhe.MedicaoAnterior        = detalheMedicaoAnterior;

                detalhe.Save();

                if (i % 1000 == 0)
                {
                    try
                    {
                        uow.CommitTransaction();
                    }
                    catch
                    {
                        uow.RollbackTransaction();
                        throw new Exception("Process aborted by system");
                    }
                }

                progress.Report(new ImportProgressReport
                {
                    TotalRows     = QuantidadeDeSpool,
                    CurrentRow    = i,
                    MessageImport = $"Fechando Spools: {i}/{QuantidadeDeSpool}"
                });
            }

            progress.Report(new ImportProgressReport
            {
                TotalRows     = QuantidadeDeSpool,
                CurrentRow    = QuantidadeDeSpool,
                MessageImport = $"Gravando Alterações no Banco"
            });

            uow.CommitTransaction();
            uow.PurgeDeletedObjects();
            uow.CommitChanges();
            uow.Dispose();
        }
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            ImmediatePostDataDemo johnNilsen = ObjectSpace.FindObject <ImmediatePostDataDemo>(CriteriaOperator.Parse("LastName == ?", "Nilsen"));

            if (johnNilsen == null)
            {
                johnNilsen                 = ObjectSpace.CreateObject <ImmediatePostDataDemo>();
                johnNilsen.LastName        = "Nilsen";
                johnNilsen.FirstName       = "John";
                johnNilsen.BooleanProperty = true;
                johnNilsen.NumericProperty = 12;
            }
            ImmediatePostDataDemo maryTellitson = ObjectSpace.FindObject <ImmediatePostDataDemo>(CriteriaOperator.Parse("LastName == ?", "Tellitson"));

            if (maryTellitson == null)
            {
                maryTellitson                 = ObjectSpace.CreateObject <ImmediatePostDataDemo>();
                maryTellitson.LastName        = "Tellitson";
                maryTellitson.FirstName       = "Mary";
                maryTellitson.BooleanProperty = false;
                maryTellitson.NumericProperty = 15;
            }
            SimpleDemo simpleDemoObj = ObjectSpace.FindObject <SimpleDemo>(CriteriaOperator.Parse("Name == ?", "SimpleDemoObject1"));

            if (simpleDemoObj == null)
            {
                for (int i = 1; i < 5; i++)
                {
                    SimpleData simpleData = ObjectSpace.CreateObject <SimpleData>();
                    simpleData.Name    = $"SimpleData{i}";
                    simpleDemoObj      = ObjectSpace.CreateObject <SimpleDemo>();
                    simpleDemoObj.Name = $"SimpleDemoObject{i}";
                    simpleDemoObj.Data = simpleData;
                }
            }
            BusinessObjects.Country c = ObjectSpace.FindObject <BusinessObjects.Country>(CriteriaOperator.Parse("Name == ?", "France"));
            if (c == null)
            {
                c      = ObjectSpace.CreateObject <BusinessObjects.Country>();
                c.Name = "France";
                City city = ObjectSpace.CreateObject <City>();
                city.Name = "Paris";
                c.Cities.Add(city);
                city      = ObjectSpace.CreateObject <City>();
                city.Name = "Lyon";
                c.Cities.Add(city);
                city      = ObjectSpace.CreateObject <City>();
                city.Name = "Marseille";
                c.Cities.Add(city);

                c         = ObjectSpace.CreateObject <BusinessObjects.Country>();
                c.Name    = "USA";
                city      = ObjectSpace.CreateObject <City>();
                city.Name = "New York";
                c.Cities.Add(city);
                city      = ObjectSpace.CreateObject <City>();
                city.Name = "Los Angeles";
                c.Cities.Add(city);
                city      = ObjectSpace.CreateObject <City>();
                city.Name = "Seattle";
                c.Cities.Add(city);

                CascadeLookupBatch cascadeLookup = ObjectSpace.CreateObject <CascadeLookupBatch>();
                cascadeLookup.Name    = "Route 1";
                cascadeLookup.Country = c;
                cascadeLookup.City    = city;

                c         = ObjectSpace.CreateObject <BusinessObjects.Country>();
                c.Name    = "Italy";
                city      = ObjectSpace.CreateObject <City>();
                city.Name = "Rome";
                c.Cities.Add(city);
                city      = ObjectSpace.CreateObject <City>();
                city.Name = "Milan";
                c.Cities.Add(city);
                city      = ObjectSpace.CreateObject <City>();
                city.Name = "Venice";
                c.Cities.Add(city);

                cascadeLookup         = ObjectSpace.CreateObject <CascadeLookupBatch>();
                cascadeLookup.Name    = "Route 2";
                cascadeLookup.Country = c;
                cascadeLookup.City    = city;
            }
            ObjectSpace.CommitChanges();

            LargeDataDemo largeDataDemoObject = ObjectSpace.FindObject <LargeDataDemo>(CriteriaOperator.Parse("Name == ?", "LargeDataDemoObject"));

            if (largeDataDemoObject == null)
            {
                for (int i = 1; i < 100000; i++)
                {
                    LargeData obj1 = ObjectSpace.CreateObject <LargeData>();
                    obj1.Name = "LargeData" + i;
                    if (i == 150)
                    {
                        LargeDataDemo largeDataDemo = ObjectSpace.CreateObject <LargeDataDemo>();
                        largeDataDemo.LargeData = obj1;
                        largeDataDemo.Name      = "LargeDataDemoObject";
                    }
                    if (i % 1000 == 0)
                    {
                        ObjectSpace.CommitChanges();
                    }
                }
            }
            ObjectSpace.CommitChanges();
        }
Esempio n. 45
0
        public ETL_Transaction ExtractTransaction(Session session, Guid TransactionId, string AccountCode)
        {
            ETL_Transaction resultTransaction = null;

            try
            {
                bool             Acceptable         = false;
                CriteriaOperator criteria_RowStatus = new BinaryOperator("RowStatus", Constant.ROWSTATUS_ACTIVE, BinaryOperatorType.GreaterOrEqual);
                CriteriaOperator criteria_Code      = new BinaryOperator("Code", AccountCode, BinaryOperatorType.Equal);
                CriteriaOperator criteria           = CriteriaOperator.And(criteria_Code, criteria_RowStatus);
                Account          account            = session.FindObject <Account>(criteria);
                /*2014/02/20 Duc.Vo INS START*/
                Organization defaultOrg       = Organization.GetDefault(session, OrganizationEnum.NAAN_DEFAULT);
                Organization currentDeployOrg = Organization.GetDefault(session, OrganizationEnum.QUASAPHARCO);
                Account      defaultAccount   = Account.GetDefault(session, DefaultAccountEnum.NAAN_DEFAULT);
                /*2014/02/20 Duc.Vo INS END*/
                Transaction transaction = session.GetObjectByKey <Transaction>(TransactionId);
                if (transaction == null)
                {
                    return(resultTransaction);
                }

                Util util = new Util();

                /*2014/02/20 Duc.Vo MOD START*/
                resultTransaction = new ETL_Transaction();
                if (currentDeployOrg != null)
                {
                    resultTransaction.OwnerOrgId = currentDeployOrg.OrganizationId;
                }
                else
                {
                    resultTransaction.OwnerOrgId = defaultOrg.OrganizationId;
                }

                if (transaction is SaleInvoiceTransaction)
                {
                    if ((transaction as SaleInvoiceTransaction).SalesInvoiceId.SourceOrganizationId != null)
                    {
                        resultTransaction.CustomerOrgId = (transaction as SaleInvoiceTransaction).SalesInvoiceId.SourceOrganizationId.OrganizationId;
                    }
                    else
                    {
                        resultTransaction.CustomerOrgId = defaultOrg.OrganizationId;
                    }
                }
                else
                if (transaction is PurchaseInvoiceTransaction)
                {
                    if ((transaction as PurchaseInvoiceTransaction).PurchaseInvoiceId.SourceOrganizationId != null)
                    {
                        resultTransaction.SupplierOrgId = (transaction as PurchaseInvoiceTransaction).PurchaseInvoiceId.SourceOrganizationId.OrganizationId;
                    }
                    else
                    {
                        resultTransaction.SupplierOrgId = defaultOrg.OrganizationId;
                    }
                }
                else
                if (transaction is PaymentVouchesTransaction)
                {
                    PaymentVoucherTransactionBO paymentVoucherTransactionBO = new PaymentVoucherTransactionBO();

                    Organization SuppOrg = paymentVoucherTransactionBO.GetAllocatedSupplier(session, transaction.TransactionId);
                    Organization CustOrg = paymentVoucherTransactionBO.GetAllocatedCustomer(session, transaction.TransactionId);

                    if (SuppOrg != null)
                    {
                        resultTransaction.SupplierOrgId = SuppOrg.OrganizationId;
                    }
                    else
                    {
                        resultTransaction.SupplierOrgId = defaultOrg.OrganizationId;
                    }

                    if (CustOrg != null)
                    {
                        resultTransaction.CustomerOrgId = CustOrg.OrganizationId;
                    }
                    else
                    {
                        resultTransaction.CustomerOrgId = defaultOrg.OrganizationId;
                    }
                }
                else
                if (transaction is ReceiptVouchesTransaction)
                {
                    ReceiptVoucherTransactionBO receiptVoucherTransactionBO = new ReceiptVoucherTransactionBO();
                    Organization SuppOrg = receiptVoucherTransactionBO.GetAllocatedSupplier(session, transaction.TransactionId);
                    Organization CustOrg = receiptVoucherTransactionBO.GetAllocatedCustomer(session, transaction.TransactionId);

                    if (SuppOrg != null)
                    {
                        resultTransaction.SupplierOrgId = SuppOrg.OrganizationId;
                    }
                    else
                    {
                        resultTransaction.SupplierOrgId = defaultOrg.OrganizationId;
                    }

                    if (CustOrg != null)
                    {
                        resultTransaction.CustomerOrgId = CustOrg.OrganizationId;
                    }
                    else
                    {
                        resultTransaction.CustomerOrgId = defaultOrg.OrganizationId;
                    }
                }
                else
                {
                    Organization SuppOrg = GetAllocatedSupplierByManualTransaction(session, transaction.TransactionId);
                    Organization CustOrg = GetAllocatedCustomerByManualTransaction(session, transaction.TransactionId);

                    if (SuppOrg != null)
                    {
                        resultTransaction.SupplierOrgId = SuppOrg.OrganizationId;
                    }
                    else
                    {
                        resultTransaction.SupplierOrgId = defaultOrg.OrganizationId;
                    }

                    if (CustOrg != null)
                    {
                        resultTransaction.CustomerOrgId = CustOrg.OrganizationId;
                    }
                    else
                    {
                        resultTransaction.CustomerOrgId = defaultOrg.OrganizationId;
                    }
                }

                if (resultTransaction.SupplierOrgId == Guid.Empty)
                {
                    resultTransaction.SupplierOrgId = defaultOrg.OrganizationId;
                }

                if (resultTransaction.CustomerOrgId == Guid.Empty)
                {
                    resultTransaction.CustomerOrgId = defaultOrg.OrganizationId;
                }

                /*2014/02/20 Duc.Vo MOD END*/
                resultTransaction.TransactionId      = transaction.TransactionId;
                resultTransaction.Amount             = transaction.Amount;
                resultTransaction.Code               = transaction.Code;
                resultTransaction.CreateDate         = transaction.CreateDate;
                resultTransaction.Description        = transaction.Description;
                resultTransaction.IsBalanceForward   = (transaction is BalanceForwardTransaction);
                resultTransaction.IssuedDate         = transaction.IssueDate;
                resultTransaction.UpdateDate         = transaction.UpdateDate;
                resultTransaction.GeneralJournalList = new List <ETL_GeneralJournal>();
                foreach (GeneralJournal journal in transaction.GeneralJournals.Where(i => i.RowStatus == Constant.ROWSTATUS_BOOKED_ENTRY || i.RowStatus == Constant.ROWSTATUS_ACTIVE))
                {
                    ETL_GeneralJournal tempJournal = new ETL_GeneralJournal();
                    /*2014/02/20 Duc.Vo MOD START*/
                    if (journal.AccountId != null)
                    {
                        tempJournal.AccountId = journal.AccountId.AccountId;
                    }
                    else
                    {
                        tempJournal.AccountId = defaultAccount.AccountId;
                    }
                    /*2014/02/20 Duc.Vo MOD END*/
                    tempJournal.CreateDate = journal.CreateDate;
                    tempJournal.Credit     = journal.Credit;
                    if (journal.CurrencyId == null)
                    {
                        tempJournal.CurrencyId = CurrencyBO.DefaultCurrency(session).CurrencyId;
                    }
                    else
                    {
                        tempJournal.CurrencyId = journal.CurrencyId.CurrencyId;
                    }
                    tempJournal.Debit            = journal.Debit;
                    tempJournal.Description      = journal.Description;
                    tempJournal.GeneralJournalId = journal.GeneralJournalId;
                    tempJournal.JournalType      = journal.JournalType;
                    resultTransaction.GeneralJournalList.Add(tempJournal);
                    if (IsRelateAccount(session, account.AccountId, tempJournal.AccountId))
                    {
                        Acceptable = true;
                    }
                }
                if (!Acceptable)
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(resultTransaction);
        }
 public IHttpActionResult SupplierProduct()
 {
     try
     {
         XpoTypesInfoHelper.GetXpoTypeInfoSource();
         XafTypesInfo.Instance.RegisterEntity(typeof(SupplierProduct));
         XPObjectSpaceProvider        directProvider = new XPObjectSpaceProvider(scc, null);
         IObjectSpace                 ObjectSpace    = directProvider.CreateObjectSpace();
         List <SupplierProduct_Model> list           = new List <SupplierProduct_Model>();
         IList <SupplierProduct>      collection     = ObjectSpace.GetObjects <SupplierProduct>(CriteriaOperator.Parse("GCRecord is null "));
         if (collection.Count > 0)
         {
             foreach (SupplierProduct row in collection)
             {
                 SupplierProduct_Model supplier = new SupplierProduct_Model();
                 supplier.LotNumber          = row.LotNumber;
                 supplier.FinanceYearOid     = row.FinanceYearOid.YearName;
                 supplier.BudgetSourceOid    = row.BudgetSourceOid.BudgetName;
                 supplier.AnimalSeedOid      = row.AnimalSeedOid.SeedName;
                 supplier.AnimalSeedLevelOid = row.AnimalSeedLevelOid.SeedLevelName;
                 supplier.PlotHeaderOid      = row.PlotInfoOidOid.PlotName;
                 supplier.Weight             = Convert.ToDouble(row.Weight);
                 supplier.UnitOid            = row.UnitOid.UnitName;
                 supplier.LastCleansingDate  = row.LastCleansingDate;
                 supplier.Status             = row.Status.ToString();
                 supplier.Used           = row.Used;
                 supplier.ReferanceUsed  = row.ReferanceUsed;
                 supplier.PlotInfoOidOid = row.PlotInfoOidOid.PlotName;
                 supplier.FormType       = row.FormType.ToString();
                 supplier.SeedTypeOid    = row.SeedTypeOid.SeedTypeName;
                 list.Add(supplier);
             }
             return(Ok(list));
         }
         else
         {
             return(BadRequest("NoData"));
         }
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
        //XpoMode
        public TreeViewConfigurationPlaceTable(Window pSourceWindow, XPGuidObject pDefaultValue, CriteriaOperator pXpoCriteria, Type pDialogType, GenericTreeViewMode pGenericTreeViewMode = GenericTreeViewMode.Default, GenericTreeViewNavigatorMode pGenericTreeViewNavigatorMode = GenericTreeViewNavigatorMode.Default)
        {
            //Init Vars
            Type xpoGuidObjectType = typeof(POS_ConfigurationPlaceTable);
            //Override Default Value with Parameter Default Value, this way we can have diferent Default Values for GenericTreeView
            POS_ConfigurationPlaceTable defaultValue = (pDefaultValue != null) ? pDefaultValue as POS_ConfigurationPlaceTable : null;
            //Override Default DialogType with Parameter Dialog Type, this way we can have diferent DialogTypes for GenericTreeView
            Type typeDialogClass = (pDialogType != null) ? pDialogType : typeof(DialogConfigurationPlaceTable);

            //Configure columnProperties
            List <GenericTreeViewColumnProperty> columnProperties = new List <GenericTreeViewColumnProperty>();

            columnProperties.Add(new GenericTreeViewColumnProperty("Code")
            {
                Title = Resx.global_record_code, MinWidth = 100
            });
            columnProperties.Add(new GenericTreeViewColumnProperty("Designation")
            {
                Title = Resx.global_designation, Expand = true
            });
            columnProperties.Add(new GenericTreeViewColumnProperty("Place")
            {
                Title = Resx.global_ConfigurationPlaceTablePlace, ChildName = "Designation", MinWidth = 150
            });
            columnProperties.Add(new GenericTreeViewColumnProperty("UpdatedAt")
            {
                Title = Resx.global_record_date_updated, MinWidth = 150, MaxWidth = 150
            });

            //Configure Criteria/XPCollection/Model
            //CriteriaOperator.Parse("Code >= 100 and Code <= 9999");
            CriteriaOperator criteria      = pXpoCriteria;
            XPCollection     xpoCollection = new XPCollection(GlobalFramework.SessionXpo, xpoGuidObjectType, criteria);

            //Call Base Initializer
            base.InitObject(
                pSourceWindow,                 //Pass parameter
                defaultValue,                  //Pass parameter
                pGenericTreeViewMode,          //Pass parameter
                pGenericTreeViewNavigatorMode, //Pass parameter
                columnProperties,              //Created Here
                xpoCollection,                 //Created Here
                typeDialogClass                //Created Here
                );
        }
 public IHttpActionResult SupplierSend()
 {
     try
     {
         XpoTypesInfoHelper.GetXpoTypeInfoSource();
         XafTypesInfo.Instance.RegisterEntity(typeof(SupplierSend));
         XPObjectSpaceProvider     directProvider = new XPObjectSpaceProvider(scc, null);
         IObjectSpace              ObjectSpace    = directProvider.CreateObjectSpace();
         List <SupplierSend_Model> list           = new List <SupplierSend_Model>();
         IList <SupplierSend>      collection     = ObjectSpace.GetObjects <SupplierSend>(CriteriaOperator.Parse("GCRecord is null "));
         if (collection.Count > 0)
         {
             foreach (SupplierSend row in collection)
             {
                 SupplierSend_Model Model = new SupplierSend_Model();
                 Model.SendNo                 = row.SendNo;
                 Model.CreateDate             = row.CreateDate;
                 Model.FinanceYearOid         = row.FinanceYearOid.YearName;
                 Model.OrganizationSendOid    = row.OrganizationSendOid.OrganizeNameTH;
                 Model.OrganizationReceiveOid = row.OrganizationReceiveOid.OrganizeNameTH;
                 Model.Remark                 = row.Remark;
                 Model.SendStatusOid          = row.SendStatusOid;
                 list.Add(Model);
             }
         }
         else
         {
             return(BadRequest("NoData"));
         }
         return(Ok(list));
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
Esempio n. 49
0
        private void sb_ok_Click(object sender, EventArgs e)
        {
            decimal dec_price = decimal.Zero;
            decimal dec_nums  = decimal.Zero;
            string  s_fa001   = string.Empty;

            if (string.IsNullOrEmpty(te_price.Text))
            {
                te_price.ErrorImageOptions.Alignment = ErrorIconAlignment.MiddleRight;
                te_price.ErrorText = "管理费单价必须输入!";
                return;
            }
            else if (string.IsNullOrEmpty(te_nums.Text))
            {
                te_nums.ErrorImageOptions.Alignment = ErrorIconAlignment.MiddleRight;
                te_nums.ErrorText = "管理费缴费年限必须输入!";
                return;
            }

            dec_price = Convert.ToDecimal(te_price.Text);
            dec_nums  = Convert.ToDecimal(te_nums.Text);
            if (dec_price < 0)
            {
                Tools.msg(MessageBoxIcon.Warning, "提示", "管理费单价必须大于0!");
                te_price.Focus();
                return;
            }
            if (dec_nums <= 0)
            {
                Tools.msg(MessageBoxIcon.Warning, "提示", "缴费年限必须大于0!");
                te_nums.Focus();
                return;
            }
            s_fa001 = MiscAction.GetEntityPK("FA01");
            try
            {
                if (BusinessAction.ManageFee(s_fa001, ac01.AC001, dec_price, dec_nums, Envior.cur_userId, Envior.WORKSTATIONID) > 0)
                {
                    if (XtraMessageBox.Show("缴费成功!\r\n" + "是否现在开具发票?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        sb_ok.Enabled = false;
                        //获取税务客户信息
                        Frm_TaxClientInfo frm_taxClient = new Frm_TaxClientInfo(ac01.AC003);
                        if (frm_taxClient.ShowDialog() != DialogResult.OK)
                        {
                            return;
                        }
                        TaxClientInfo clientInfo = frm_taxClient.swapdata["taxclientinfo"] as TaxClientInfo;

                        CriteriaOperator    criteria          = CriteriaOperator.Parse("FA001='" + s_fa001 + "'");
                        XPCollection <FP01> xpCollection_fp01 = new XPCollection <FP01>(PersistentCriteriaEvaluationBehavior.BeforeTransaction, session1, criteria);
                        foreach (FP01 fp01 in xpCollection_fp01)
                        {
                            if (TaxInvoice.GetNextInvoiceNo() > 0)
                            {
                                if (XtraMessageBox.Show("下一张税票代码:" + Envior.NEXT_BILL_CODE + "\r\n" + "票号:" + Envior.NEXT_BILL_NUM + ",是否继续?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                                {
                                    TaxInvoice.Invoice(fp01.FP001, clientInfo);
                                }
                            }
                        }
                    }
                    //打印缴费记录
                    if (XtraMessageBox.Show("现在打印缴费记录?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        //Tools.msg(MessageBoxIcon.Information, "提示", "现在打印缴费记录!");
                        PrintAction.PrintPayRecord(s_fa001);
                    }

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch (Exception ee)
            {
                Tools.msg(MessageBoxIcon.Error, "错误", "缴费错误!\r\n" + ee.ToString());
            }
        }
Esempio n. 50
0
 public Criterion(string propertyName, object value, CriteriaOperator criteriaOperator)
 {
     _propertyName     = propertyName;
     _value            = value;
     _criteriaOperator = criteriaOperator;
 }
Esempio n. 51
0
        public static IEnumerable <T> GetNodes <T>(this IEnumerable <T> modelNodes, string criteria) where T : IModelNode
        {
            var expressionEvaluator = GetExpressionEvaluator((IModelNode)modelNodes, CriteriaOperator.Parse(criteria));

            return(expressionEvaluator != null?modelNodes.Where(arg => (bool)expressionEvaluator.Evaluate(arg)) : Enumerable.Empty <T>());
        }
Esempio n. 52
0
        //XpoMode
        public TreeViewDocumentOrderTicket(Window pSourceWindow, XPGuidObject pDefaultValue, CriteriaOperator pXpoCriteria, Type pDialogType, GenericTreeViewMode pGenericTreeViewMode = GenericTreeViewMode.Default, GenericTreeViewNavigatorMode pGenericTreeViewNavigatorMode = GenericTreeViewNavigatorMode.Default)
        {
            //Init Vars
            Type xpoGuidObjectType = typeof(FIN_DocumentOrderTicket);
            //Override Default Value with Parameter Default Value, this way we can have diferent Default Values for GenericTreeView
            FIN_DocumentOrderTicket defaultValue = (pDefaultValue != null) ? pDefaultValue as FIN_DocumentOrderTicket : null;
            //Override Default DialogType with Parameter Dialog Type, this way we can have diferent DialogTypes for GenericTreeView
            Type typeDialogClass = (pDialogType != null) ? pDialogType : null;

            //Configure columnProperties
            List <GenericTreeViewColumnProperty> columnProperties = new List <GenericTreeViewColumnProperty>();

            columnProperties.Add(new GenericTreeViewColumnProperty("TicketId")
            {
                Title = Resx.global_ticket_number, MinWidth = 50
            });
            columnProperties.Add(new GenericTreeViewColumnProperty("DateStart")
            {
                Title = Resx.global_date, MinWidth = 100
            });
            columnProperties.Add(new GenericTreeViewColumnProperty("UpdatedBy")
            {
                Title = Resx.global_user_name, ChildName = "Name", MinWidth = 100
            });
            columnProperties.Add(new GenericTreeViewColumnProperty("UpdatedWhere")
            {
                Title = Resx.global_terminal_name, ChildName = "Designation", MinWidth = 100
            });

            //Sort Order
            SortProperty[] sortProperty = new SortProperty[1];
            sortProperty[0] = new SortProperty("TicketId", SortingDirection.Ascending);

            //Configure Criteria/XPCollection/Model
            //CriteriaOperator.Parse("Code >= 100 and Code <= 9999");
            CriteriaOperator criteria      = pXpoCriteria;
            XPCollection     xpoCollection = new XPCollection(GlobalFramework.SessionXpo, xpoGuidObjectType, criteria, sortProperty);

            //Call Base Initializer
            base.InitObject(
                pSourceWindow,                 //Pass parameter
                defaultValue,                  //Pass parameter
                pGenericTreeViewMode,          //Pass parameter
                pGenericTreeViewNavigatorMode, //Pass parameter
                columnProperties,              //Created Here
                xpoCollection,                 //Created Here
                typeDialogClass                //Created Here
                );
        }
Esempio n. 53
0
        private void InitUI(bool useDataDemo)
        {
            //Get Values from Config
            Guid systemCountry;
            Guid systemCurrency;
            //bool debug = false;
            bool useDatabaseDataDemo = Convert.ToBoolean(GlobalFramework.Settings["useDatabaseDataDemo"]);

            if (GlobalFramework.Settings["xpoOidConfigurationCountrySystemCountry"] != string.Empty)
            {
                systemCountry = new Guid(GlobalFramework.Settings["xpoOidConfigurationCountrySystemCountry"]);
            }
            else
            {
                systemCountry = SettingsApp.XpoOidConfigurationCountryPortugal;
            }

            if (GlobalFramework.Settings["xpoOidConfigurationCurrencySystemCurrency"] != string.Empty)
            {
                systemCurrency = new Guid(GlobalFramework.Settings["xpoOidConfigurationCurrencySystemCurrency"]);
            }
            else
            {
                systemCurrency = SettingsApp.XpoOidConfigurationCurrencyEuro;
            }

            //Init Inital Values
            cfg_configurationcountry  intialValueConfigurationCountry  = (cfg_configurationcountry)FrameworkUtils.GetXPGuidObject(typeof(cfg_configurationcountry), systemCountry);
            cfg_configurationcurrency intialValueConfigurationCurrency = (cfg_configurationcurrency)FrameworkUtils.GetXPGuidObject(typeof(cfg_configurationcurrency), systemCurrency);

            try
            {
                //Init dictionary for Parameters + Widgets
                _dictionaryObjectBag = new Dictionary <cfg_configurationpreferenceparameter, EntryBoxValidation>();

                //Pack VBOX
                VBox vbox = new VBox(true, 2)
                {
                    WidthRequest = 300
                };

                //Country
                CriteriaOperator criteriaOperatorSystemCountry = CriteriaOperator.Parse("(Disabled IS NULL OR Disabled  <> 1) AND (RegExFiscalNumber IS NOT NULL)");
                _entryBoxSelectSystemCountry = new XPOEntryBoxSelectRecordValidation <cfg_configurationcountry, TreeViewConfigurationCountry>(this, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_country"), "Designation", "Oid", intialValueConfigurationCountry, criteriaOperatorSystemCountry, SettingsApp.RegexGuid, true);
                _entryBoxSelectSystemCountry.EntryValidation.IsEditable = false;
                _entryBoxSelectSystemCountry.EntryValidation.Validate(_entryBoxSelectSystemCountry.Value.Oid.ToString());
                //Disabled, Now Country and Currency are disabled
                _entryBoxSelectSystemCountry.ButtonSelectValue.Sensitive = true;
                _entryBoxSelectSystemCountry.EntryValidation.Sensitive   = true;
                _entryBoxSelectSystemCountry.ClosePopup += delegate
                {
                    ////Require to Update RegEx
                    _entryBoxZipCode.EntryValidation.Rule = _entryBoxSelectSystemCountry.Value.RegExZipCode;
                    _entryBoxZipCode.EntryValidation.Validate();
                    //Require to Update RegEx and Criteria to filter Country Clients Only
                    _entryBoxFiscalNumber.EntryValidation.Rule = _entryBoxSelectSystemCountry.Value.RegExFiscalNumber;
                    _entryBoxFiscalNumber.EntryValidation.Validate();
                    if (_entryBoxFiscalNumber.EntryValidation.Validated)
                    {
                        bool isValidFiscalNumber = FiscalNumber.IsValidFiscalNumber(_entryBoxFiscalNumber.EntryValidation.Text, _entryBoxSelectSystemCountry.Value.Code2);
                        _entryBoxFiscalNumber.EntryValidation.Validated = isValidFiscalNumber;
                    }
                    //Call Main Validate
                    Validate();
                };

                //Currency
                CriteriaOperator criteriaOperatorSystemCurrency = CriteriaOperator.Parse("(Disabled IS NULL OR Disabled  <> 1)");
                _entryBoxSelectSystemCurrency = new XPOEntryBoxSelectRecordValidation <cfg_configurationcurrency, TreeViewConfigurationCurrency>(this, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_currency"), "Designation", "Oid", intialValueConfigurationCurrency, criteriaOperatorSystemCurrency, SettingsApp.RegexGuid, true);
                _entryBoxSelectSystemCurrency.EntryValidation.IsEditable = false;
                _entryBoxSelectSystemCurrency.EntryValidation.Validate(_entryBoxSelectSystemCurrency.Value.Oid.ToString());

                //Disabled, Now Country and Currency are disabled
                //_entryBoxSelectSystemCurrency.ButtonSelectValue.Sensitive = false;
                //_entryBoxSelectSystemCurrency.EntryValidation.Sensitive = false;
                _entryBoxSelectSystemCurrency.ClosePopup += delegate
                {
                    //Call Main Validate
                    Validate();
                };

                //Add to Vbox
                vbox.PackStart(_entryBoxSelectSystemCountry, true, true, 0);
                vbox.PackStart(_entryBoxSelectSystemCurrency, true, true, 0);

                //Start Render Dynamic Inputs
                CriteriaOperator criteriaOperator = CriteriaOperator.Parse("(Disabled = 0 OR Disabled is NULL) AND (FormType = 1 AND FormPageNo = 1)");
                SortProperty[]   sortProperty     = new SortProperty[2];
                sortProperty[0] = new SortProperty("Ord", SortingDirection.Ascending);
                XPCollection xpCollection = new XPCollection(GlobalFramework.SessionXpo, typeof(cfg_configurationpreferenceparameter), criteriaOperator, sortProperty);
                if (xpCollection.Count > 0)
                {
                    string label    = string.Empty;
                    string regEx    = string.Empty;
                    object regExObj = null;
                    bool   required = false;

                    foreach (cfg_configurationpreferenceparameter item in xpCollection)
                    {
                        label = (item.ResourceString != null && resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], item.ResourceString) != null)
                            ? resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], item.ResourceString)
                            : string.Empty;
                        regExObj = FrameworkUtils.GetFieldValueFromType(typeof(SettingsApp), item.RegEx);
                        regEx    = (regExObj != null) ? regExObj.ToString() : string.Empty;
                        required = Convert.ToBoolean(item.Required);

                        //Override Db Regex
                        if (item.Token == "COMPANY_POSTALCODE")
                        {
                            regEx = _entryBoxSelectSystemCountry.Value.RegExZipCode;
                        }
                        if (item.Token == "COMPANY_FISCALNUMBER")
                        {
                            regEx = _entryBoxSelectSystemCountry.Value.RegExFiscalNumber;
                        }
                        //IN009295 Start POS - Capital Social com valor por defeito
                        if (item.Token == "COMPANY_STOCK_CAPITAL")
                        {
                            item.Value = "1";
                        }
                        //Debug
                        //_log.Debug(string.Format("Label: [{0}], RegEx: [{1}], Required: [{2}]", label, regEx, required));

                        EntryBoxValidation entryBoxValidation = new EntryBoxValidation(
                            this,
                            label,
                            KeyboardMode.AlfaNumeric,
                            regEx,
                            required
                            )
                        {
                            Name = item.Token
                        };

                        //Use demo data to fill values
                        if (useDataDemo)
                        {
                            if (item.Token == "COMPANY_NAME")
                            {
                                entryBoxValidation.EntryValidation.Text = "Acme";
                            }
                            if (item.Token == "COMPANY_BUSINESS_NAME")
                            {
                                entryBoxValidation.EntryValidation.Text = "Technologies, Ltda";
                            }
                            if (item.Token == "COMPANY_ADDRESS")
                            {
                                entryBoxValidation.EntryValidation.Text = "22 Acacia Ave";
                            }
                            if (item.Token == "COMPANY_CITY")
                            {
                                entryBoxValidation.EntryValidation.Text = "Acme City";
                            }
                            if (item.Token == "COMPANY_POSTALCODE")
                            {
                                entryBoxValidation.EntryValidation.Text = "1000-280";
                            }
                            if (item.Token == "COMPANY_COUNTRY")
                            {
                                entryBoxValidation.EntryValidation.Text = "United States";
                            }
                            if (item.Token == "COMPANY_FISCALNUMBER")
                            {
                                entryBoxValidation.EntryValidation.Text = "999999990";
                            }
                            if (item.Token == "COMPANY_STOCK_CAPITAL")
                            {
                                entryBoxValidation.EntryValidation.Text = "1000";
                            }
                            if (item.Token == "COMPANY_EMAIL")
                            {
                                entryBoxValidation.EntryValidation.Text = "*****@*****.**";
                            }
                            if (item.Token == "COMPANY_WEBSITE")
                            {
                                entryBoxValidation.EntryValidation.Text = "www.acme.com";
                            }
                        }

                        //Only Assign Value if Debugger Attached: Now the value for normal user is cleaned in Init Database, we keep this code here, may be usefull
                        //if (Debugger.IsAttached == true || useDatabaseDataDemo && !useDataDemo) { entryBoxValidation.EntryValidation.Text = item.Value; }
                        //if (Debugger.IsAttached == true)
                        //{
                        //    if (debug) _log.Debug(String.Format("[{0}:{1}]:item.Value: [{2}], entryBoxValidation.EntryValidation.Text: [{3}]", Debugger.IsAttached == true, useDatabaseDataDemo, item.Value, entryBoxValidation.EntryValidation.Text));
                        //}

                        //Assign shared Event
                        entryBoxValidation.EntryValidation.Changed += EntryValidation_Changed;

                        //If is ZipCode Assign it to _entryBoxZipCode Reference
                        if (item.Token == "COMPANY_POSTALCODE")
                        {
                            _entryBoxZipCode = entryBoxValidation;
                            _entryBoxZipCode.EntryValidation.Rule = _entryBoxSelectSystemCountry.Value.RegExZipCode;
                        }
                        //If is FiscalNumber Assign it to entryBoxSelectCustomerFiscalNumber Reference
                        else if (item.Token == "COMPANY_FISCALNUMBER")
                        {
                            _entryBoxFiscalNumber = entryBoxValidation;
                            _entryBoxFiscalNumber.EntryValidation.Rule = _entryBoxSelectSystemCountry.Value.RegExFiscalNumber;
                        }

                        if (item.Token == "COMPANY_TAX_ENTITY")
                        {
                            entryBoxValidation.EntryValidation.Text = "Global";
                        }

                        //Call Validate
                        entryBoxValidation.EntryValidation.Validate();
                        //Pack and Add to ObjectBag
                        vbox.PackStart(entryBoxValidation, true, true, 0);
                        _dictionaryObjectBag.Add(item, entryBoxValidation);
                    }
                }

                Viewport viewport = new Viewport()
                {
                    ShadowType = ShadowType.None
                };
                viewport.Add(vbox);

                _scrolledWindow            = new ScrolledWindow();
                _scrolledWindow.ShadowType = ShadowType.EtchedIn;
                _scrolledWindow.SetPolicy(PolicyType.Automatic, PolicyType.Automatic);
                _scrolledWindow.Add(viewport);

                viewport.ResizeMode        = ResizeMode.Parent;
                _scrolledWindow.ResizeMode = ResizeMode.Parent;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }
        }
        private void ShowInPlaceReportAction_Execute(object sender, SingleChoiceActionExecuteEventArgs e)
        {
            if (checkObjectType())
            {
                IList <int> oids       = new List <int>();
                string      reportname = e.SelectedChoiceActionItem.Data.ToString();

                if (typeof(ClassDocument).IsAssignableFrom(View.ObjectTypeInfo.Type))
                {
                    if (View is ListView)
                    {
                        foreach (ClassDocument dtl in View.SelectedObjects)
                        {
                            oids.Add(dtl.Oid);
                        }
                    }
                    else if (View is DetailView)
                    {
                        oids.Add(((ClassDocument)View.CurrentObject).Oid);
                    }
                }
                else if (typeof(ClassStockTransferDocument).IsAssignableFrom(View.ObjectTypeInfo.Type))
                {
                    if (View is ListView)
                    {
                        foreach (ClassStockTransferDocument dtl in View.SelectedObjects)
                        {
                            oids.Add(dtl.Oid);
                        }
                    }
                    else if (View is DetailView)
                    {
                        oids.Add(((ClassStockTransferDocument)View.CurrentObject).Oid);
                    }
                }

                if (oids.Count > 0)
                {
                    string temp = "";
                    foreach (int dtl in oids)
                    {
                        if (temp == "")
                        {
                            temp = dtl.ToString();
                        }
                        else
                        {
                            temp += "," + dtl.ToString();
                        }
                    }
                    IObjectSpace  objectSpace = ReportDataProvider.ReportObjectSpaceProvider.CreateObjectSpace(typeof(ReportDataV2));
                    IReportDataV2 reportData  = objectSpace.FindObject <ReportDataV2>(CriteriaOperator.Parse("[DisplayName] = '" + reportname + "'"));
                    objectSpace.Dispose();
                    string handle = ReportDataProvider.ReportsStorage.GetReportContainerHandle(reportData);
                    Frame.GetController <ReportServiceController>().ShowPreview(handle, CriteriaOperator.Parse("Oid in (" + temp + ")"));
                }
            }
        }
Esempio n. 55
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            UpdateAnalysisCriteriaColumn();

            // PermissionPolicyRole defaultRole = CreateDefaultRole();

            UpdateStatus("CreateContacts", "", "Creating contacts, departments and positions in the database...");

            ObjectSpace.CommitChanges();
            try {
                CreateDepartments();
                CreateContacts();
            }
            catch (Exception e) {
                Tracing.Tracer.LogText("Cannot initialize contacts, departments and positions from the XML file.");
                Tracing.Tracer.LogError(e);
            }
            InitContactsLocation();


            UpdateStatus("CreatePayments", "", "Creating payments, resumes and scheduler events in the database...");
            IList <Contact> topTenContacts = ObjectSpace.GetObjects <Contact>();

            ObjectSpace.SetCollectionSorting(topTenContacts, new SortProperty[] { new SortProperty("LastName", DevExpress.Xpo.DB.SortingDirection.Ascending) });
            ObjectSpace.SetTopReturnedObjectsCount(topTenContacts, 10);
            string[] notes =
            {
                "works with customers until their problems are resolved and often goes an extra step to help upset customers be completely surprised by how far we will go to satisfy customers",
                "is very good at making team members feel included. The inclusion has improved the team's productivity dramatically",
                "is very good at sharing knowledge and information during a problem to increase the chance it will be resolved quickly",
                "actively elicits feedback from customers and works to resolve their problems",
                "creates an inclusive work environment where everyone feels they are a part of the team",
                "consistently keeps up on new trends in the industry and applies these new practices to every day work",
                "is clearly not a short term thinker - the ability to set short and long term business goals is a great asset to the company",
                "seems to want to achieve all of the goals in the last few weeks before annual performance review time, but does not consistently work towards the goals throughout the year",
                "does not yet delegate effectively and has a tendency to be overloaded with tasks which should be handed off to subordinates",
                "to be discussed with the top management..."
            };
            for (int i = 0; i < topTenContacts.Count; i++)
            {
                Contact contact = topTenContacts[i];
                if (ObjectSpace.FindObject <Paycheck>(CriteriaOperator.Parse("Contact=?", contact)) == null)
                {
                    PayrollSampleDataGenerator.GenerateContactPaychecks(ObjectSpace, contact);
                    ObjectSpace.CommitChanges();
                }
                Resume resume = ObjectSpace.FindObject <Resume>(CriteriaOperator.Parse("Contact=?", contact));
                if (resume == null)
                {
                    resume = ObjectSpace.CreateObject <Resume>();
                    FileData file = ObjectSpace.CreateObject <FileData>();
                    try {
                        Stream stream = FindContactResume(contact);
                        if (stream != null)
                        {
                            file.LoadFromStream(string.Format("{0}.pdf", contact.FullName), stream);
                        }
                    }
                    catch (Exception e) {
                        Tracing.Tracer.LogText("Cannot initialize FileData for the contact {0}.", contact.FullName);
                        Tracing.Tracer.LogError(e);
                    }
                    resume.File    = file;
                    resume.Contact = contact;
                }
                Contact reviewerContact = i < 5 ? FindTellitson() : FindJanete();
                Note    note            = ObjectSpace.FindObject <Note>(CriteriaOperator.Parse("Contains(Text, ?)", contact.FullName));
                if (note == null)
                {
                    note          = ObjectSpace.CreateObject <Note>();
                    note.Author   = reviewerContact.FullName;
                    note.Text     = string.Format("<span style='color:#000000;font-family:Tahoma;font-size:8pt;'><b>{0}</b> \r\n{1}</span>", contact.FullName, notes[i]);
                    note.DateTime = DateTime.Now.AddDays(i * (-1));
                }
#if !EASYTEST
                Event appointment = ObjectSpace.FindObject <Event>(CriteriaOperator.Parse("Contains(Subject, ?)", contact.FullName));
                if (appointment == null)
                {
                    appointment             = ObjectSpace.CreateObject <Event>();
                    appointment.Subject     = string.Format("{0} - performance review", contact.FullName);
                    appointment.Description = string.Format("{0} \r\n{1}", contact.FullName, notes[i]);
                    appointment.StartOn     = note.DateTime.AddDays(5).AddHours(12);
                    appointment.EndOn       = appointment.StartOn.AddHours(2);
                    appointment.Location    = "101";
                    appointment.AllDay      = false;
                    appointment.Status      = 0;
                    appointment.Label       = i % 2 == 0 ? 2 : 5;
                    Resource reviewerContactResource = ObjectSpace.FindObject <Resource>(CriteriaOperator.Parse("Contains(Caption, ?)", reviewerContact.FullName));
                    if (reviewerContactResource == null)
                    {
                        reviewerContactResource         = ObjectSpace.CreateObject <Resource>();
                        reviewerContactResource.Caption = reviewerContact.FullName;
                        reviewerContactResource.Color   = reviewerContact == FindTellitson() ? Color.AliceBlue : Color.LightCoral;
                    }
                    appointment.Resources.Add(reviewerContactResource);
                }
#endif
            }

            ObjectSpace.CommitChanges();

            UpdateStatus("CreateTasks", "", "Creating demo tasks in the database...");

#if EASYTEST
            Contact contactMary = FindTellitson();
            Contact contactJohn = FindContact("John", "Nilsen");
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Review reports'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject            = "Review reports";
                task.AssignedTo         = contactJohn;
                task.StartDate          = DateTime.Parse("May 03, 2008");
                task.DueDate            = DateTime.Parse("September 06, 2008");
                task.Status             = DevExpress.Persistent.Base.General.TaskStatus.InProgress;
                task.Priority           = Priority.High;
                task.EstimatedWorkHours = 60;
                task.Description        = "Analyse the reports and assign new tasks to employees.";
            }

            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Fix breakfast'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject            = "Fix breakfast";
                task.AssignedTo         = contactMary;
                task.StartDate          = DateTime.Parse("May 03, 2008");
                task.DueDate            = DateTime.Parse("May 04, 2008");
                task.Status             = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority           = Priority.Low;
                task.EstimatedWorkHours = 1;
                task.ActualWorkHours    = 3;
                task.Description        = "The Development Department - by 9 a.m.\r\nThe R&QA Department - by 10 a.m.";
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task1'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject            = "Task1";
                task.AssignedTo         = contactJohn;
                task.StartDate          = DateTime.Parse("June 03, 2008");
                task.DueDate            = DateTime.Parse("June 06, 2008");
                task.Status             = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority           = Priority.High;
                task.EstimatedWorkHours = 10;
                task.ActualWorkHours    = 15;
                task.Description        = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task2'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject            = "Task2";
                task.AssignedTo         = contactJohn;
                task.StartDate          = DateTime.Parse("July 03, 2008");
                task.DueDate            = DateTime.Parse("July 06, 2008");
                task.Status             = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority           = Priority.Low;
                task.EstimatedWorkHours = 8;
                task.ActualWorkHours    = 16;
                task.Description        = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
            }
#endif
#if !EASYTEST
            IList <Contact>  contacts = ObjectSpace.GetObjects <Contact>();
            IList <DemoTask> taskList = GenerateTask(contacts);
            if (taskList.Count > 0)
            {
                Random rndGenerator = new Random();
                foreach (Contact contact in contacts)
                {
                    if (taskList.Count == 1)
                    {
                        contact.Tasks.Add(taskList[0]);
                    }
                    else if (taskList.Count == 2)
                    {
                        contact.Tasks.Add(taskList[0]);
                        contact.Tasks.Add(taskList[1]);
                    }
                    else
                    {
                        int index = rndGenerator.Next(1, taskList.Count - 2);
                        contact.Tasks.Add(taskList[index]);
                        contact.Tasks.Add(taskList[index - 1]);
                        contact.Tasks.Add(taskList[index + 1]);
                    }
                }
            }
#endif
            UpdateStatus("CreateAnalysis", "", "Creating analysis reports in the database...");
            CreateDataToBeAnalysed();
            UpdateStatus("CreateSecurityData", "", "Creating users and roles in the database...");
            #region Create a User for the Simple Security Strategy
            //// If a simple user named 'Sam' doesn't exist in the database, create this simple user
            //SecuritySimpleUser adminUser = ObjectSpace.FindObject<SecuritySimpleUser>(new BinaryOperator("UserName", "Sam"));
            //if(adminUser == null) {
            //    adminUser = ObjectSpace.CreateObject<SecuritySimpleUser>();
            //    adminUser.UserName = "******";
            //}
            //// Make the user an administrator
            //adminUser.IsAdministrator = true;
            //// Set a password if the standard authentication type is used
            //adminUser.SetPassword("");
            #endregion

            #region Create Users for the Complex Security Strategy
            // If a user named 'Sam' doesn't exist in the database, create this user
            PermissionPolicyUser user1 = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "Sam"));
            if (user1 == null)
            {
                user1          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                user1.UserName = "******";
                // Set a password if the standard authentication type is used
                user1.SetPassword("");
            }
            // If a user named 'John' doesn't exist in the database, create this user
            PermissionPolicyUser user2 = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "John"));
            if (user2 == null)
            {
                user2          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                user2.UserName = "******";
                // Set a password if the standard authentication type is used
                user2.SetPassword("");
            }
            // If a role with the Administrators name doesn't exist in the database, create this role
            PermissionPolicyRole adminRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Administrators"));
            if (adminRole == null)
            {
                adminRole      = ObjectSpace.CreateObject <PermissionPolicyRole>();
                adminRole.Name = "Administrators";
            }
            adminRole.IsAdministrative = true;

            // If a role with the Users name doesn't exist in the database, create this role
            PermissionPolicyRole userRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Users"));
            if (userRole == null)
            {
                userRole                  = ObjectSpace.CreateObject <PermissionPolicyRole>();
                userRole.Name             = "Users";
                userRole.PermissionPolicy = SecurityPermissionPolicy.AllowAllByDefault;
                userRole.AddNavigationPermission("Application/NavigationItems/Items/Default/Items/PermissionPolicyRole_ListView", SecurityPermissionState.Deny);
                userRole.AddNavigationPermission("Application/NavigationItems/Items/Default/Items/PermissionPolicyUser_ListView", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyRole>(SecurityOperations.FullAccess, SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyUser>(SecurityOperations.FullAccess, SecurityPermissionState.Deny);
                userRole.AddObjectPermission <PermissionPolicyUser>(SecurityOperations.ReadOnlyAccess, "[Oid] = CurrentUserId()", SecurityPermissionState.Allow);
                userRole.AddMemberPermission <PermissionPolicyUser>(SecurityOperations.Write, "ChangePasswordOnFirstLogon", null, SecurityPermissionState.Allow);
                userRole.AddMemberPermission <PermissionPolicyUser>(SecurityOperations.Write, "StoredPassword", null, SecurityPermissionState.Allow);
                userRole.AddTypePermission <PermissionPolicyRole>(SecurityOperations.Read, SecurityPermissionState.Allow);
                userRole.AddTypePermission <PermissionPolicyTypePermissionObject>("Write;Delete;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyMemberPermissionsObject>("Write;Delete;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyObjectPermissionsObject>("Write;Delete;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyNavigationPermissionObject>("Write;Delete;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyActionPermissionObject>("Write;Delete;Create", SecurityPermissionState.Deny);
            }

            // Add the Administrators role to the user1
            user1.Roles.Add(adminRole);
            // Add the Users role to the user2
            user2.Roles.Add(userRole);
            #endregion

            ObjectSpace.CommitChanges();
        }
        protected override void OnActivated()
        {
            base.OnActivated();
            // Perform various tasks depending on the target View.
            PrintSelectionBaseController PrintSelectionController = Frame.GetController <PrintSelectionBaseController>();

            if (PrintSelectionController != null && PrintSelectionController.Actions.Count > 0)
            {
                if (PrintSelectionController.Actions["ShowInReportV2"] != null)
                {
                    if (checkObjectType())
                    {
                        PrintSelectionController.Actions["ShowInReportV2"].Active.SetItemValue("EnableAction", false);
                    }
                    //PrintSelectionController.Actions["ShowInReportV2"].Executing += FilterCopyFromController_Executing;
                }
            }

            ShowInPlaceReportAction.Items.Clear();
            if (checkObjectType())
            {
                bool             found = false;
                SystemUsers      user  = (SystemUsers)SecuritySystem.CurrentUser;
                ChoiceActionItem setStatusItem;
                foreach (FilteringCriterion criterion in ObjectSpace.GetObjects <FilteringCriterion>())
                {
                    if (criterion.ObjectType == typeof(ReportDataV2))
                    {
                        if (criterion.Roles.Count > 0)
                        {
                            foreach (ReportDataV2 rpt in ObjectSpace.GetObjects <ReportDataV2>(CriteriaOperator.Parse(criterion.Criterion)))
                            {
                                if (rpt.DataTypeName == View.ObjectTypeInfo.Type.ToString())
                                {
                                    //if (criterion.Criterion.Contains("DataTypeCaption"))
                                    //{
                                    found = true;

                                    foreach (IPermissionPolicyRole role in user.Roles)
                                    {
                                        if (criterion.Roles.Where(p => p.FilterRole.Name == role.Name).Count() > 0)
                                        {
                                            if (rpt.IsInplaceReport)
                                            {
                                                if (ShowInPlaceReportAction.Items.FindItemByID(rpt.DisplayName) == null)
                                                {
                                                    setStatusItem = new ChoiceActionItem(rpt.DisplayName, rpt.DisplayName);
                                                    ShowInPlaceReportAction.Items.Add(setStatusItem);
                                                }
                                            }
                                        }
                                    }
                                    //}
                                }
                            }
                        }
                        else
                        {
                            foreach (ReportDataV2 rpt in ObjectSpace.GetObjects <ReportDataV2>(CriteriaOperator.Parse(criterion.Criterion)))
                            {
                                if (rpt.DataTypeName == View.ObjectTypeInfo.Type.ToString())
                                {
                                    //if (criterion.Criterion.Contains("DataTypeCaption"))
                                    //{
                                    found = true;

                                    if (rpt.IsInplaceReport)
                                    {
                                        if (ShowInPlaceReportAction.Items.FindItemByID(rpt.DisplayName) == null)
                                        {
                                            if (ShowInPlaceReportAction.Items.FindItemByID(rpt.DisplayName) == null)
                                            {
                                                setStatusItem = new ChoiceActionItem(rpt.DisplayName, rpt.DisplayName);
                                                ShowInPlaceReportAction.Items.Add(setStatusItem);
                                            }
                                        }
                                    }
                                    //}
                                }
                            }
                        }
                    }
                }
                if (!found)
                {
                    foreach (ReportDataV2 rpt in ObjectSpace.GetObjects <ReportDataV2>())
                    {
                        if (rpt.DataTypeName == View.ObjectTypeInfo.Type.ToString() && rpt.IsInplaceReport)
                        {
                            if (ShowInPlaceReportAction.Items.FindItemByID(rpt.DisplayName) == null)
                            {
                                ShowInPlaceReportAction.Items.Add(new ChoiceActionItem(rpt.DisplayName, rpt.DisplayName));
                            }
                        }
                    }
                }

                if (View.GetType() == typeof(DetailView))
                {
                    this.ShowInPlaceReportAction.Active.SetItemValue("Enabled", ((DetailView)View).ViewEditMode == ViewEditMode.View);
                    ((DetailView)View).ViewEditModeChanged += MyCustomInplaceReportController_ViewEditModeChanged;
                }
            }
        }
Esempio n. 57
0
 private Position FindPosition(string positionTitle) => ObjectSpace.FindObject <Position>(CriteriaOperator.Parse("Title=?", positionTitle), true);
Esempio n. 58
0
        public static List <GraficoRitmoTimeDTO> CalcularGraficoRitmoTimeProjeto(Guid oidProjeto, Session session)
        {
            List <GraficoRitmoTimeDTO> lista = new List <GraficoRitmoTimeDTO>();

            using (XPCollection <CicloDesenv> ciclos = new XPCollection <CicloDesenv>(session, CriteriaOperator.
                                                                                      Parse("Projeto.Oid = ?", oidProjeto)))
            {
                ciclos.Sorting.Add(new SortProperty("NbCiclo", SortingDirection.Ascending));
                int cicloInicioTendencia = 0;
                foreach (CicloDesenv ciclo in ciclos)
                {
                    if (ciclo.CsSituacaoCiclo.Equals(CsSituacaoCicloDomain.Concluido) ||
                        ciclo.CsSituacaoCiclo.Equals(CsSituacaoCicloDomain.Cancelado))
                    {
                        lista.Add(new GraficoRitmoTimeDTO()
                        {
                            Ciclo     = ciclo.NbCiclo,
                            Ritmo     = ciclo.NbPontosRealizados,
                            Planejado = ciclo.NbPontosPlanejados,
                            Meta      = ciclo.GetPontosMeta()
                        });
                    }
                    else
                    {
                        lista.Add(new GraficoRitmoTimeDTO()
                        {
                            Ciclo     = ciclo.NbCiclo,
                            Ritmo     = 0,
                            Planejado = ciclo.NbPontosPlanejados,
                            Meta      = ciclo.GetPontosMeta()
                        });
                    }
                    if (ciclo.CsSituacaoCiclo.Equals(CsSituacaoCicloDomain.Concluido) ||
                        ciclo.CsSituacaoCiclo.Equals(CsSituacaoCicloDomain.Cancelado))
                    {
                        cicloInicioTendencia = ciclo.NbCiclo;
                    }
                }

                Boolean addNull = false;
                if (cicloInicioTendencia == 0)
                {
                    addNull = true;
                }
                foreach (GraficoRitmoTimeDTO item in lista)
                {
                    if (addNull)
                    {
                        item.Ritmo     = null;
                        item.Planejado = null;
                        item.Meta      = null;
                    }
                    if (item.Ciclo.Equals(cicloInicioTendencia))
                    {
                        addNull = true;
                    }
                }
            }

            return(lista);
        }
Esempio n. 59
0
        public IHttpActionResult ManageAnimalSupplier()
        {
            try
            {
                string OrganizationOid = HttpContext.Current.Request.Form["OrganizationOid"].ToString();
                string FinanceYearOid  = HttpContext.Current.Request.Form["FinanceYearOid"].ToString();
                XpoTypesInfoHelper.GetXpoTypeInfoSource();
                XafTypesInfo.Instance.RegisterEntity(typeof(ManageAnimalSupplier));
                List <ManageAnimalSupplier_Model> list_detail    = new List <ManageAnimalSupplier_Model>();
                XPObjectSpaceProvider             directProvider = new XPObjectSpaceProvider(scc, null);
                IObjectSpace ObjectSpace = directProvider.CreateObjectSpace();
                IList <ManageAnimalSupplier> collection = ObjectSpace.GetObjects <ManageAnimalSupplier>(CriteriaOperator.Parse(" GCRecord is null and Status = 1 and OrganizationOid=? and FinanceYearOid = ?", OrganizationOid, FinanceYearOid));

                //ManageAnimalSupplier ObjMaster;
                //ObjMaster = ObjectSpace.FindObject<ManageAnimalSupplier>(CriteriaOperator.Parse("GCRecord is null and StockType = 1 and OrganizationOid =? and FinanceYearOid = ? ", OrganizationOid, FinanceYearOid));
                foreach (ManageAnimalSupplier row in collection)
                {
                    ManageAnimalSupplier_Model Model = new ManageAnimalSupplier_Model();
                    Model.Oid              = row.Oid.ToString();
                    Model.FinanceYearOid   = row.FinanceYearOid.Oid.ToString();
                    Model.FinanceYear      = row.FinanceYearOid.YearName;
                    Model.OrgZoneOid       = row.OrgZoneOid.Oid.ToString();
                    Model.OrgZone          = row.OrgZoneOid.OrganizeNameTH;
                    Model.OrganizationOid  = row.OrganizationOid.Oid.ToString();
                    Model.Organization     = row.OrganizationOid.SubOrganizeName;
                    Model.AnimalSupplieOid = row.AnimalSupplieOid.Oid.ToString();
                    Model.AnimalSupplie    = row.AnimalSupplieOid.AnimalSupplieName;
                    Model.ZoneQTY          = row.ZoneQTY;
                    Model.CenterQTY        = row.CenterQTY;
                    Model.OfficeQTY        = row.OfficeQTY;
                    Model.OfficeGAPQTY     = row.OfficeGAPQTY;
                    Model.OfficeBeanQTY    = row.OfficeBeanQTY;
                    Model.Status           = row.Status.ToString();
                    Model.SortID           = row.SortID;
                    list_detail.Add(Model);
                }

                return(Ok(true));
            }
            catch (Exception ex)
            {                      //Error case เกิดข้อผิดพลาด
                UserError err = new UserError();
                err.code    = "6"; // error จากสาเหตุอื่นๆ จะมีรายละเอียดจาก system แจ้งกลับ
                err.message = ex.Message;
                //  Return resual
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 60
0
 private void SetFilterCriteriaForGrid(CriteriaOperator criteria)
 {
     // todo: [ivan] implement filters for web
     //m_PivotView.PivotGridView.Criteria = criteria;
 }