Example #1
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);
            }
        }
Example #2
0
 public virtual void Visit(BinaryOperator node)
 {
     if (node != null)
     {
          AcceptChildren(node);
     }
 }
 public void Visit(BinaryOperator op)
 {
     op.LeftOperand.Accept(this);
     _resultBuilder.Append(" ");
     op.RightOperand.Accept(this);
     _resultBuilder.Append("binary");
 }
Example #4
0
        // ||, &&, ==, !=
        // +, -, *, /, %

        public BinaryExpression(CssValue left, BinaryOperator op, CssValue right)
            : base(NodeKind.Expression)
        {
            Left = left;
            Operator = op;
            Right = right;
        }
 public BinaryExpression(BinaryOperator @operator, Expression left, Expression right,
     TypeReference expressionType, TypeSystem typeSystem, IEnumerable<Instruction> instructions, bool isOverridenOperation = false)
     : this(@operator, left, right, DetermineIsChecked(instructions), instructions, isOverridenOperation)
 {
     this.ExpressionType = expressionType;
     this.typeSystem = typeSystem;
 }
 public static CriteriaOperator GetCriteria(Type serializationConfigurationType, ISerializationConfigurationGroup serializationConfigurationGroup)
 {
     const ISerializationConfiguration serializationConfiguration = null;
     var groupOperator = new BinaryOperator(serializationConfiguration.GetPropertyName(x => x.SerializationConfigurationGroup),serializationConfigurationGroup);
     return new GroupOperator(new BinaryOperator(serializationConfiguration.GetPropertyName(x => x.TypeToSerialize),
                               serializationConfigurationType), groupOperator);
 }
        public static IExpressionGraph TypeOperation(IExpressionGraph myLeftValueObject, IExpressionGraph myRightValueObject, BinaryOperator myOperator)
        {
            switch (myOperator)
            {
                case BinaryOperator.AND:
                    myLeftValueObject.IntersectWith(myRightValueObject);

                    break;
                case BinaryOperator.OR:
                    
                    myLeftValueObject.UnionWith(myRightValueObject);

                    break;
                case BinaryOperator.Equals:
                case BinaryOperator.GreaterOrEqualsThan:
                case BinaryOperator.GreaterThan:
                case BinaryOperator.InRange:
                case BinaryOperator.LessOrEqualsThan:
                case BinaryOperator.LessThan:
                case BinaryOperator.NotEquals:
                default:
                    throw new ArgumentOutOfRangeException("myOperator");
            }

            return myLeftValueObject;
        }
 object ICriteriaVisitor.Visit(BinaryOperator theOperator){
     var propertyName = ((OperandProperty) theOperator.LeftOperand).PropertyName;
     if (_dictionary.ContainsKey(propertyName)){
         ((OperandValue) theOperator.RightOperand).Value = _dictionary[propertyName];
     }
     return theOperator;
 }
 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;
 }
Example #10
0
 public static ICodeTemplate FindDefaultTemplate(TemplateType templateType, Session session, Type codeTemplateType, CodeDomProvider codeDomProvider){
     const ICodeTemplate template = null;
     var binaryOperator = new BinaryOperator(template.GetPropertyName(x => x.TemplateType),templateType);
     var isDefault = new BinaryOperator(template.GetPropertyName(x => x.IsDefault),true);
     var provider = new BinaryOperator(template.GetPropertyName(x => x.CodeDomProvider),codeDomProvider);
     return session.FindObject(PersistentCriteriaEvaluationBehavior.InTransaction,
                               codeTemplateType, new GroupOperator(binaryOperator, isDefault,provider))
            as ICodeTemplate;
 }
        public static IPersistentClassInfo Find(Session session, string referenceTypeFullName)
        {
            const IPersistentClassInfo persistentClassInfo = null;
            string propertyName = persistentClassInfo.GetPropertyName(x => x.PersistentAssemblyInfo) + "." + persistentClassInfo.GetPropertyName(x => x.PersistentAssemblyInfo.Name);
            var binaryOperator = new BinaryOperator(propertyName, referenceTypeFullName.Substring(0,referenceTypeFullName.IndexOf(".")));


            var operands = new BinaryOperator(persistentClassInfo.GetPropertyName(x=>x.Name),referenceTypeFullName.Substring(referenceTypeFullName.IndexOf(".")+1));
            return session.FindObject(PersistentCriteriaEvaluationBehavior.InTransaction, WCTypesInfo.Instance.FindBussinessObjectType<IPersistentClassInfo>(), new GroupOperator(binaryOperator, operands)) as IPersistentClassInfo;
        }
 private void FormatBinaryOperator(BinaryOperator op, bool withParenthesis)
 {
     operators.Push(op);
     if (withParenthesis) { _resultBuilder.Append("("); }
     op.LeftOperand.Accept(this);
     _resultBuilder.AppendFormat(op.ToString());
     op.RightOperand.Accept(this);
     if (withParenthesis) { _resultBuilder.Append(")"); }
     operators.Pop();
 }
Example #13
0
		/// <summary>
		///   Initializes a new instance of the <see cref="BinaryFormula" /> class.
		/// </summary>
		/// <param name="leftOperand">The formula on the left-hand side of the binary operator.</param>
		/// <param name="binaryOperator">The operator of the binary formula.</param>
		/// <param name="rightOperand">The formula on the right-hand side of the binary operator.</param>
		internal BinaryFormula(Formula leftOperand, BinaryOperator binaryOperator, Formula rightOperand)
		{
			Requires.NotNull(leftOperand, nameof(leftOperand));
			Requires.InRange(binaryOperator, nameof(binaryOperator));
			Requires.NotNull(rightOperand, nameof(rightOperand));

			LeftOperand = leftOperand;
			Operator = binaryOperator;
			RightOperand = rightOperand;
		}
 object ICriteriaVisitor.Visit(BinaryOperator theOperator) {
     Process(theOperator);
     var leftOperandValue = GetCustomFunctionOperandValue(theOperator.LeftOperand);
     if (!ReferenceEquals(leftOperandValue,null))
         theOperator.LeftOperand=leftOperandValue;
     var rightOperandValue = GetCustomFunctionOperandValue(theOperator.RightOperand);
     if (!ReferenceEquals(rightOperandValue,null))
         theOperator.RightOperand=rightOperandValue;
     return theOperator;
 }
 private BinaryExpression(BinaryOperator @operator, Expression left, Expression right, bool isChecked, IEnumerable<Instruction> instructions, bool isOverridenOperation)
     : base(instructions)
 {
     this.Operator = @operator;
     this.left = left;
     this.right = right;
     this.IsOverridenOperation = isOverridenOperation;
     this.IsChecked = isChecked;
     FixIfNullComparison();
 }
        protected override BinaryExpressionBase<BinaryOperator> Create(Expression left, BinaryOperator op, Expression right)
        {
            if (!(left is AttributeBinaryExpression && right is AttributeBinaryExpression))
            {
                throw new ArgumentException("Both parameter 'left' and parameter 'right' " +
                                            "must be a AttributeBinaryExpression instance.");
            }

            return new AttributesPredicateExpression(left as AttributeBinaryExpression, op, right as AttributeBinaryExpression);
        }
 XPBaseCollection GetAuditTrail(Session session, XPBaseObject xpBaseObject, Type auditedObjectWeakReferenceType) {
     var binaryOperator = new BinaryOperator("TargetType", session.GetObjectType(xpBaseObject));
     var operands = new BinaryOperator("TargetKey", XPWeakReference.KeyToString(session.GetKeyValue(xpBaseObject)));
     var auditObjectWR = (XPWeakReference) session.FindObject(auditedObjectWeakReferenceType,new GroupOperator(binaryOperator,operands));
     if (auditObjectWR != null) {
         var baseCollection = (XPBaseCollection) auditObjectWR.ClassInfo.GetMember("AuditDataItems").GetValue(auditObjectWR);
         baseCollection.BindingBehavior = CollectionBindingBehavior.AllowNone;
         return baseCollection;
     }
     return null;
 }
Example #18
0
        /// <summary>
        /// Creates a new binary expression
        /// </summary>
        /// <param name="myLeftExpression">The left side of the BinaryExpression</param>
        /// <param name="myBinaryOperator">The binary operator</param>
        /// <param name="myRightExpression">The right side of the BinaryExpression</param>
        /// <param name="myExpressionIndex">The index which should be used for the expression</param>
        public BinaryExpression (IExpression myLeftExpression, 
                                    BinaryOperator myBinaryOperator, 
                                    IExpression myRightExpression,
                                    string myExpressionIndex = null)
        {
            Left = myLeftExpression;
            Right = myRightExpression;
            Operator = myBinaryOperator;

            ExpressionIndex = myExpressionIndex;
        }
 public void AssignmentOperators(BinaryOperator @operator, bool space, string expected)
 {
     Test(
         expected,
         Syntax.BinaryExpression(
             @operator,
             Syntax.ParseName("a"),
             Syntax.LiteralExpression(1)
         ),
         p => p.Spaces.AroundOperators.AssignmentOperators = space
     );
 }
Example #20
0
        private void lstBoxApplications_SelectedValueChanged(object sender, EventArgs e)
        {   
                BinaryOperator bOper = new BinaryOperator("Application", lstBoxApplications.SelectedValue);

                //  CriteriaOperator cri = BinaryOperator
                ColumnFilterInfo d = new ColumnFilterInfo(bOper);

                ((ColumnView)gridConfig.Views[0]).Columns[0].FilterInfo = d;

         

        }
 public void Test(string expected, BinaryOperator @operator)
 {
     Test(
         expected,
         new BinaryExpressionSyntax
         {
             Left = new LiteralExpressionSyntax { Value = 1 },
             Right = new LiteralExpressionSyntax { Value = 1 },
             Operator = @operator
         }
     );
 }
 public void BeforeTypeParameterListAngle(BinaryOperator @operator, bool space, string expected)
 {
     Test(
         expected,
         Syntax.BinaryExpression(
             @operator,
             Syntax.ParseName("a"),
             Syntax.LiteralExpression(1)
         ),
         p => p.Spaces.AroundOperators.LogicalOperators = space
     );
 }
Example #23
0
        public object Visit(BinaryOperator theOperator) {
            UpdatePropertyName(theOperator.LeftOperand);

            CriteriaOperator operandValue;

            if (ToValue(theOperator.RightOperand, out operandValue))
                theOperator.RightOperand = operandValue;
            else
                theOperator.RightOperand.Accept(this);

            return theOperator;
        }
Example #24
0
		public BinaryExpression(IExpression leftExpression, BinaryOperator binaryOperator, IExpression rightExpression)
		{
			if ((object)leftExpression == null)
				throw new ArgumentNullException(nameof(leftExpression));

			if ((object)rightExpression == null)
				throw new ArgumentNullException(nameof(rightExpression));

			this.leftExpression = leftExpression;
			this.binaryOperator = binaryOperator;
			this.rightExpression = rightExpression;
		}
 static String getDisplayName(BinaryOperator operator) {
     switch (operator) {
     case Add:
         return "+";
     case And:
         return "&";
     case As:
         return "as";
     case Divide:
         return "/";
     case Equal:
         return "==";
     case GreaterThan:
         return ">";
     case GreaterThanOrEqual:
         return ">=";
     case Instanceof:
         return "instanceof";
     case LeftShift:
         return "<<";
     case LessThan:
         return "<";
     case LessThanOrEqual:
         return "<=";
     case LogicalAnd:
         return "&&";
     case LogicalOr:
         return "||";
     case Modulo:
         return "%";
     case Multiply:
         return "*";
     case NotEqual:
         return "!=";
     case NullCoalescing:
         return "??";
     case Or:
         return "|";
     case RightShift:
         return ">>";
     case Subtract:
         return "-";
     case UnsignedRightShift:
         return ">>>";
     case Xor:
         return "^";
     default:
         throw new IllegalStateException();
     }
 }
Example #26
0
        public virtual void Visit(BinaryOperator node)
        {
            if (node != null)
            {
                if (node.Operand1 != null)
                {
                    node.Operand1.Accept(this);
                }

                if (node.Operand2 != null)
                {
                    node.Operand2.Accept(this);
                }
            }
        }
Example #27
0
        void showDocumentsAction_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e) {

            try
            {
                IObjectSpace objectSpace = Application.CreateObjectSpace();

                var o = (System.Data.Objects.DataClasses.EntityObject)e.Action.SelectionContext.CurrentObject;
                var c = ((DevExpress.ExpressApp.EF.EFObjectSpace)objectSpace).ObjectContext;
                var table = NKD.Module.BusinessObjects.BusinessObjectHelper.GetTableName(c, e.Action.SelectionContext.CurrentObject.GetType());
                var value = (Guid)o.EntityKey.EntityKeyValues[0].Value;

                
                CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(FileData));
                CriteriaOperator c1 = new BinaryOperator(
                    new OperandProperty("TableType"), table,
                    BinaryOperatorType.Equal
                );
                CriteriaOperator c2 = new BinaryOperator(
                    new OperandProperty("ReferenceID"), value,
                    BinaryOperatorType.Equal
                );
                CriteriaOperator co = c1 & c2;
                collectionSource.Criteria.Add("Refences", co);
                //Do this for manual data lists
                //if ((collectionSource.Collection as XPBaseCollection) != null)
                //{
                //    ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
                //}
                ListView view = Application.CreateListView(Application.GetListViewId(typeof(FileData)), collectionSource, false);
                view.Editor.AllowEdit = true;
                foreach (var k in view.AllowNew.GetKeys())
                    view.AllowNew[k] = false;
                foreach (var k in view.AllowDelete.GetKeys())
                    view.AllowDelete[k] = false;
                foreach (var k in view.AllowEdit.GetKeys())
                    view.AllowEdit[k] = false;
                foreach (var k in e.DialogController.AcceptAction.Enabled.GetKeys())
                    e.DialogController.AcceptAction.Enabled[k] = false;
                e.DialogController.AcceptAction.Enabled.SetItemValue("Item.Enabled", false);
                e.View = view;
                e.DialogController.SaveOnAccept = false;
                
            }
            catch (Exception ex)
            { }


        }
 private string convertOperatorToString(BinaryOperator operation)
 {
     string result = "";
     switch (operation) {
     case BinaryOperator.PLUS: {
         result = "+";
         break;
     }
     case BinaryOperator.MINUS: {
         result = "-";
         break;
     }
     case BinaryOperator.MULTIPLY: {
         result = "*";
         break;
     }
     case BinaryOperator.DIVIDE: {
         result = "/";
         break;
     }
     case BinaryOperator.MODULO: {
         result = "%";
         break;
     }
     case BinaryOperator.SHIFT_LEFT: {
         result = "<<";
         break;
     }
     case BinaryOperator.SHIFT_RIGHT: {
         result = ">>";
         break;
     }
     case BinaryOperator.BINARY_AND: {
         result = "&";
         break;
     }
     case BinaryOperator.BINARY_OR: {
         result = "|";
         break;
     }
     case BinaryOperator.CONCAT: {
         result = "||";
         break;
     }
     }
     return result;
 }
Example #29
0
        public static void OnDeleting(ISendByOrganization organization, IObjectSpace objectSpace)
        {
            var oid = (organization as DevExpress.ExpressApp.DC.DCBaseObject).Oid;

            CriteriaOperator criteria = new BinaryOperator("SentBy.Oid", oid, BinaryOperatorType.Equal);
            if (ReferenceEquals(criteria, null)==false)//(criteria != null)
            {
                var examination = objectSpace.GetObjects<IExamination>(criteria);

                if (examination != null)
                {
                    if (examination.Count>0)
                    {
                        throw new UserFriendlyException(DevExpress.ExpressApp.Utils.CaptionHelper.GetLocalizedText("Messages", "RelatedObjectsDelWarning"));
                    }
                }
            }
        }
Example #30
0
        public static void OnDeleting(ITermsOfPayment payment, IObjectSpace objectSpace)
        {
            var oid = (payment as DevExpress.ExpressApp.DC.DCBaseObject).Oid;

            CriteriaOperator criteria = new BinaryOperator("TermsOfPayment.Oid", oid, BinaryOperatorType.Equal);
            if (ReferenceEquals(criteria, null)==false)
            {
                var patient = objectSpace.GetObjects<IPatient>(criteria);

                if (patient != null)
                {
                    if (patient.Any() ==true)
                    {
                        throw new UserFriendlyException(DevExpress.ExpressApp.Utils.CaptionHelper.GetLocalizedText("Messages", "RelatedObjectsDelWarning"));
                    }
                }
            }
        }
Example #31
0
        public void GivenANumberWithComparatorOfSingleBinaryOperator_WhenBuilt_ThenCorrectExpressionShouldBeCreated(string prefix, BinaryOperator binaryOperator)
        {
            const decimal expected = 15.0m;

            Validate(
                CreateSearchParameter(SearchParamType.Number),
                null,
                $"{prefix}{expected}",
                e => ValidateBinaryExpression(e, FieldName.Number, binaryOperator, expected));
        }
Example #32
0
        public ETL_GoodsInInventoryTransaction ExtractTransaction(Session session, Guid TransactionId, string AccountCode)
        {
            ETL_GoodsInInventoryTransaction 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);

                Organization defaultOrg       = Organization.GetDefault(session, OrganizationEnum.NAAN_DEFAULT);
                Organization currentDeployOrg = Organization.GetDefault(session, OrganizationEnum.QUASAPHARCO);
                Account      defaultAccount   = Account.GetDefault(session, DefaultAccountEnum.NAAN_DEFAULT);
                Transaction  transaction      = session.GetObjectByKey <Transaction>(TransactionId);
                if (transaction == null)
                {
                    return(resultTransaction);
                }

                resultTransaction = new ETL_GoodsInInventoryTransaction();
                if (currentDeployOrg != null)
                {
                    resultTransaction.OwnerOrgId = currentDeployOrg.OrganizationId;
                }
                else
                {
                    resultTransaction.OwnerOrgId = defaultOrg.OrganizationId;
                }

                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>();

                double           numOfItem = 0;
                InventoryCommand command   = null;
                if (transaction != null)
                {
                    InventoryJournal inventoryJournal = null;
                    try
                    {
                        inventoryJournal = transaction.InventoryJournalFinancials.FirstOrDefault().InventoryJournalId;
                        numOfItem        = inventoryJournal.Debit > 0 ? inventoryJournal.Debit : inventoryJournal.Credit;
                        command          = (inventoryJournal.InventoryTransactionId as InventoryCommandItemTransaction).InventoryCommandId;
                    }
                    catch (Exception)
                    {
                        numOfItem = 0;
                        command   = null;
                    }
                }

                resultTransaction.Quantity   = numOfItem;
                resultTransaction.ArtifactId = command == null ? Guid.Empty : command.InventoryCommandId;

                if (numOfItem != 0)
                {
                    resultTransaction.Price = (decimal)resultTransaction.Amount / (decimal)numOfItem;
                }
                else
                {
                    resultTransaction.Price = 0;
                }

                foreach (GeneralJournal journal
                         in
                         transaction.GeneralJournals.Where(i => i.RowStatus == Constant.ROWSTATUS_BOOKED_ENTRY || i.RowStatus == Constant.ROWSTATUS_ACTIVE))
                {
                    if ((journal.Debit + journal.Credit) == 0)
                    {
                        continue;
                    }

                    ETL_GeneralJournal tempJournal = new ETL_GeneralJournal();
                    if (journal.AccountId != null)
                    {
                        tempJournal.AccountId = journal.AccountId.AccountId;
                    }
                    else
                    {
                        tempJournal.AccountId = defaultAccount.AccountId;
                    }

                    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);

                    Account tmpAccount       = session.GetObjectByKey <Account>(tempJournal.AccountId);
                    bool    flgIsLeafAccount = tmpAccount.Accounts == null || tmpAccount.Accounts.Count == 0 ? true : false;

                    if (flgIsLeafAccount &&
                        accountingBO.IsRelateAccount(session, account.AccountId, tempJournal.AccountId))
                    {
                        Acceptable = true;
                    }
                }
                if (!Acceptable)
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            resultTransaction.AccountCode = AccountCode;
            return(resultTransaction);
        }
Example #33
0
        protected virtual string BinaryOperator(BinaryOperator opr)
        {
            switch (opr)
            {
            case Data.BinaryOperator.Plus:
                return("+");

            case Data.BinaryOperator.Minus:
                return("-");

            case Data.BinaryOperator.Multiply:
                return("*");

            case Data.BinaryOperator.Divide:
                return("/");

            case Data.BinaryOperator.Mod:
                return("%");

            case Data.BinaryOperator.Equals:
                return("=");

            case Data.BinaryOperator.NotEquals:
                return("!=");

            case Data.BinaryOperator.GreaterThan:
                return(">");

            case Data.BinaryOperator.GreaterEquals:
                return(">=");

            case Data.BinaryOperator.LessThan:
                return("<");

            case Data.BinaryOperator.LessEquals:
                return("<=");

            case Data.BinaryOperator.And:
                return("AND");

            case Data.BinaryOperator.Or:
                return("OR");

            case Data.BinaryOperator.AndAlso:
                return("AND");

            case Data.BinaryOperator.OrAlso:
                return("OR");

            case Data.BinaryOperator.In:
                return("IN");

            case Data.BinaryOperator.Like:
                return("LIKE");

            case Data.BinaryOperator.Is:
                return("IS");

            case Data.BinaryOperator.Dot:
                return(".");

            case Data.BinaryOperator.None:
            default:
                throw new Exception("不支持的二元操作符。");
            }
        }
Example #34
0
 public Unit Binary(Expression pc, BinaryOperator op, Variable dest, Expression s1, Expression s2, IBoxedExpressionVisitor data)
 {
     data.Binary(op, BoxedExpression.For(s1, this.decoder), BoxedExpression.For(s2, this.decoder), null);
     return(Unit.Value);
 }
Example #35
0
        private StatementPart ParseOperators(ref ParserContext context)
        {
            int            startIndex  = context.Index;
            MethodOperator methodFound = null;
            UnaryOperator  unaryFound  = null;
            BinaryOperator binaryFound = null;

            while (context.Index < context.Chars.Length)
            {
                context.Next();

                int length = context.Index - startIndex;
                if (length > operatorStringsMaxLength)
                {
                    break;
                }
                var partTokens = context.Chars.Slice(startIndex, length);
                foreach (var methodOperator in methodOperators)
                {
                    if (partTokens.SequenceEqual(methodOperator.TokenWithOpener.AsSpan()))
                    {
                        methodFound = methodOperator;
                        break;
                    }
                }
                foreach (var unaryOperator in unaryOperators)
                {
                    if (partTokens.SequenceEqual(unaryOperator.Token.AsSpan()))
                    {
                        unaryFound = unaryOperator;
                        break;
                    }
                }
                foreach (var binaryOperator in binaryOperators)
                {
                    if (partTokens.SequenceEqual(binaryOperator.Token.AsSpan()))
                    {
                        binaryFound = binaryOperator;
                        break;
                    }
                }

                if (methodFound != null)
                {
                    break; //ending ( guarentees can't be longer
                }
            }
            if (methodFound != null)
            {
                var argumentParts = new List <StatementPart>();
                while (context.Index < context.Chars.Length)
                {
                    context.GroupStack.Push(MethodOperator.ArgumentOpener);
                    var argumentPart = ParseParts(ref context);
                    argumentParts.Add(argumentPart);

                    if (context.Current != MethodOperator.ArgumentSeperator)
                    {
                        break;
                    }

                    context.Next();
                }

                var part = new StatementPart(startIndex, methodFound, argumentParts);
                return(part);
            }
            if (unaryFound != null && binaryFound != null)
            {
                if (unaryFound.Token.Length < binaryFound.Token.Length)
                {
                    binaryFound = null;
                }
                else if (unaryFound.Token.Length > binaryFound.Token.Length)
                {
                    unaryFound = null;
                }

                if (unaryFound != null && binaryFound != null)
                {
                    context.Reset(startIndex + unaryFound.Token.Length); //possibly looked for a longer operator name
                    var part = new StatementPart(startIndex, unaryFound, binaryFound);
                    return(part);
                }
            }
            if (unaryFound != null)
            {
                context.Reset(startIndex + unaryFound.Token.Length); //possibly looked for a longer operator name
                var part = new StatementPart(startIndex, unaryFound);
                return(part);
            }
            if (binaryFound != null)
            {
                context.Reset(startIndex + binaryFound.Token.Length); //possibly looked for a longer operator name
                var part = new StatementPart(startIndex, binaryFound);
                return(part);
            }

            context.Reset(startIndex);
            return(ParseGroupOpen(ref context));
        }
        private static Activity HandleBinaryExpression <TLeft, TRight, TResult>(BinaryOperator op, TestExpression left, TestExpression right)
        {
            Activity           we           = null;
            InArgument <TLeft> leftArgument = (InArgument <TLeft>)TestExpression.GetInArgumentFromExpectedNode <TLeft>(left);

            leftArgument.EvaluationOrder = 0;
            InArgument <TRight> rightArgument = (InArgument <TRight>)TestExpression.GetInArgumentFromExpectedNode <TRight>(right);

            rightArgument.EvaluationOrder = 1;

            switch (op)
            {
            case BinaryOperator.Add:
                we = new Add <TLeft, TRight, TResult>()
                {
                    Checked = false,
                    Left    = leftArgument,
                    Right   = rightArgument
                };
                break;

            case BinaryOperator.And:
                we = new And <TLeft, TRight, TResult>()
                {
                    Left  = leftArgument,
                    Right = rightArgument
                };
                break;

            case BinaryOperator.AndAlso:
                we = new AndAlso()
                {
                    Left  = TestExpression.GetWorkflowElementFromExpectedNode <bool>(left),
                    Right = TestExpression.GetWorkflowElementFromExpectedNode <bool>(right)
                };
                break;

            case BinaryOperator.CheckedAdd:
                we = new Add <TLeft, TRight, TResult>()
                {
                    Checked = true,
                    Left    = leftArgument,
                    Right   = rightArgument
                };
                break;

            case BinaryOperator.CheckedMultiply:
                we = new Multiply <TLeft, TRight, TResult>()
                {
                    Checked = true,
                    Left    = leftArgument,
                    Right   = rightArgument
                };
                break;

            case BinaryOperator.CheckedSubtract:
                we = new Subtract <TLeft, TRight, TResult>()
                {
                    Checked = true,
                    Left    = leftArgument,
                    Right   = rightArgument
                };
                break;

            case BinaryOperator.Divide:
                we = new Divide <TLeft, TRight, TResult>()
                {
                    Left  = leftArgument,
                    Right = rightArgument
                };
                break;

            case BinaryOperator.Equal:
                we = new Equal <TLeft, TRight, TResult>()
                {
                    Left  = leftArgument,
                    Right = rightArgument
                };
                break;

            case BinaryOperator.GreaterThan:
                we = new GreaterThan <TLeft, TRight, TResult>()
                {
                    Left  = leftArgument,
                    Right = rightArgument
                };
                break;

            case BinaryOperator.GreaterThanOrEqual:
                we = new GreaterThanOrEqual <TLeft, TRight, TResult>()
                {
                    Left  = leftArgument,
                    Right = rightArgument
                };
                break;

            case BinaryOperator.LessThan:
                we = new LessThan <TLeft, TRight, TResult>()
                {
                    Left  = leftArgument,
                    Right = rightArgument
                };
                break;

            case BinaryOperator.LessThanOrEqual:
                we = new LessThanOrEqual <TLeft, TRight, TResult>()
                {
                    Left  = leftArgument,
                    Right = rightArgument
                };
                break;

            case BinaryOperator.Or:
                we = new Or <TLeft, TRight, TResult>()
                {
                    Left  = leftArgument,
                    Right = rightArgument
                };
                break;

            case BinaryOperator.Multiply:
                we = new Multiply <TLeft, TRight, TResult>()
                {
                    Checked = false,
                    Left    = leftArgument,
                    Right   = rightArgument
                };
                break;

            case BinaryOperator.NotEqual:
                we = new NotEqual <TLeft, TRight, TResult>()
                {
                    Left  = leftArgument,
                    Right = rightArgument
                };
                break;

            case BinaryOperator.OrElse:
                we = new OrElse()
                {
                    Left  = TestExpression.GetWorkflowElementFromExpectedNode <bool>(left),
                    Right = TestExpression.GetWorkflowElementFromExpectedNode <bool>(right)
                };
                break;

            case BinaryOperator.Subtract:
                we = new Subtract <TLeft, TRight, TResult>()
                {
                    Checked = false,
                    Left    = leftArgument,
                    Right   = rightArgument
                };
                break;

            default:
                throw new NotSupportedException(string.Format("Operator: {0} is unsupported", op.ToString()));
            }

            return(we);
        }
Example #37
0
        private CriteriaOperator SearchCriteriaObjectBuilder()
        {
            CriteriaOperator criteria    = null;
            CriteriaOperator criteriaAND = null;
            CriteriaOperator criteriaOR  = null;

            criteria = new GroupOperator();
            ((GroupOperator)criteria).OperatorType = GroupOperatorType.And;

            criteriaAND = new GroupOperator();
            ((GroupOperator)criteriaAND).OperatorType = GroupOperatorType.And;

            criteriaOR = new GroupOperator();
            ((GroupOperator)criteriaOR).OperatorType = GroupOperatorType.Or;


            // Конъюнктивные члены

            if (!string.IsNullOrEmpty(AdditionalCriterionString))
            {
                CriteriaOperator AdditionalCriterionOperator = CriteriaOperator.Parse(AdditionalCriterionString);
                ((GroupOperator)criteriaAND).Operands.Add(AdditionalCriterionOperator);
            }


            if (this.DateBegin != System.DateTime.MinValue)
            {
                CriteriaOperator criteriathisDateBegin = new BinaryOperator("ObligationUnitDateTime", this.DateBegin, BinaryOperatorType.GreaterOrEqual);
                ((GroupOperator)criteriaAND).Operands.Add(criteriathisDateBegin);
            }

            if (this.DateEnd != System.DateTime.MinValue)
            {
                CriteriaOperator criteriathisDateEnd = new BinaryOperator("ObligationUnitDateTime", this.DateEnd, BinaryOperatorType.LessOrEqual);
                ((GroupOperator)criteriaAND).Operands.Add(criteriathisDateEnd);
            }


            //CriteriaOperator criteriaDepartment = null;
            //if (this.Department != null) {
            //    criteriaDepartment = new BinaryOperator("DepartmentRegistrator.Oid", this.Department.Oid, BinaryOperatorType.Equal);
            //    ((GroupOperator)criteriaAND).Operands.Add(criteriaDepartment);
            //}

            //CriteriaOperator criteriaDealState = null;
            //if (this.DealState != 0) {
            //    criteriaDealState = new BinaryOperator("DealState", DealState, BinaryOperatorType.Equal);
            //    ((GroupOperator)criteriaAND).Operands.Add(criteriaDealState);
            //}

            // BEGIN
            CriteriaOperator criteriaCustomerAND = new GroupOperator();

            ((GroupOperator)criteriaCustomerAND).OperatorType = GroupOperatorType.And;

            CriteriaOperator criteriaPrimaryParty = null;

            if (this.PrimaryParty != null)
            {
                criteriaPrimaryParty = new BinaryOperator("PrimaryParty.Oid", PrimaryParty.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaCustomerAND).Operands.Add(criteriaPrimaryParty);
            }

            CriteriaOperator criteriaContragentParty = null;

            if (this.ContragentParty != null)
            {
                criteriaContragentParty = new BinaryOperator("ContragentParty.Oid", ContragentParty.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaCustomerAND).Operands.Add(criteriaContragentParty);
            }

            if (((GroupOperator)criteriaCustomerAND).Operands.Count > 0)
            {
                ((GroupOperator)criteriaAND).Operands.Add(criteriaCustomerAND);
            }



            CriteriaOperator criteriaContract = null;

            if (this.Contract != null)
            {
                criteriaContract = new BinaryOperator("Contract.Oid", Contract.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaCustomerAND).Operands.Add(criteriaContract);
            }

            CriteriaOperator criteriaContractDeal = null;

            if (this.ContractDeal != null)
            {
                criteriaContractDeal = new BinaryOperator("ContractDeal.Oid", ContractDeal.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaCustomerAND).Operands.Add(criteriaContractDeal);
            }

            CriteriaOperator criteriaCostItem = null;

            if (this.CostItem != null)
            {
                criteriaCostItem = new BinaryOperator("CostItem.Oid", CostItem.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaCustomerAND).Operands.Add(criteriaCostItem);
            }

            CriteriaOperator criteriaSubject = null;

            if (this.Subject != null)
            {
                criteriaSubject = new BinaryOperator("Subject.Oid", Subject.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaCustomerAND).Operands.Add(criteriaSubject);
            }

            CriteriaOperator criteriafmOrder = null;

            if (this.fmOrder != null)
            {
                criteriafmOrder = new BinaryOperator("fmOrder.Oid", fmOrder.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaCustomerAND).Operands.Add(criteriafmOrder);
            }

            CriteriaOperator criteriaStage = null;

            if (this.Stage != null)
            {
                criteriaStage = new BinaryOperator("Stage.Oid", Stage.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaCustomerAND).Operands.Add(criteriaStage);
            }

            CriteriaOperator criteriaStageTech = null;

            if (this.StageTech != null)
            {
                criteriaStageTech = new BinaryOperator("StageTech.Oid", StageTech.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaCustomerAND).Operands.Add(criteriaStageTech);
            }

            // END

            /*
             * // BEGIN
             * CriteriaOperator criteriaSupplierOR = new GroupOperator();
             * ((GroupOperator)criteriaSupplierOR).OperatorType = GroupOperatorType.Or;
             *
             * CriteriaOperator criteriaSupplier = null;
             * if (this.Supplier != null) {
             *  criteriaSupplier = new BinaryOperator("Supplier.Party.Oid", Supplier.Oid, BinaryOperatorType.Equal);
             *  ((GroupOperator)criteriaSupplierOR).Operands.Add(criteriaSupplier);
             * }
             *
             * CriteriaOperator criteriaPersonOfSupplier = null;
             * if (this.PersonOfSupplier != null) {
             *  criteriaPersonOfSupplier = new BinaryOperator("Supplier.Party.Person.Oid", PersonOfSupplier.Oid, BinaryOperatorType.Equal);
             *  ((GroupOperator)criteriaSupplierOR).Operands.Add(criteriaPersonOfSupplier);
             * }
             *
             * if (((GroupOperator)criteriaSupplierOR).Operands.Count > 0) ((GroupOperator)criteriaAND).Operands.Add(criteriaSupplierOR);
             * // END
             *
             * CriteriaOperator criteriaCurator = null;
             * if (this.Curator != null) {
             *  criteriaCurator = new BinaryOperator("Curator.Oid", Curator.Oid, BinaryOperatorType.Equal);
             *  ((GroupOperator)criteriaAND).Operands.Add(criteriaCurator);
             * }
             *
             * CriteriaOperator criteriaUserRegistrator = null;
             * if (this.UserRegistrator != null) {
             *  criteriaUserRegistrator = new BinaryOperator("UserRegistrator.Oid", UserRegistrator.Oid, BinaryOperatorType.Equal);
             *  ((GroupOperator)criteriaAND).Operands.Add(criteriaUserRegistrator);
             * }
             */

            CriteriaOperator criteriaValuta = null;

            if (this.Valuta != null)
            {
                criteriaValuta = new BinaryOperator("Valuta.Oid", Valuta.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaAND).Operands.Add(criteriaValuta);
            }

            if (this.PriceFrom != 0)
            {
                CriteriaOperator criteriathisPriceFrom = new BinaryOperator("CostInRUR", this.PriceFrom, BinaryOperatorType.GreaterOrEqual);
                ((GroupOperator)criteriaAND).Operands.Add(criteriathisPriceFrom);
            }

            if (this.PriceTo != 0)
            {
                CriteriaOperator criteriathisPriceTo = new BinaryOperator("CostInRUR", this.PriceTo, BinaryOperatorType.LessOrEqual);
                ((GroupOperator)criteriaAND).Operands.Add(criteriathisPriceTo);
            }

            CriteriaOperator criteriaPaymentValuta = null;

            if (this.PaymentValuta != null)
            {
                criteriaPaymentValuta = new BinaryOperator("PaymentValuta.Oid", PaymentValuta.Oid, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaAND).Operands.Add(criteriaPaymentValuta);
            }

            if (this.PaymentPriceFrom != 0)
            {
                CriteriaOperator criteriaPaymentPriceFrom = new BinaryOperator("PaymentCost", this.PaymentPriceFrom, BinaryOperatorType.GreaterOrEqual);
                ((GroupOperator)criteriaAND).Operands.Add(criteriaPaymentPriceFrom);
            }

            if (this.PaymentPriceTo != 0)
            {
                CriteriaOperator criteriaPaymentPriceTo = new BinaryOperator("PaymentCost", this.PaymentPriceTo, BinaryOperatorType.LessOrEqual);
                ((GroupOperator)criteriaAND).Operands.Add(criteriaPaymentPriceTo);
            }

            if (this.PlaneFact != 0)
            {
                CriteriaOperator criteriaPlaneFact = new BinaryOperator("PlaneFact ", this.PlaneFact, BinaryOperatorType.Equal);
                ((GroupOperator)criteriaAND).Operands.Add(criteriaPlaneFact);
            }

            // Совокупность критериев OR добавляем через AND к общей совокупности поисковых членов
            if (((GroupOperator)criteriaAND).Operands.Count > 0)
            {
                ((GroupOperator)criteria).Operands.Add(criteriaAND);
            }


            // Дизъюнктивные члены
            CriteriaOperator criteriaDocumentNumber = null;

            if (!string.IsNullOrEmpty(this.DocumentNumber))
            {
                //criteriaDocumentNumber = new BinaryOperator("DealVersion.ContractDocument.Number", "%" + this.DocumentNumber + "%", BinaryOperatorType.Like);
                criteriaDocumentNumber = new BinaryOperator("ContractDocument.Number", "%" + this.DocumentNumber + "%", BinaryOperatorType.Like);
                ((GroupOperator)criteriaOR).Operands.Add(criteriaDocumentNumber);
            }

            CriteriaOperator criteriaDescriptionShort = null;

            if (!string.IsNullOrEmpty(this.Description))
            {
                //criteriaDescriptionShort = new BinaryOperator("DealVersion.DescriptionShort", "%" + this.Description + "%", BinaryOperatorType.Like);
                criteriaDescriptionShort = new BinaryOperator("DescriptionShort", "%" + this.Description + "%", BinaryOperatorType.Like);
                ((GroupOperator)criteriaOR).Operands.Add(criteriaDescriptionShort);
            }

            // Совокупность критериев OR добавляем через AND к общей совокупности поисковых членов
            if (((GroupOperator)criteriaOR).Operands.Count > 0)
            {
                ((GroupOperator)criteria).Operands.Add(criteriaOR);
            }



            if (((GroupOperator)criteria).Operands.Count > 0)
            {
                return(criteria);
            }
            else
            {
                return(null);
            }
        }
Example #38
0
 public BinaryOpSpec(string token, BinaryOperator op, bool alphaNum)
 {
     this.token    = token;
     this.op       = op;
     this.alphaNum = alphaNum;
 }
 public AttributeBinaryExpression(PropertyNameExpression left, BinaryOperator op, UInt64 value)
     : base(left, op, new LiteralExpression <UInt64>(value))
 {
 }
Example #40
0
 public bool IsBinaryOperator(Expression exp, out BinaryOperator op, out Expression left, out Expression right)
 {
     return(VisitorForIsBinaryExpression.IsBinary(exp, out op, out left, out right, this));
 }
Example #41
0
 public virtual bool Binary(Expression pc, BinaryOperator op, Variable dest, Expression s1, Expression s2, Unit data)
 {
     return(false);
 }
Example #42
0
 public Vector2DAddOperation() : base("Vector 2D add", null, BinaryOperator.GetCenteredOperator("+"))
 {
 }
Example #43
0
 public override bool Binary(Expression pc, BinaryOperator op, Variable dest, Expression s1, Expression s2, Unit data)
 {
     this.Variable = dest;
     return(true);
 }
Example #44
0
        public void GivenADateWithComparatorOfSingleBinaryOperator_WhenBuilt_ThenCorrectExpressionShouldBeCreated(string prefix, string dateTimeInput, FieldName fieldName, BinaryOperator binaryOperator, bool expectStartTimeValue)
        {
            var partialDateTime     = PartialDateTime.Parse(dateTimeInput);
            var dateTimeSearchValue = new DateTimeSearchValue(partialDateTime);

            Validate(
                CreateSearchParameter(SearchParamType.Date),
                null,
                prefix + dateTimeInput,
                e => ValidateDateTimeBinaryOperatorExpression(
                    e,
                    fieldName,
                    binaryOperator,
                    expectStartTimeValue ? dateTimeSearchValue.Start : dateTimeSearchValue.End));
        }
                private INumericalAbstractDomain <BoxedVariable <Variable>, BoxedExpression> FloatTypesBinary(APC pc, BinaryOperator op, Variable dest, Variable s1, Variable s2, INumericalAbstractDomain <BoxedVariable <Variable>, BoxedExpression> data)
                {
                    ConcreteFloat t1, t2;

                    if (TryFloatType(pc, s1, out t1) && TryFloatType(pc, s2, out t2))
                    {
                        var prevType = data.GetFloatType(ToBoxedVariable(dest));

                        if (prevType.IsTop)
                        {
                            data.SetFloatType(ToBoxedVariable(dest), ConcreteFloat.Float80);
                        }
                        else
                        {
                            data.SetFloatType(ToBoxedVariable(dest), ConcreteFloat.Uncompatible);
                        }
                    }

                    return(data);
                }
 protected AttributeBinaryExpression(PropertyNameExpression left, BinaryOperator op, Expression right)
     : base(left, op, right)
 {
 }
Example #47
0
        private void VarifyUser(UserLoginResult result)
        {
            if (result.Parameter.ServerName == "")
            {
                result.Message = "Please input the server name.";
                return;
            }
            string serverUrl = string.Empty;

            if (result.Parameter.ServiceName != "")
            {
                serverUrl = result.Parameter.ServerName + "/" + result.Parameter.ServiceName;
            }
            else
            {
                serverUrl = result.Parameter.ServerName;
            }
            serverUrl = AppandProtocal(serverUrl);
            Uri serverUri;

            if (!Uri.TryCreate(serverUrl, UriKind.Absolute, out serverUri))
            {
                result.Message = "The server or service you entered is incorrect.";
                return;
            }
            bool isServerReachable = CheckConnection(serverUri);

            if (!isServerReachable)
            {
                result.Message = "The server or service you entered is not available.";
                return;
            }
            string loginPageUrl      = serverUrl + (serverUrl.EndsWith("/") ? "" : "/") + "Login.aspx";
            bool   isLogiPageAvaible = IsUrlReachable(loginPageUrl);

            if (!isLogiPageAvaible)
            {
                result.Message = "The server or service you entered is not available.";
                return;
            }

            UpdateSetting(ServerUrlSettingName, serverUrl);

            LoadMetadata();

            string userName = result.Parameter.UserName;
            string password = result.Parameter.Password;
            var    provider = (ClientFormsAuthenticationMembershipProvider)Membership.Provider;

            provider.ServiceUri = ConfigurationManager.AppSettings["ServerUrl"] + "/Authentication_JSON_AppService.axd";
            if (!Membership.ValidateUser(userName, password))
            {
                result.Message = "The username or password you entered is incorrect.";
                return;
            }
            try
            {
                var dynamicDataServiceContext   = new DynamicDataServiceContext();
                CriteriaOperator userNameFilter = new BinaryOperator("UserName", userName);
                var user =
                    dynamicDataServiceContext.GetObjects("User", userNameFilter, null)._First();

                var userId       = (Guid)user.GetType().GetProperty("UserId").GetValue(user, null);
                var fullName     = (string)user.GetType().GetProperty("FullName").GetValue(user, null);
                var extraColumns = new Dictionary <string, string> {
                    { "Role", "Role" }
                };
                var userRoles      = dynamicDataServiceContext.GetObjects("UserRole", new BinaryOperator("UserId", userId), extraColumns);
                var currentRoles   = userRoles.AsQueryable().Select("Role").ToArrayList();
                var userPrivileges = new List <Privilege>();
                foreach (var role in currentRoles)
                {
                    dynamicDataServiceContext.LoadProperty(role, "RolePrivileges");
                    var rolePrivileges = (IList)role.GetType().GetProperty("RolePrivileges").GetValue(role, null);
                    foreach (var rolePrivilege in rolePrivileges)
                    {
                        dynamicDataServiceContext.LoadProperty(rolePrivilege, "Privilege");
                        var privilege = rolePrivilege.GetType().GetProperty("Privilege").GetValue(rolePrivilege, null);
                        var name      = (string)privilege.GetType().GetProperty("Name").GetValue(privilege, null);
                        dynamicDataServiceContext.LoadProperty(privilege, "PrivilegeEntities");
                        var privilegeEntities =
                            (IList)privilege.GetType().GetProperty("PrivilegeEntities").GetValue(privilege, null);
                        userPrivileges.AddRange(from object privilegeEntity in privilegeEntities
                                                select(string) privilegeEntity.GetType().GetProperty("EntityName")
                                                .GetValue(privilegeEntity, null)
                                                into entityName
                                                select new Privilege()
                        {
                            EntityName = entityName, Name = name
                        });
                    }
                }

                var identity  = new CustomIdentity(userId, userName, fullName);
                var principal = new CustomPrincipal(identity, userPrivileges.ToArray());
                AppDomain.CurrentDomain.SetThreadPrincipal(principal);
                result.Result = true;
            }
            catch (Exception ex)
            {
                result.Message = BuildExceptionString(ex);
            }
        }
Example #48
0
        /// <summary>
        /// Memory accesses are translated into expressions, performing simplifications
        /// where possible.
        /// </summary>
        public Expression EffectiveAddressExpression(X86Instruction instr, MemoryOperand mem)
        {
            Expression?eIndex      = null;
            Expression?eBase       = null;
            Expression?expr        = null;
            bool       ripRelative = false;

            if (mem.Base != RegisterStorage.None)
            {
                if (mem.Base == Registers.rip)
                {
                    ripRelative = true;
                }
                else
                {
                    eBase = AluRegister(mem.Base);
                    if (expr != null)
                    {
                        expr = m.IAdd(eBase, expr);
                    }
                    else
                    {
                        expr = eBase;
                    }
                }
            }

            if (mem.Offset !.IsValid)
            {
                if (ripRelative)
                {
                    expr = instr.Address + (instr.Length + mem.Offset.ToInt64());
                }
                else if (expr != null)
                {
                    BinaryOperator op = Operator.IAdd;
                    long           l  = mem.Offset.ToInt64();
                    if (l < 0 && l > -0x800)
                    {
                        l  = -l;
                        op = Operator.ISub;
                    }

                    DataType dt      = (eBase != null) ? eBase.DataType : eIndex !.DataType;
                    Constant cOffset = Constant.Create(dt, l);
                    expr = new BinaryExpression(op, dt, expr, cOffset);
                }
                else
                {
                    expr = mem.Offset;
                }
            }

            if (mem.Index != RegisterStorage.None)
            {
                eIndex = AluRegister(mem.Index);
                if (mem.Scale != 0 && mem.Scale != 1)
                {
                    eIndex = m.IMul(eIndex, Constant.Create(mem.Index.DataType, mem.Scale));
                }
                expr = m.IAdd(expr !, eIndex);
            }
            if (!IsSegmentedAccessRequired && expr is Constant c && mem.SegOverride == RegisterStorage.None)
            {
                return(arch.MakeAddressFromConstant(c, false) !);
            }
            return(expr !);
        }
        public async Task RunAsync(int iterations)
        {
            using (var connection = GetOpenConnection())
            {
#pragma warning disable IDE0017 // Simplify object initialization
#pragma warning disable RCS1121 // Use [] instead of calling 'First'.
                var tests = new Tests();

                // Linq2SQL
                Try(() =>
                {
                    var l2scontext1 = GetL2SContext(connection);
                    tests.Add(id => l2scontext1.Posts.First(p => p.Id == id), "Linq2Sql: Normal");

                    var l2scontext2     = GetL2SContext(connection);
                    var compiledGetPost = CompiledQuery.Compile((Linq2Sql.DataClassesDataContext ctx, int id) => ctx.Posts.First(p => p.Id == id));
                    tests.Add(id => compiledGetPost(l2scontext2, id), "Linq2Sql: Compiled");

                    var l2scontext3 = GetL2SContext(connection);
                    tests.Add(id => l2scontext3.ExecuteQuery <Post>("select * from Posts where Id = {0}", id).First(), "Linq2Sql: ExecuteQuery");
                }, "LINQ-to-SQL");

                // Entity Framework
                Try(() =>
                {
                    var entityContext = new EFContext(connection);
                    tests.Add(id => entityContext.Posts.First(p => p.Id == id), "Entity Framework");

                    var entityContext2 = new EFContext(connection);
                    tests.Add(id => entityContext2.Database.SqlQuery <Post>("select * from Posts where Id = {0}", id).First(), "Entity Framework: SqlQuery");

                    var entityContext3 = new EFContext(connection);
                    tests.Add(id => entityContext3.Posts.AsNoTracking().First(p => p.Id == id), "Entity Framework: No Tracking");
                }, "Entity Framework");

                // Entity Framework Core
                Try(() =>
                {
                    var entityContext = new EFCoreContext(ConnectionString);
                    tests.Add(id => entityContext.Posts.First(p => p.Id == id), "Entity Framework Core");

                    var entityContext2 = new EFCoreContext(ConnectionString);
                    tests.Add(id => entityContext2.Posts.FromSql("select * from Posts where Id = {0}", id).First(), "Entity Framework Core: FromSql");

                    var entityContext3 = new EFContext(connection);
                    tests.Add(id => entityContext3.Posts.AsNoTracking().First(p => p.Id == id), "Entity Framework Core: No Tracking");
                }, "Entity Framework Core");

                // Dapper
                Try(() =>
                {
                    var mapperConnection = GetOpenConnection();
                    tests.Add(id => mapperConnection.Query <Post>("select * from Posts where Id = @Id", new { Id = id }, buffered: true).First(), "Dapper: Query (buffered)");
                    tests.Add(id => mapperConnection.Query <Post>("select * from Posts where Id = @Id", new { Id = id }, buffered: false).First(), "Dapper: Query (non-buffered)");
                    tests.Add(id => mapperConnection.QueryFirstOrDefault <Post>("select * from Posts where Id = @Id", new { Id = id }), "Dapper: QueryFirstOrDefault");

                    var mapperConnection2 = GetOpenConnection();
                    tests.Add(id => mapperConnection2.Query("select * from Posts where Id = @Id", new { Id = id }, buffered: true).First(), "Dapper: Dynamic Query (buffered)");
                    tests.Add(id => mapperConnection2.Query("select * from Posts where Id = @Id", new { Id = id }, buffered: false).First(), "Dapper: Dynamic Query (non-buffered)");
                    tests.Add(id => mapperConnection2.QueryFirstOrDefault("select * from Posts where Id = @Id", new { Id = id }), "Dapper: Dynamic QueryFirstOrDefault");

                    // dapper.contrib
                    var mapperConnection3 = GetOpenConnection();
                    tests.Add(id => mapperConnection3.Get <Post>(id), "Dapper.Contrib");
                }, "Dapper");

                // Dashing
                Try(() =>
                {
                    var config   = new DashingConfiguration();
                    var database = new SqlDatabase(config, ConnectionString);
                    var session  = database.BeginTransactionLessSession(GetOpenConnection());
                    tests.Add(id => session.Get <Dashing.Post>(id), "Dashing Get");
                }, "Dashing");

                // Massive
                Try(() =>
                {
                    var massiveModel      = new DynamicModel(ConnectionString);
                    var massiveConnection = GetOpenConnection();
                    tests.Add(id => massiveModel.Query("select * from Posts where Id = @0", massiveConnection, id).First(), "Massive: Dynamic ORM Query");
                }, "Massive");

                // PetaPoco
                Try(() =>
                {
                    // PetaPoco test with all default options
                    var petapoco = new PetaPoco.Database(ConnectionString, "System.Data.SqlClient");
                    petapoco.OpenSharedConnection();
                    tests.Add(id => petapoco.Fetch <Post>("SELECT * from Posts where Id=@0", id).First(), "PetaPoco: Normal");

                    // PetaPoco with some "smart" functionality disabled
                    var petapocoFast = new PetaPoco.Database(ConnectionString, "System.Data.SqlClient");
                    petapocoFast.OpenSharedConnection();
                    petapocoFast.EnableAutoSelect    = false;
                    petapocoFast.EnableNamedParams   = false;
                    petapocoFast.ForceDateTimesToUtc = false;
                    tests.Add(id => petapocoFast.Fetch <Post>("SELECT * from Posts where Id=@0", id).First(), "PetaPoco: Fast");
                }, "PetaPoco");

                // NHibernate
                Try(() =>
                {
                    var nhSession1 = NHibernateHelper.OpenSession();
                    tests.Add(id => nhSession1.CreateSQLQuery("select * from Posts where Id = :id")
                              .SetInt32("id", id)
                              .List(), "NHibernate: SQL");

                    var nhSession2 = NHibernateHelper.OpenSession();
                    tests.Add(id => nhSession2.CreateQuery("from Post as p where p.Id = :id")
                              .SetInt32("id", id)
                              .List(), "NHibernate: HQL");

                    var nhSession3 = NHibernateHelper.OpenSession();
                    tests.Add(id => nhSession3.CreateCriteria <Post>()
                              .Add(Restrictions.IdEq(id))
                              .List(), "NHibernate: Criteria");

                    var nhSession4 = NHibernateHelper.OpenSession();
                    tests.Add(id => nhSession4
                              .Query <Post>()
                              .First(p => p.Id == id), "NHibernate: LINQ");

                    var nhSession5 = NHibernateHelper.OpenSession();
                    tests.Add(id => nhSession5.Get <Post>(id), "NHibernate: Session.Get");
                }, "NHibernate");

                // Belgrade
                Try(() =>
                {
                    var query = new Belgrade.SqlClient.SqlDb.QueryMapper(ConnectionString);
                    tests.AsyncAdd(id => query.Sql("SELECT TOP 1 * FROM Posts WHERE Id = @Id").Param("Id", id).Map(
                                       reader =>
                    {
                        var post            = new Post();
                        post.Id             = reader.GetInt32(0);
                        post.Text           = reader.GetString(1);
                        post.CreationDate   = reader.GetDateTime(2);
                        post.LastChangeDate = reader.GetDateTime(3);

                        post.Counter1 = reader.IsDBNull(4) ? null : (int?)reader.GetInt32(4);
                        post.Counter2 = reader.IsDBNull(5) ? null : (int?)reader.GetInt32(5);
                        post.Counter3 = reader.IsDBNull(6) ? null : (int?)reader.GetInt32(6);
                        post.Counter4 = reader.IsDBNull(7) ? null : (int?)reader.GetInt32(7);
                        post.Counter5 = reader.IsDBNull(8) ? null : (int?)reader.GetInt32(8);
                        post.Counter6 = reader.IsDBNull(9) ? null : (int?)reader.GetInt32(9);
                        post.Counter7 = reader.IsDBNull(10) ? null : (int?)reader.GetInt32(10);
                        post.Counter8 = reader.IsDBNull(11) ? null : (int?)reader.GetInt32(11);
                        post.Counter9 = reader.IsDBNull(12) ? null : (int?)reader.GetInt32(12);
                    }), "Belgrade Sql Client");
                }, "Belgrade Sql Client");

                //Susanoo
                Try(() =>
                {
                    var susanooDb = new DatabaseManager(connection);

                    var susanooPreDefinedCommand =
                        CommandManager.Instance.DefineCommand("SELECT * FROM Posts WHERE Id = @Id", CommandType.Text)
                        .DefineResults <Post>()
                        .Realize();

                    var susanooDynamicPreDefinedCommand =
                        CommandManager.Instance.DefineCommand("SELECT * FROM Posts WHERE Id = @Id", CommandType.Text)
                        .DefineResults <dynamic>()
                        .Realize();

                    tests.Add(Id =>
                              CommandManager.Instance.DefineCommand("SELECT * FROM Posts WHERE Id = @Id", CommandType.Text)
                              .DefineResults <Post>()
                              .Realize()
                              .Execute(susanooDb, new { Id }).First(), "Susanoo: Mapping Cache Retrieval");

                    tests.Add(Id =>
                              CommandManager.Instance.DefineCommand("SELECT * FROM Posts WHERE Id = @Id", CommandType.Text)
                              .DefineResults <dynamic>()
                              .Realize()
                              .Execute(susanooDb, new { Id }).First(), "Susanoo: Dynamic Mapping Cache Retrieval");

                    tests.Add(Id => susanooDynamicPreDefinedCommand
                              .Execute(susanooDb, new { Id }).First(), "Susanoo: Dynamic Mapping Static");

                    tests.Add(Id => susanooPreDefinedCommand
                              .Execute(susanooDb, new { Id }).First(), "Susanoo: Mapping Static");
                }, "Susanoo");

                //ServiceStack's OrmLite:
                Try(() =>
                {
                    var dbFactory = new OrmLiteConnectionFactory(ConnectionString, SqlServerDialect.Provider);
                    var db        = dbFactory.Open();
                    tests.Add(id => db.SingleById <Post>(id), "ServiceStack.OrmLite: SingleById");
                }, "ServiceStack.OrmLite");

                // Hand Coded
                Try(() =>
                {
                    var postCommand = new SqlCommand()
                    {
                        Connection  = connection,
                        CommandText = @"select Id, [Text], [CreationDate], LastChangeDate, 
                Counter1,Counter2,Counter3,Counter4,Counter5,Counter6,Counter7,Counter8,Counter9 from Posts where Id = @Id"
                    };
                    var idParam = postCommand.Parameters.Add("@Id", SqlDbType.Int);

                    tests.Add(id =>
                    {
                        idParam.Value = id;

                        using (var reader = postCommand.ExecuteReader())
                        {
                            reader.Read();
                            var post            = new Post();
                            post.Id             = reader.GetInt32(0);
                            post.Text           = reader.GetNullableString(1);
                            post.CreationDate   = reader.GetDateTime(2);
                            post.LastChangeDate = reader.GetDateTime(3);

                            post.Counter1 = reader.GetNullableValue <int>(4);
                            post.Counter2 = reader.GetNullableValue <int>(5);
                            post.Counter3 = reader.GetNullableValue <int>(6);
                            post.Counter4 = reader.GetNullableValue <int>(7);
                            post.Counter5 = reader.GetNullableValue <int>(8);
                            post.Counter6 = reader.GetNullableValue <int>(9);
                            post.Counter7 = reader.GetNullableValue <int>(10);
                            post.Counter8 = reader.GetNullableValue <int>(11);
                            post.Counter9 = reader.GetNullableValue <int>(12);
                        }
                    }, "Hand Coded");

#if !NETSTANDARD1_3
                    var table = new DataTable
                    {
                        Columns =
                        {
                            { "Id",             typeof(int)      },
                            { "Text",           typeof(string)   },
                            { "CreationDate",   typeof(DateTime) },
                            { "LastChangeDate", typeof(DateTime) },
                            { "Counter1",       typeof(int)      },
                            { "Counter2",       typeof(int)      },
                            { "Counter3",       typeof(int)      },
                            { "Counter4",       typeof(int)      },
                            { "Counter5",       typeof(int)      },
                            { "Counter6",       typeof(int)      },
                            { "Counter7",       typeof(int)      },
                            { "Counter8",       typeof(int)      },
                            { "Counter9",       typeof(int)      },
                        }
                    };
                    tests.Add(id =>
                    {
                        idParam.Value   = id;
                        object[] values = new object[13];
                        using (var reader = postCommand.ExecuteReader())
                        {
                            reader.Read();
                            reader.GetValues(values);
                            table.Rows.Add(values);
                        }
                    }, "DataTable via IDataReader.GetValues");
#endif
                }, "Hand Coded");

                // DevExpress.XPO
                Try(() =>
                {
                    IDataLayer dataLayer = XpoDefault.GetDataLayer(connection, DevExpress.Xpo.DB.AutoCreateOption.SchemaAlreadyExists);
                    dataLayer.Dictionary.GetDataStoreSchema(typeof(Xpo.Post));
                    UnitOfWork session          = new UnitOfWork(dataLayer, dataLayer);
                    session.IdentityMapBehavior = IdentityMapBehavior.Strong;
                    session.TypesManager.EnsureIsTypedObjectValid();

                    tests.Add(id => session.Query <Xpo.Post>().First(p => p.Id == id), "DevExpress.XPO: Query<T>");
                    tests.Add(id => session.GetObjectByKey <Xpo.Post>(id, true), "DevExpress.XPO: GetObjectByKey<T>");
                    tests.Add(id =>
                    {
                        CriteriaOperator findCriteria = new BinaryOperator()
                        {
                            OperatorType = BinaryOperatorType.Equal,
                            LeftOperand  = new OperandProperty("Id"),
                            RightOperand = new ConstantValue(id)
                        };
                        session.FindObject <Xpo.Post>(findCriteria);
                    }, "DevExpress.XPO: FindObject<T>");
                }, "DevExpress.XPO");

                // Subsonic isn't maintained anymore - doesn't import correctly
                //Try(() =>
                //    {
                //    // Subsonic ActiveRecord
                //    tests.Add(id => 3SubSonic.Post.SingleOrDefault(x => x.Id == id), "SubSonic ActiveRecord.SingleOrDefault");

                //    // Subsonic coding horror
                //    SubSonic.tempdbDB db = new SubSonic.tempdbDB();
                //    tests.Add(id => new SubSonic.Query.CodingHorror(db.Provider, "select * from Posts where Id = @0", id).ExecuteTypedList<Post>(), "SubSonic Coding Horror");
                //}, "Subsonic");

                //// BLToolkit - doesn't import correctly in the new .csproj world
                //var db1 = new DbManager(GetOpenConnection());
                //tests.Add(id => db1.SetCommand("select * from Posts where Id = @id", db1.Parameter("id", id)).ExecuteList<Post>(), "BLToolkit");

                Console.WriteLine();
                Console.WriteLine("Running...");
                await tests.RunAsync(iterations).ConfigureAwait(false);

#pragma warning restore RCS1121 // Use [] instead of calling 'First'.
#pragma warning restore IDE0017 // Simplify object initialization
            }
        }
 public AttributeBinaryExpression(PropertyNameExpression left, BinaryOperator op, IEnumerable <DateTime> values)
     : base(left, op, new CollectionExpression <DateTime>(values))
 {
 }
Example #51
0
 public object Visit(BinaryOperator theOperator)
 {
     theOperator.LeftOperand.Accept(this);
     theOperator.RightOperand.Accept(this);
     return(theOperator);
 }
Example #52
0
 public string Binary(Expression pc, BinaryOperator op, Variable dest, Expression s1, Expression s2, Unit data)
 {
     return(null);
 }
 public AttributeBinaryExpression(PropertyNameExpression left, BinaryOperator op, SByte value)
     : base(left, op, new LiteralExpression <SByte>(value))
 {
 }
 public AttributeBinaryExpression(PropertyNameExpression left, BinaryOperator op, String value)
     : base(left, op, new StringExpression(value))
 {
 }
Example #55
0
 public IBinaryOperator Equality()
 {
     return(BinaryOperator.Wrap(EqualityMethod(), ValueTypeEqualityMethod(), "operator =="));
 }
                public override INumericalAbstractDomain <BoxedVariable <Variable>, BoxedExpression> Binary(APC pc, BinaryOperator op, Variable dest, Variable s1, Variable s2, INumericalAbstractDomain <BoxedVariable <Variable>, BoxedExpression> data)
                {
                    data = FloatTypesBinary(pc, op, dest, s1, s2, data);

                    return(base.Binary(pc, op, dest, s1, s2, data));
                }
Example #57
0
 public IBinaryOperator Inequality()
 {
     return(BinaryOperator.Wrap(InequalityMethod(), ValueTypeInequalityMethod(), "operator !="));
 }
Example #58
0
 public PyObj PreBinaryOperation(BinaryOperator binaryOperator)
 {
     return(Calculator.PreBinaryOperation(this, binaryOperator));
 }
 public ReadOnlyOperatorOverload(BinaryOperator operatorOverload)
 {
     this.operatorOverload = new ReadOnlyBinaryOperator(operatorOverload);
 }
 public AttributeBinaryExpression(PropertyNameExpression left, BinaryOperator op, Decimal value)
     : base(left, op, new LiteralExpression <Decimal>(value))
 {
 }