/// <summary>
        /// Creates a copy of the provided value which includes all objects reachable through given span paths.
        /// </summary>
        /// <param name="valueToSpan">Value to apply span for.</param>
        /// <param name="expandedPaths">The expanded paths.</param>
        /// <param name="selectedPaths">The selected paths needed to match up with the expanded paths.</param>
        /// <returns>
        /// Copy of the value trimmed to given span paths.
        /// </returns>
        public QueryValue GenerateSpan(QueryValue valueToSpan, IEnumerable<string> expandedPaths, IEnumerable<string> selectedPaths)
        {
            ExceptionUtilities.CheckArgumentNotNull(valueToSpan, "valueToSpan");
            ExceptionUtilities.CheckArgumentNotNull(expandedPaths, "expandedPaths");
            ExceptionUtilities.CheckArgumentNotNull(selectedPaths, "selectedPaths");

            var collection = valueToSpan as QueryCollectionValue;

            if (collection == null)
            {
                return valueToSpan;
            }

            // split each span path into a string array, which we can efficiently analyze later without 
            // having to deal with string parsing all the time
            var identityMap = new Dictionary<QueryStructuralValue, QueryStructuralValue>();

            var result = this.CloneCollectionValue(identityMap, collection);

            foreach (var spanPath in expandedPaths)
            {
                var splitPath = spanPath.Split('.');
                foreach (var item in collection.Elements)
                {
                    this.ExpandRelated(identityMap, item, splitPath, 0, expandedPaths, selectedPaths);
                }
            }

            return result;
        }
        /// <summary>
        /// Sets the given values on the given structural value instance
        /// </summary>
        /// <param name="queryValue">The instance to set the values on</param>
        /// <param name="namedValues">The values to set</param>
        public void UpdateValues(QueryValue queryValue, IEnumerable<NamedValue> namedValues)
        {
            ExceptionUtilities.CheckArgumentNotNull(queryValue, "queryValue");
            ExceptionUtilities.CheckArgumentNotNull(namedValues, "namedValues");

            this.unusedNamedValuePaths = new List<string>(namedValues.Select(s => s.Name).ToArray());

            var queryStructuralValue = queryValue as QueryStructuralValue;
            if (queryStructuralValue != null)
            {
                this.UpdateValues(queryStructuralValue, namedValues, null);
            }
            else
            {
                var queryCollectionValue = queryValue as QueryCollectionValue;
                ExceptionUtilities.CheckObjectNotNull(queryCollectionValue, "Can only update QueryValues of Collection or Structural type not '{0}'", queryValue.Type);
                this.UpdateValues(queryCollectionValue, namedValues);
            }

            var errorStringBuilder = new StringBuilder();
            foreach (NamedValue unusedNamedValue in namedValues.Where(nv => this.unusedNamedValuePaths.Contains(nv.Name)))
            {
                errorStringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "{0}={1}", unusedNamedValue.Name, Convert.ToString(unusedNamedValue.Value, CultureInfo.InvariantCulture)));
            }

            if (errorStringBuilder.Length > 0)
            {
                throw new TaupoInfrastructureException("All properties have not been set:\r\n" + errorStringBuilder.ToString());
            }
        }
        /// <summary>
        /// Gets the expected query value for the action request
        /// </summary>
        /// <param name="initialExpectedResults">Initial expected values for an action</param>
        /// <param name="parameterValues">Parameter values for the action</param>
        /// <returns>A query Value that is the expected value</returns>
        public QueryValue GetExpectedQueryValue(QueryValue initialExpectedResults, params QueryValue[] parameterValues)
        {
            ExceptionUtilities.CheckArgumentNotNull(initialExpectedResults, "initialExpectedResults");
            ExceptionUtilities.Assert(parameterValues.Length == 1, "There must be only one parameter that is passed in");

            return parameterValues[0];
        }
        private bool WriteErrorIfNotNull(string propertyPath, QueryValue queryValue)
        {
            if (!queryValue.IsNull)
            {
                this.errors.Add(string.Format(CultureInfo.InvariantCulture, "Error: expected null value for propertyPath '{0}' instead recieved '{1}'", propertyPath, queryValue.ToString()));
                return true;
            }

            return false;
        }
Example #5
0
        internal void SetNavigateResult(AssociationType associationType, AssociationEnd toEnd, QueryValue result)
        {
            if (!this.navigateResultLookup.ContainsKey(associationType))
            {
                this.navigateResultLookup.Add(associationType, new Dictionary<AssociationEnd, QueryValue>());
            }

            Dictionary<AssociationEnd, QueryValue> lookupBasedOnEnd = this.navigateResultLookup[associationType];
            lookupBasedOnEnd[toEnd] = result;
        }
        /// <summary>
        /// Validates a payload with the given root element against the given expected value
        /// </summary>
        /// <param name="rootElement">The root element of the payload</param>
        /// <param name="expectedValue">The expected value</param>
        public void Validate(ODataPayloadElement rootElement, QueryValue expectedValue)
        {
            ExceptionUtilities.CheckArgumentNotNull(rootElement, "rootElement");
            ExceptionUtilities.CheckArgumentNotNull(expectedValue, "expectedValue");
            ExceptionUtilities.CheckAllRequiredDependencies(this);

            this.Assert.IsNull(expectedValue.EvaluationError, string.Format(CultureInfo.InvariantCulture, "Query evaluation error: {0}", expectedValue.EvaluationError));

            var visitor = new PayloadDataValidatingVisitor(this);
            visitor.Validate(rootElement, expectedValue);
        }
        private void ExpandRelated(Dictionary<QueryStructuralValue, QueryStructuralValue> identityMap, QueryValue item, string[] splitPath, int position, IEnumerable<string> expandedPath, IEnumerable<string> selectedPath)
        {
            QueryStructuralValue qsv = item as QueryStructuralValue;
            if (qsv == null)
            {
                return;
            }

            if (position >= splitPath.Length)
            {
                return;
            }

            var memberName = splitPath[position];
            var member = qsv.Type.Properties.SingleOrDefault(c => c.Name == memberName);
            if (member == null)
            {
                return;
            }

            // do not expand if the selected paths don't contain the expand value
            if (selectedPath.Count() > 0 && !selectedPath.Contains(member.Name))
            {
                return;
            }

            var clone = this.CloneStructuralValue(identityMap, qsv);

            if (member.PropertyType is QueryCollectionType)
            {
                var oldValue = qsv.GetCollectionValue(memberName);

                clone.SetValue(memberName, this.CloneCollectionValue(identityMap, oldValue));
                if (!oldValue.IsNull)
                {
                    foreach (var e in oldValue.Elements)
                    {
                        this.ExpandRelated(identityMap, e, splitPath, position + 1, expandedPath, selectedPath);
                    }
                }
            }
            else if (member.PropertyType is QueryStructuralType)
            {
                var oldValue = qsv.GetStructuralValue(memberName);
                var newValue = this.CloneStructuralValue(identityMap, oldValue);
                clone.SetValue(memberName, newValue);
                this.ExpandRelated(identityMap, oldValue, splitPath, position + 1, expandedPath, selectedPath);
            }
        }
        /// <summary>
        /// Validates the data in the response payload based on the expected query value
        /// </summary>
        /// <param name="requestUri">The request uri</param>
        /// <param name="response">The response</param>
        /// <param name="expected">The expected query value</param>
        /// <param name="maxProtocolVersion">The max protocol version of the service</param>
        public void ValidateResponsePayload(ODataUri requestUri, ODataResponse response, QueryValue expected, DataServiceProtocolVersion maxProtocolVersion)
        {
            ExceptionUtilities.CheckObjectNotNull(requestUri, "requestUri");
            ExceptionUtilities.CheckObjectNotNull(response, "response");
            ExceptionUtilities.CheckObjectNotNull(expected, "expected");

            var expectedVersion = response.GetDataServiceVersion();
            this.Validator.ExpectedProtocolVersion = expectedVersion;
            this.Validator.ExpectedPayloadOptions = ODataPayloadOptions.None;

            string contentType;
            if (response.Headers.TryGetValue(HttpHeaders.ContentType, out contentType))
            {
                var strategy = this.FormatSelector.GetStrategy(contentType, requestUri);
                ExceptionUtilities.CheckObjectNotNull(strategy, "Could not get strategy for content type '{0}'", contentType);
                this.Validator.PrimitiveValueComparer = strategy.GetPrimitiveComparer();

                this.Validator.ExpectedPayloadOptions = this.ProtocolImplementationDetails.GetExpectedPayloadOptions(contentType, expectedVersion, requestUri);
            }

            this.ValidateAndPrintInfoOnError(requestUri, response.RootElement, expected);
        }
        /// <summary>
        /// Gets the expected query value for the action request
        /// </summary>
        /// <param name="initialExpectedResults">Initial expected values for an action</param>
        /// <param name="parameterValues">Parameter values for the action</param>
        /// <returns>A query Value that is the expected value</returns>
        public QueryValue GetExpectedQueryValue(QueryValue initialExpectedResults, params QueryValue[] parameterValues)
        {
            ExceptionUtilities.CheckArgumentNotNull(initialExpectedResults, "initialExpectedResults");
            if (initialExpectedResults.IsNull || this.ReturnProperty == null)
            {
                return initialExpectedResults.Type.NullValue;
            }

            QueryStructuralValue initialStructuralValue = initialExpectedResults as QueryStructuralValue;
            QueryCollectionValue initialCollectionValue = initialExpectedResults as QueryCollectionValue;
            if (initialStructuralValue != null)
            {
                return initialStructuralValue.GetValue(this.ReturnProperty);
            }
            else
            {
                ExceptionUtilities.CheckArgumentNotNull(initialCollectionValue, "Unsupported initialExpectedResults type.");
                if (initialCollectionValue.Elements.Count > 0)
                {
                    // Sort the results by the keys
                    var queryEntityType = (QueryEntityType)initialCollectionValue.Type.ElementType;
                    var sortedList = initialCollectionValue.Elements.Select(r => (QueryStructuralValue)r).ToList();
                    foreach (var key in queryEntityType.EntityType.AllKeyProperties)
                    {
                        sortedList = sortedList.OrderBy(r => r.GetScalarValue(key.Name).Value).ToList();
                    }

                    var firstItemValue = (QueryStructuralValue)sortedList.First();
                    ExceptionUtilities.CheckArgumentNotNull(firstItemValue, "firstItemValue");
                    return firstItemValue.GetValue(this.ReturnProperty);
                }
                else
                {
                    return initialCollectionValue.Type.ElementType.NullValue;
                }
            }
        }
        /// <summary>
        /// Gets the expected query value for the action request
        /// </summary>
        /// <param name="initialExpectedResults">Initial expected values for an action</param>
        /// <param name="parameterValues">Parameter values for the action</param>
        /// <returns>A query Value that is the expected value</returns>
        public QueryValue GetExpectedQueryValue(QueryValue initialExpectedResults, params QueryValue[] parameterValues)
        {
            ExceptionUtilities.CheckArgumentNotNull(initialExpectedResults, "initialExpectedResults");

            QueryStructuralValue initialStructuralValue = initialExpectedResults as QueryStructuralValue;
            ExceptionUtilities.CheckArgumentNotNull(initialStructuralValue, "initialStructuralValue");

            QueryScalarValue initialScalarValue = initialStructuralValue.GetScalarValue(this.IntegerProperty);
            ExceptionUtilities.CheckArgumentNotNull(initialScalarValue, "initialScalarValue");

            int intPropertyValue = (int)initialScalarValue.Value;
            ExceptionUtilities.CheckArgumentNotNull(intPropertyValue, "intPropertyValue");

            if (intPropertyValue != int.MaxValue)
            {
                initialStructuralValue.SetPrimitiveValue(this.IntegerProperty, intPropertyValue + 1);
            }
            else
            {
                initialStructuralValue.SetPrimitiveValue(this.IntegerProperty, 0);
            }

            return initialStructuralValue;
        }
Example #11
0
 /// <summary>
 /// Adds entities that are materialized in the given QueryValue into list of currently visible entities.
 /// </summary>
 /// <param name="value">QueryValue representing result of a query.</param>
 /// <param name="spanPaths">Span paths for the query.</param>
 protected void UpdateVisibleEntitiesGraph(QueryValue value, string[] spanPaths)
 {
     this.UpdateVisibleEntitiesGraphForQueryValue(value, string.Empty, spanPaths);
 }
        private string VerifyExpected(ODataRequest request, ODataResponse response, QueryValue expected, HttpStatusCode expectedStatusCode, string expectedETag)
        {
            if (expected.IsNull)
            {
                ExceptionUtilities.Assert(response.StatusCode == HttpStatusCode.NoContent, "Expected status code {0} actual {1}", HttpStatusCode.NoContent, response.StatusCode);
            }
            else
            {
                this.VerificationServices.ValidateResponsePayload(request.Uri, response, expected, this.maxProtocolVersion);
                ExceptionUtilities.Assert(response.StatusCode == expectedStatusCode, "Expected status code {0} actual {1}", expectedStatusCode, response.StatusCode);

                // Verify that there are no next links in a response payload to an action with SDP enabled
                var entitySetInstance = response.RootElement as EntitySetInstance;
                if (entitySetInstance != null)
                {
                    this.Assert(entitySetInstance.NextLink == null, "Should be no next links in response", request, response);
                }

                expectedETag = this.CalculateExpectedETag(expected);
            }

            return expectedETag;
        }
 // Math
 private QueryValue EvaluateMathMethod(string functionName, QueryType type, QueryValue[] arguments)
 {
     ValidateArguments(functionName, type, 1, arguments);
     return this.EvaluateMethod((QueryScalarType)type, typeof(Math), functionName, (QueryScalarValue)arguments[0]);
 }
 // String
 private QueryValue EvaluateStringMethod(string functionName, QueryType type, QueryValue[] arguments)
 {
     ValidateArguments(functionName, type, null, arguments);
     return this.EvaluateMethod((QueryScalarType)type, typeof(string), functionName, arguments.Cast<QueryScalarValue>().ToArray());
 }
 /// <summary>
 /// Helper method for recursively validating elements and wrapping exceptions from the assertion handler.
 /// If validation fails, the exception type will be maintained, but it will be wrapped in an exception with the given message.
 /// </summary>
 /// <param name="element">The element to validate</param>
 /// <param name="value">The expected value</param>
 /// <param name="errorMessage">The error message template to wrap any exceptions in</param>
 /// <param name="args">The arguments to the error message template</param>
 private void RecurseWithMessage(ODataPayloadElement element, QueryValue value, string errorMessage, params object[] args)
 {
     using (this.parent.Assert.WithMessage(errorMessage, args))
     {
         this.Recurse(element, value);
     }
 }
            /// <summary>
            /// Validates a payload with the given root element against the given expected value
            /// </summary>
            /// <param name="rootElement">The root element of the payload</param>
            /// <param name="expected">The expected value</param>
            public void Validate(ODataPayloadElement rootElement, QueryValue expected)
            {
                ExceptionUtilities.CheckArgumentNotNull(rootElement, "rootElement");
                ExceptionUtilities.CheckArgumentNotNull(expected, "expected");

                this.expectedValueStack.Push(expected);
                this.payloadStack.Push(rootElement);

                rootElement.Accept(this);
            }
        /// <summary>
        /// Validates the arguments.
        /// </summary>
        /// <param name="functionName">Name of the function.</param>
        /// <param name="type">The query type.</param>
        /// <param name="expectedCount">The expected argument count.</param>
        /// <param name="arguments">The arguments.</param>
        private static void ValidateArguments(string functionName, QueryType type, int? expectedCount, QueryValue[] arguments)
        {
            ExceptionUtilities.CheckArgumentNotNull(functionName, "functionName");
            ExceptionUtilities.CheckArgumentNotNull(type, "type");
            ExceptionUtilities.CheckArgumentNotNull(arguments, "arguments");

            ExceptionUtilities.Assert(type is QueryScalarType, "Type for function '{0}' was not a scalar type", functionName);
            ExceptionUtilities.Assert(arguments.All(a => a is QueryScalarValue), "Arguments for function '{0}' were not all scalar", functionName);

            if (expectedCount.HasValue)
            {
                ExceptionUtilities.Assert(arguments.Length == expectedCount.Value, "Number of arguments for function '{0}' was wrong. Expected {1} but got {2}", functionName, expectedCount.Value, arguments.Length);
            }
        }
 /// <summary>
 /// This function returns a multidimensional array containing a list of all defined variables,
 /// be them environment, server or user-defined variables, within the scope that get_defined_vars() is called.
 /// </summary>
 /// <param name="locals">The table of defined variables.</param>
 /// <returns></returns>
 public static PhpArray get_defined_vars(QueryValue <LocalVariables> locals) => locals.Value.Locals.DeepCopy();
        /// <summary>
        /// Import variables into the current variables table from an array.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="localsData">The table of defined variables.</param>
        /// <param name="vars">The <see cref="PhpArray"/> containing names of variables and values to be assigned to them.</param>
        /// <param name="type">The type of the extraction.</param>
        /// <param name="prefix">The prefix (can be a <B>null</B> reference) of variables names.</param>
        /// <returns>The number of variables actually affected by the extraction.</returns>
        /// <exception cref="PhpException"><paramref name="type"/> is invalid.</exception>
        /// <exception cref="PhpException"><paramref name="vars"/> is a <B>null</B> reference.</exception>
        /// <exception cref="InvalidCastException">Some key of <paramref name="localsData"/> is not type of <see cref="string"/>.</exception>
        public static int extract(Context ctx, QueryValue <LocalVariables> localsData, PhpArray vars, ExtractType type = ExtractType.Overwrite, string prefix = null)
        {
            if (vars == null)
            {
                //PhpException.ArgumentNull("vars");
                //return 0;
                throw new ArgumentNullException(nameof(vars));
            }

            if (vars.Count == 0)
            {
                return(0);
            }

            var locals = localsData.Value.Locals;

            // unfortunately, type contains flags are combined with enumeration:
            bool refs = (type & ExtractType.Refs) != 0;

            type &= ExtractType.NonFlags;

            //
            //
            //
            int extracted_count = 0;
            var enumerator      = vars.GetFastEnumerator();

            while (enumerator.MoveNext())
            {
                var name = enumerator.CurrentKey.ToString();
                if (string.IsNullOrEmpty(name) && type != ExtractType.PrefixInvalid)
                {
                    continue;
                }

                switch (type)
                {
                case ExtractType.Overwrite:

                    // anything is overwritten:

                    break;

                case ExtractType.Skip:

                    // skips existing name:
                    if (locals.ContainsKey(name))
                    {
                        continue;
                    }

                    break;

                case ExtractType.IfExists:

                    // skips nonexistent name:
                    if (!locals.ContainsKey(name))
                    {
                        continue;
                    }

                    break;

                case ExtractType.PrefixAll:

                    // prefix anything:
                    name = string.Concat(prefix, "_", name);

                    break;

                case ExtractType.PrefixInvalid:

                    // prefixes invalid, others are overwritten:
                    if (!PhpVariable.IsValidName(name))
                    {
                        name = string.Concat(prefix, "_", name);
                    }

                    break;

                case ExtractType.PrefixSame:

                    // prefixes existing, others are overwritten:
                    if (locals.ContainsKey(name))
                    {
                        name = string.Concat(prefix, "_", name);
                    }

                    break;

                case ExtractType.PrefixIfExists:

                    // prefixes existing, others are skipped:
                    if (locals.ContainsKey(name))
                    {
                        name = string.Concat(prefix, "_", name);
                    }
                    else
                    {
                        continue;
                    }

                    break;

                default:
                    throw new ArgumentException(nameof(type));
                    //PhpException.InvalidArgument("type", LibResources.GetString("arg_invalid_value"));
                    //return 0;
                }

                // invalid names are skipped:
                if (PhpVariable.IsValidName(name))
                {
                    // write the value to locals:
                    if (refs)
                    {
                        // makes a reference and writes it back (deep copy is not necessary, "no duplicate pointers" rule preserved):
                        locals.SetItemAlias(new IntStringKey(name), enumerator.CurrentValueAliased);
                    }
                    else
                    {
                        // deep copy the value and write into locals
                        locals.SetItemValue(new IntStringKey(name), enumerator.CurrentValue.GetValue().DeepCopy());
                    }

                    extracted_count++;
                }
            }

            //
            return(extracted_count);
        }
        // Token: 0x06000227 RID: 551 RVA: 0x0000D064 File Offset: 0x0000B264
        public void queryDB(Dictionary <string, QueryValue> dicts)
        {
            if (this.qb == null || dicts == null || dicts.Count < 0)
            {
                return;
            }
            DataTable dataTable = new DataTable();

            dataTable.Columns.Add("permanentUserId");
            dataTable.Columns.Add("username");
            dataTable.Columns.Add("identityId");
            dataTable.Columns.Add("phoneNum");
            dataTable.Columns.Add("address");
            dataTable.Columns.Add("usertype");
            dataTable.Columns.Add("priceType");
            dataTable.Columns.Add("paytype");
            dataTable.Columns.Add("pursuitTimes");
            dataTable.Columns.Add("pursuitNum");
            dataTable.Columns.Add("paynum");
            dataTable.Columns.Add("time");
            dataTable.Columns.Add("operator");
            List <string> list = new List <string>();
            string        sqlStrForQueryUser = this.getSqlStrForQueryUser(dicts);
            DataTable     dataTable2;

            if (sqlStrForQueryUser != "")
            {
                foreach (string key in dicts.Keys)
                {
                    QueryValue queryValue = dicts[key];
                    this.db.AddParameter(key, queryValue.Value);
                }
                dataTable2 = this.db.ExecuteQuery("SELECT * FROM usersTable WHERE " + sqlStrForQueryUser + " ORDER BY createTime ASC");
                if (dataTable2 != null && dataTable2.Rows != null && dataTable2.Rows.Count > 0)
                {
                    foreach (object obj in dataTable2.Rows)
                    {
                        DataRow dataRow = (DataRow)obj;
                        list.Add(dataRow["permanentUserId"].ToString());
                    }
                }
            }
            string text = "";

            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    string text2 = list[i];
                    this.db.AddParameter("permanentUserId" + text2, text2);
                    if (i != 0)
                    {
                        text += " OR ";
                    }
                    text = text + "permanentUserId=@permanentUserId" + text2;
                }
            }
            else if (list.Count == 0 && dicts.Count != 0 && sqlStrForQueryUser != "")
            {
                this.qb.initDGV(this.initDGV(dataTable));
                return;
            }
            TimeSpan timeSpan  = this.qb.getStartDT() - WMConstant.DT1970;
            TimeSpan timeSpan2 = this.qb.getEndDT() - WMConstant.DT1970;

            this.db.AddParameter("createTimeStart", string.Concat(timeSpan.TotalSeconds));
            this.db.AddParameter("createTimeEnd", string.Concat(timeSpan2.TotalSeconds));
            this.db.AddParameter("operateType", "3");
            string sqlKeys = this.getQueryConditionEntitys()[7].SqlKeys;

            if (dicts.ContainsKey(sqlKeys))
            {
                QueryValue queryValue2 = dicts[sqlKeys];
                this.db.AddParameter(sqlKeys, queryValue2.Value);
                string text3 = text;
                text = string.Concat(new string[]
                {
                    text3,
                    (text == "") ? "" : (" " + queryValue2.AndOr + " "),
                    sqlKeys,
                    queryValue2.Oper,
                    "@",
                    sqlKeys
                });
            }
            dataTable2 = this.db.ExecuteQuery("SELECT * FROM userCardLog WHERE " + ((text == "") ? "" : ("(" + text + ") AND ")) + "time>=@createTimeStart AND time<=@createTimeEnd AND operateType=@operateType ORDER BY operationId ASC");
            if (dataTable2 != null && dataTable2.Rows != null && dataTable2.Rows.Count > 0)
            {
                foreach (object obj2 in dataTable2.Rows)
                {
                    DataRow dataRow2 = (DataRow)obj2;
                    this.db.AddParameter("permanentUserId", dataRow2["permanentUserId"].ToString());
                    DataRow dataRow3 = this.db.ExecuteRow("SELECT * FROM usersTable WHERE permanentUserId=@permanentUserId");
                    if (dataRow3 != null)
                    {
                        this.db.AddParameter("typeId", dataRow3["userTypeId"].ToString());
                        DataRow dataRow4 = this.db.ExecuteRow("SELECT * FROM userTypeTable WHERE typeId=@typeId");
                        this.db.AddParameter("priceConsistId", dataRow3["userPriceConsistId"].ToString());
                        DataRow dataRow5 = this.db.ExecuteRow("SELECT * FROM priceConsistTable WHERE priceConsistId=@priceConsistId");
                        this.db.AddParameter("userCardLogId", dataRow2["operationId"].ToString());
                        DataRow dataRow6 = this.db.ExecuteRow("SELECT * FROM payLogTable WHERE userCardLogId=@userCardLogId");
                        if (dataRow4 != null && dataRow5 != null && dataRow6 != null)
                        {
                            DataRow dataRow7 = dataTable.NewRow();
                            dataRow7["permanentUserId"] = dataRow3["permanentUserId"].ToString();
                            dataRow7["username"]        = dataRow3["username"].ToString();
                            dataRow7["identityId"]      = dataRow3["identityId"].ToString();
                            dataRow7["phoneNum"]        = dataRow3["phoneNum"].ToString();
                            dataRow7["address"]         = dataRow3["address"].ToString();
                            dataRow7["usertype"]        = dataRow4["userType"].ToString();
                            dataRow7["priceType"]       = dataRow5["priceConstistName"].ToString();
                            dataRow7["paytype"]         = WMConstant.PayTypeList[(int)(checked ((IntPtr)(Convert.ToInt64(dataRow6["payType"]))))];
                            dataRow7["pursuitTimes"]    = dataRow2["consumeTimes"].ToString();
                            dataRow7["pursuitNum"]      = dataRow6["pursuitNum"].ToString();
                            dataRow7["paynum"]          = dataRow6["totalPrice"].ToString();
                            dataRow7["time"]            = WMConstant.DT1970.AddSeconds(ConvertUtils.ToDouble(dataRow2["time"].ToString())).ToString("yyyy-MM-dd HH:mm:ss");
                            dataRow7["operator"]        = dataRow2["operator"].ToString();
                            dataTable.Rows.Add(dataRow7);
                            dataTable.AcceptChanges();
                        }
                    }
                }
            }
            this.qb.initDGV(this.initDGV(dataTable));
        }
        /// <summary>
        /// Verifies the descriptor after execute.
        /// </summary>
        /// <param name="continuation">The continuation.</param>
        /// <param name="dataContext">The data context.</param>
        /// <param name="entityPayloads">The list of entities</param>
        /// <param name="expectedValue">The expected value.</param>
        protected void VerifyDescriptorAfterExecute(IAsyncContinuation continuation, DataServiceContext dataContext, IEnumerable <object> entityPayloads, QueryValue expectedValue)
        {
            // If no streams were generated as part of the test initialization then this block of verification is needed
            if (this.SkipGenerateNamedStream)
            {
                continuation.Continue();
            }
            else
            {
                object[] entities = entityPayloads.ToArray();
                if (this.DataProviderSettings.UsePayloadDrivenVerification)
                {
                    expectedValue = this.baselineQueryValue;
                }

                var expectedEntities = expectedValue as QueryCollectionValue;
                QueryStructuralValue element;

                if (expectedEntities == null)
                {
                    continuation.Continue();
                }
                else
                {
                    AsyncHelpers.AsyncForEach(
                        expectedEntities.Elements.ToList(),
                        continuation,
                        (qv, entityContinuation) =>
                    {
                        // NOTE: The results could be a list of AnonTypes at which point these wouldn't be have descriptors so
                        // no need to verify
                        element = qv as QueryStructuralValue;

                        var queryEntityType = element.Type as QueryEntityType;
                        if (queryEntityType == null)
                        {
                            entityContinuation.Continue();
                        }
                        else
                        {
                            var queryEntityValue        = element as QueryEntityValue;
                            QueryKeyStructuralValue key = queryEntityValue.Key();

                            // This handles the expand scenario (Orders(1)?$expand=Customer) where the entity in the list doesn't have a corresponding QueryStructuralValue
                            object entity = entities.Where(upe => queryEntityType.ClrType.IsAssignableFrom(upe.GetType()) && queryEntityType.GetEntityInstanceKey(upe).Equals(key)).FirstOrDefault();

                            if (entity == null)
                            {
                                entityContinuation.Continue();
                            }
                            else
                            {
                                EntityDescriptor ed  = dataContext.GetEntityDescriptor(entity);
                                var streamProperties = queryEntityType.Properties.Where(p => p.IsStream()).ToList();          // intentionally include the default stream
                                int expectedStreamDescriptorCount = streamProperties.Count(p => p.Name != AstoriaQueryStreamType.DefaultStreamPropertyName);
                                this.Assert.AreEqual(expectedStreamDescriptorCount, ed.StreamDescriptors.Count, "Entity descriptor had unexpected number of stream descriptors");

                                AsyncHelpers.AsyncForEach(
                                    streamProperties,
                                    entityContinuation,
                                    (streamProperty, streamDescriptorContinuation) =>
                                {
                                    if (streamProperty.Name == AstoriaQueryStreamType.DefaultStreamPropertyName)
                                    {
                                        this.VerifyDefaultStream(dataContext, element, ed, streamDescriptorContinuation);
                                    }
                                    else
                                    {
                                        this.VerifyNamedStreams(dataContext, element, streamProperty, ed, streamDescriptorContinuation);
                                    }
                                });
                            }
                        }
                    });
                }
            }
        }
        public void ExecuteUriAndCompare <TResult>(IAsyncContinuation continuation, bool isAsync, IQueryable <TResult> query, string uriString, QueryValue expectedValue, DataServiceContext dataContext, ExpectedClientErrorBaseline clientExpectedError)
        {
            this.isAsynchronous = isAsync;
            this.ExecuteQueryAction(
                continuation,
                expectedValue,
                dataContext,
                clientExpectedError,
                delegate(List <object> entityPayloads, IAsyncContinuation continuation2)
            {
                AsyncHelpers.CatchErrors(
                    continuation2,
                    () =>
                {
                    this.Logger.WriteLine(LogLevel.Verbose, "Executing query, async:{0}, Uri:{1}:", isAsync, dataContext.BaseUri + "/" + uriString);

                    Uri builtUri = new Uri(dataContext.BaseUri + "/" + uriString);

                    EventHandler <SendingRequest2EventArgs> sendingRequest = delegate(object sender, SendingRequest2EventArgs args)
                    {
                        HttpRequestMessage request = ((HttpClientRequestMessage)args.RequestMessage).HttpRequestMessage;
                        this.VerifyCommonExecuteHeaders(request.Headers);
                    };

                    dataContext.SendingRequest2 += sendingRequest;

                    dataContext.Execute(
                        continuation2,
                        isAsync,
                        builtUri,
                        delegate(IEnumerable <TResult> results)
                    {
                        this.Compare(expectedValue, () => results, dataContext);

                        if (entityPayloads.Count > 0)
                        {
                            this.VerifyDescriptorAfterExecute(continuation2, dataContext, entityPayloads, expectedValue);
                        }
                        else
                        {
                            dataContext.SendingRequest2 -= sendingRequest;

                            continuation2.Continue();
                        }
                    });
                });
            });
        }
        /// <summary>
        /// Executes the given expression asynchronously and compares the result to a given expected value.
        /// </summary>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="continuation">The continuation.</param>
        /// <param name="isAsync">Determines if we execute async or not</param>
        /// <param name="query">Query to execute</param>
        /// <param name="expectedValue">The expected value.</param>
        /// <param name="dataContext">The data context.</param>
        /// <param name="clientExpectedError">Client Expected Error Information</param>
        public void ExecuteAndCompare <TResult>(IAsyncContinuation continuation, bool isAsync, IQueryable <TResult> query, QueryValue expectedValue, DataServiceContext dataContext, ExpectedClientErrorBaseline clientExpectedError)
        {
            this.isAsynchronous = isAsync;
            this.ExecuteQueryAction(
                continuation,
                expectedValue,
                dataContext,
                clientExpectedError,
                delegate(List <object> entityPayloads, IAsyncContinuation continuation2)
            {
                AsyncHelpers.CatchErrors(
                    continuation2,
                    () =>
                {
                    var dataServiceQuery = (DataServiceQuery <TResult>)query;
                    this.Logger.WriteLine(LogLevel.Verbose, "Executing query async:{0}, Expression:{1}:", isAsync, dataServiceQuery.Expression);

                    dataServiceQuery.Execute(
                        continuation2,
                        isAsync,
                        delegate(IEnumerable <TResult> results)
                    {
                        this.Compare(expectedValue, () => results, dataContext);

                        if (entityPayloads.Count > 0)
                        {
                            this.VerifyDescriptorAfterExecute(continuation2, dataContext, entityPayloads, expectedValue);
                        }
                        else
                        {
                            continuation2.Continue();
                        }
                    });
                });
            });
        }
Example #24
0
 /// <summary>
 /// Fixes up references added via Full span.
 /// </summary>
 /// <param name="value">QueryValue representing result of a query.</param>
 /// <param name="spanPaths">Span paths for the query.</param>
 protected void FixupReferencesBasedOnSpanPaths(QueryValue value, string[] spanPaths)
 {
     this.FixupReferencesBasedOnSpanPaths(value, null, null, string.Empty, spanPaths);
 }
Example #25
0
        /// <summary>
        /// Helper method for walking down a query value tree and invoking a callback on all structural values
        /// </summary>
        /// <param name="value">The value to visit</param>
        /// <param name="callback">The callback for structural values</param>
        /// <returns>The result of visiting the value</returns>
        private QueryValue VisitEntityValues(QueryValue value, Func<QueryStructuralValue, QueryStructuralValue> callback)
        {
            ExceptionUtilities.CheckArgumentNotNull(value, "value");
            ExceptionUtilities.CheckArgumentNotNull(callback, "callback");

            var collection = value as QueryCollectionValue;
            if (collection != null && collection.Type.ElementType is QueryEntityType)
            {
                return this.VisitEntityValues(collection, callback);  
            }

            var structural = value as QueryStructuralValue;
            if (structural != null && structural.Type is QueryEntityType && !structural.IsNull)
            {
                return callback(structural);
            }

            return value;
        }
        private QueryValue CloneValue(Dictionary<QueryStructuralValue, QueryStructuralValue> identityMap, QueryValue value)
        {
            // no need to clone scalar values
            if (value is QueryScalarValue)
            {
                return value;
            }

            if (value is AstoriaQueryStreamValue)
            {
                return value;
            }

            QueryStructuralValue qsv = value as QueryStructuralValue;
            if (qsv != null)
            {
                return this.CloneStructuralValue(identityMap, qsv);
            }

            QueryCollectionValue qcv = value as QueryCollectionValue;
            ExceptionUtilities.Assert(qcv != null, "Expected collection value.");

            return this.CloneCollectionValue(identityMap, qcv);
        }
Example #27
0
 public static bool IsDynamicPropertyValue(this QueryValue value)
 {
     ExceptionUtilities.CheckArgumentNotNull(value, "value");
     return(value.Annotations.OfType <IsDynamicPropertyValueAnnotation>().Any());
 }
 private QueryValue EvaluateProperty(string functionName, QueryType type, QueryValue[] arguments)
 {
     ValidateArguments(functionName, type, 1, arguments);
     return this.EvaluateProperty((QueryScalarType)type, functionName, (QueryScalarValue)arguments[0]);
 }
        /// <summary>
        /// Evaluates member property of a spatial instance.
        /// </summary>
        /// <param name="instance">The instance of query value object</param>
        /// <param name="resultType">The property result type.</param>
        /// <param name="memberPropertyName">The member property name to evaluate.</param>
        /// <returns>
        /// Query value which is the result of method evaluation.
        /// </returns>
        public override QueryValue EvaluateMemberProperty(QueryValue instance, QueryType resultType, string memberPropertyName)
        {
            if (this.IsSpatialType((IQueryClrType)instance.Type))
            {
                var clrInstance = ((QueryScalarValue)instance).Value;
                if (clrInstance == null)
                {
                    var nullValue = resultType.NullValue;
                    nullValue.EvaluationError = new QueryError("Cannot access member property on a null instance");
                    return nullValue;
                }

                var clrType = clrInstance.GetType();
                while (!clrType.IsPublic())
                {
                    clrType = clrType.GetBaseType();
                }

                var property = clrType.GetProperty(memberPropertyName, true, false);
                ExceptionUtilities.CheckObjectNotNull(property, "Could not find property");

                var propertyValue = property.GetValue(clrInstance, null);
                if (propertyValue == null)
                {
                    return resultType.NullValue;
                }

                var collectionType = resultType as QueryCollectionType;
                if (collectionType != null)
                {
                    var enumerable = propertyValue as IEnumerable;
                    ExceptionUtilities.CheckObjectNotNull(enumerable, "Collection value must be ienumerable. Value was '{0}'", propertyValue);

                    var elementType = (QueryScalarType)collectionType.ElementType;
                    return collectionType.CreateCollectionWithValues(enumerable.Cast<object>().Select(o => (QueryValue)elementType.CreateValue(o)));
                }
                else
                {
                    return ((QueryScalarType)resultType).CreateValue(propertyValue);
                }
            }

            return base.EvaluateMemberProperty(instance, resultType, memberPropertyName);
        }
 /// <summary>
 /// Helper method for recursively validating elements and catching exceptions from the assertion handler
 /// </summary>
 /// <param name="element">The element to validate</param>
 /// <param name="value">The expected value</param>
 /// <returns>Null if not exception was caught, or the caught exception</returns>
 private TestFailedException RecurseAndCatch(ODataPayloadElement element, QueryValue value)
 {
     this.expectedValueStack.Push(value);
     this.payloadStack.Push(element);
     try
     {
         this.Recurse(element, value);
         return null;
     }
     catch (TestFailedException e)
     {
         return e;
     }
     finally
     {
         this.expectedValueStack.Pop();
         this.payloadStack.Pop();
     }
 }
Example #31
0
 static Bool RuntimeQueryValue(QueryValue input) => Undefined.IsDefined(input);
 private void Recurse(ODataPayloadElement element, QueryValue value)
 {
     this.expectedValueStack.Push(value);
     this.payloadStack.Push(element);
     try
     {
         element.Accept(this);
     }
     finally
     {
         this.expectedValueStack.Pop();
         this.payloadStack.Pop();
     }
 }
        /// <summary>
        /// Retrieves a value of a constant.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="callerCtx">type of caller class. Used to resolve reserved type names if used in <paramref name="name"/>.</param>
        /// <param name="name">The name of the constant.</param>
        /// <param name="this">Optional. Reference to <c>$this</c> object. Used to resolve <c>static::</c> type reference.</param>
        /// <returns>The value.</returns>
        public static PhpValue constant(Context ctx, [ImportCallerClass] RuntimeTypeHandle callerCtx, QueryValue <ThisVariable> @this, string name)
        {
            if (!TryGetConstant(ctx, callerCtx, @this.Value.This, name, out var value))
            {
                PhpException.Throw(PhpError.Warning, Core.Resources.ErrResources.constant_not_found, name);
            }

            //
            return(value);
        }
            private void VerifyTypeName(QueryValue value, string actualTypeName, string message)
            {
                var type = value.Type;
                string expectedTypeName = this.GetExpectedTypeName(type);

                bool expectTypeName = false;
                if (this.parent.ExpectedPayloadOptions.HasFlag(ODataPayloadOptions.IncludeTypeNames))
                {
                    expectTypeName = true;

                    // if type names are omitted within multivalues, we need to figure out if we're within one
                    if (this.parent.ExpectedPayloadOptions.HasFlag(ODataPayloadOptions.OmitTypeNamesWithinMultiValues))
                    {
                        bool inMultiValue = false;
                        if (this.payloadStack.Count > 2)
                        {
                            var elementType = this.payloadStack.ElementAt(2).ElementType;
                            inMultiValue = elementType == ODataPayloadElementType.ComplexMultiValueProperty || elementType == ODataPayloadElementType.PrimitiveMultiValueProperty;
                        }

                        if (inMultiValue)
                        {
                            var multivalue = (ITypedValue)this.payloadStack.ElementAt(1);
                            string multiValueElementName;
                            if (ODataUtilities.TryGetMultiValueElementTypeName(multivalue.FullTypeName, out multiValueElementName))
                            {
                                expectTypeName = expectedTypeName != multiValueElementName;
                            }
                        }
                    }

                    // if this is a primitive type, it may not have a type name
                    var primitiveType = type as QueryScalarType;
                    if (expectTypeName && primitiveType != null)
                    {
                        if (this.payloadStack.Count == 1)
                        {
                            // top-level raw $value payloads don't have a place to write the type name
                            expectTypeName = false;
                        }
                        else if (this.parent.ExpectedPayloadOptions.HasFlag(ODataPayloadOptions.OmitTypeNamesForAllPrimitives))
                        {
                            // no type name is expected for any un-structured primitive (JSON does not have a place for this, for instance)
                            // TODO: have a knob for services which choose not to write the type for spatial
                            expectTypeName = false;
                        }
                        else if (this.parent.ExpectedPayloadOptions.HasFlag(ODataPayloadOptions.OmitTypeNamesForStrings))
                        {
                            // string is the default type and is not always specified
                            var clrType = primitiveType as IQueryClrType;
                            ExceptionUtilities.CheckObjectNotNull(clrType, "Primitive type did not have a clr type. Type was: {0}", primitiveType);
                            expectTypeName = clrType.ClrType != typeof(string);
                        }
                    }

                    if (type is QueryClrSpatialType)
                    {
                        expectTypeName |= this.parent.ExpectedPayloadOptions.HasFlag(ODataPayloadOptions.AlwaysIncludeTypeNamesForSpatialPrimitives);
                    }
                }

                if (expectTypeName)
                {
                    // special cases for null values
                    var typedValue = this.payloadStack.Peek() as TypedValue;
                    if (typedValue != null && typedValue.IsNull)
                    {
                        if (!this.parent.ExpectedPayloadOptions.HasFlag(ODataPayloadOptions.IncludeTypeNamesForNullValues))
                        {
                            // if nulls are not typed, then do not expect it
                            expectTypeName = false;
                        }
                        else if (this.payloadStack.Count < 3)
                        {
                            // Astoria-ODataLib-Integration: For null top-level properties, ODataLib does not write the type attribute
                            expectTypeName = false;
                        }
                        else if (value.IsDynamicPropertyValue())
                        {
                            // dynamic nulls do not have type information, but if this is a sub-property of a complex type, then it will have a type name
                            var parentElement = this.payloadStack.ElementAt(2);
                            if (parentElement.ElementType == ODataPayloadElementType.EntityInstance)
                            {
                                expectTypeName = false;
                            }
                        }
                    }
                }

                if (expectTypeName)
                {
                    this.parent.Assert.AreEqual(expectedTypeName, actualTypeName, message);
                }
                else
                {
                    this.parent.Assert.IsNull(actualTypeName, "{0}. Unexpected type name '{1}' found.", message, actualTypeName);
                }
            }
Example #35
0
        private static QueryValue EnsureLastSegmentIsSingletonOrNull(QueryValue value)
        {
            QueryCollectionValue collection = value as QueryCollectionValue;
            if (collection != null)
            {
                if (collection.IsNull || collection.Elements.Count == 0)
                {
                    value = collection.Type.ElementType.NullValue;
                }
                else
                {
                    value = collection.Elements.Single();
                }
            }

            return value;
        }
        internal string CalculateExpectedETag(QueryValue expected)
        {
            if (!expected.IsNull)
            {
                QueryEntityType queryEntityType = expected.Type as QueryEntityType;
                if (queryEntityType != null)
                {
                    return this.LiteralConverter.ConstructWeakETag(expected as QueryStructuralValue);
                }
            }

            return null;
        }
Example #37
0
        private QueryValue ApplySelectAndExpand(ODataUri uri, QueryValue value)
        {
            // Note: this is applied on all URIs, and it is left up to the FixupPropertiesForExpand helper method
            // to skip cases where it is not an entity type
            var expandedPaths = uri.ExpandSegments.Select(s => this.UriConverter.ConcatenateSegments(s));
            value = this.VisitEntityValues(value, s => this.FixupPropertiesForExpand(s, expandedPaths));
            var collection = value as QueryCollectionValue;

            // since we remove expand expression earlier, we need explictly examine it here and set correct IsSorted value for collections.
            if (collection != null)
            {
                var strategy = collection.Type.ElementType.EvaluationStrategy as ILinqToAstoriaQueryEvaluationStrategy;
                ExceptionUtilities.CheckObjectNotNull(strategy, "Cannot get astoria-specific evaluation strategy from collection value.");

                if (uri.ExpandSegments.Any() && !strategy.IsCollectionOrderPredictable)
                {
                    value = QueryCollectionValue.Create(collection.Type.ElementType, collection.Elements, false);
                }
            }

            // if there are any select segments, then fixup the value
            if (uri.SelectSegments.Count > 0)
            {
                // post-process the result to omit properties that were not selected
                var selectedPaths = uri.SelectSegments.Select(s => this.UriConverter.ConcatenateSegments(s.Where(s2 => !(s2 is EntityTypeSegment))));
                value = this.VisitEntityValues(value, s => this.FixupPropertiesForSelect(s, selectedPaths));
            }

            return value;
        }
Example #38
0
 public static Bool IsDefined(QueryValue input) => (Bool)(input.ValueType != QueryValueType.None);
        private void ValidateAndPrintInfoOnError(ODataUri requestUri, ODataPayloadElement rootElement, QueryValue expectedValue)
        {
            try
            {
                this.Validator.Validate(rootElement, expectedValue);
            }
            catch (DataComparisonException)
            {
                // Doing this because of unit test failures, will need to fix this later
                if (this.QueryDataSet != null)
                {
                    this.Logger.WriteLine(LogLevel.Info, "Actual Payload Entity Graph:");
                    this.Logger.WriteLine(LogLevel.Info, this.ODataPayloadElementEntityGraphPrettyPrinter.PrettyPrint(rootElement));
                    this.Logger.WriteLine(LogLevel.Info, "Expected Query Entity Graph:");
                    this.Logger.WriteLine(LogLevel.Info, this.ODataQueryValueEntityGraphPrettyPrinter.PrettyPrint(expectedValue, 10));

                    this.Logger.WriteLine(LogLevel.Info, "Query DataSet Data");
                    foreach (var entitySet in requestUri.GetAllEntitySetsIncludingExpands())
                    {
                        this.Logger.WriteLine(LogLevel.Info, entitySet.Name + " DataSet");
                        var results = this.QueryDataSet[entitySet.Name];
                        this.Logger.WriteLine(LogLevel.Info, this.ODataQueryValueEntityGraphPrettyPrinter.PrettyPrint(results, 1));
                    }
                }

                throw;
            }
        }
Example #40
0
        // Token: 0x06000281 RID: 641 RVA: 0x000149F4 File Offset: 0x00012BF4
        public void queryDB(Dictionary <string, QueryValue> dicts)
        {
            double num  = ConvertUtils.ToDouble(this.monthLimitTB.Text.Trim());
            double num2 = ConvertUtils.ToDouble(this.avaliableLimitTB.Text.Trim()) * 10.0;

            if (num <= 0.0 && num2 <= 0.0)
            {
                WMMessageBox.Show(this, "查询条件需要大于0!");
                return;
            }
            this.getSqlStr(dicts);
            new List <string>();
            string    sqlStrForQueryUser = this.getSqlStrForQueryUser(dicts);
            DataTable dataTable          = new DataTable();

            foreach (string key in dicts.Keys)
            {
                QueryValue queryValue = dicts[key];
                this.db.AddParameter(key, queryValue.Value);
            }
            this.db.AddParameter("isActive", "1");
            DataTable dataTable2 = this.db.ExecuteQuery("SELECT * FROM usersTable WHERE " + ((sqlStrForQueryUser != "") ? (sqlStrForQueryUser + " AND ") : "") + " isActive=@isActive ORDER BY createTime ASC");

            if (dataTable2 != null && dataTable2.Rows != null && dataTable2.Rows.Count > 0)
            {
                DateTime dateTime = DateTime.Now;
                dateTime -= new TimeSpan((int)(num * 30.0), 0, 0, 0);
                TimeSpan timeSpan = dateTime - WMConstant.DT1970;
                dataTable.Columns.Add("userId");
                dataTable.Columns.Add("username");
                dataTable.Columns.Add("identityId");
                dataTable.Columns.Add("phoneNum");
                dataTable.Columns.Add("address");
                dataTable.Columns.Add("lastPursuitDate");
                dataTable.Columns.Add("lastPursuitNum");
                dataTable.Columns.Add("avaliableNum");
                foreach (object obj in dataTable2.Rows)
                {
                    DataRow dataRow = (DataRow)obj;
                    this.db.AddParameter("permanentUserId", dataRow["permanentUserId"].ToString());
                    this.db.AddParameter("operateType", "2");
                    this.db.AddParameter("lastReadInfo", "1");
                    DataTable dataTable3 = this.db.ExecuteQuery("SELECT * FROM userCardLog WHERE permanentUserId=@permanentUserId ORDER BY operationId DESC");
                    if (dataTable3 != null && dataTable3.Rows != null && dataTable3.Rows.Count > 0)
                    {
                        DataRow dataRow2 = dataTable3.Rows[0];
                        double  num3     = ConvertUtils.ToDouble(dataRow2["totalNum"].ToString());
                        double  num4     = ConvertUtils.ToDouble(dataRow["totalPursuitNum"].ToString());
                        if (num2 <= 0.0 || num2 > num4 - num3)
                        {
                            if (num > 0.0)
                            {
                                bool flag = false;
                                foreach (object obj2 in dataTable3.Rows)
                                {
                                    DataRow dataRow3 = (DataRow)obj2;
                                    if (Convert.ToInt64(dataRow3["operateType"]) < 2L)
                                    {
                                        if (num <= 0.0 || ConvertUtils.ToUInt64(dataRow3["time"].ToString()) <= timeSpan.TotalSeconds)
                                        {
                                            dataRow2 = dataRow3;
                                            flag     = true;
                                            break;
                                        }
                                        break;
                                    }
                                }
                                if (!flag)
                                {
                                    continue;
                                }
                            }
                            DataRow dataRow4 = dataTable.NewRow();
                            dataRow4["userId"]          = dataRow["userId"].ToString();
                            dataRow4["username"]        = dataRow["username"].ToString();
                            dataRow4["identityId"]      = dataRow["identityId"].ToString();
                            dataRow4["phoneNum"]        = dataRow["phoneNum"].ToString();
                            dataRow4["address"]         = dataRow["address"].ToString();
                            dataRow4["lastPursuitDate"] = WMConstant.DT1970.AddSeconds(ConvertUtils.ToDouble(dataRow2["time"].ToString())).ToString("yyyy-MM-dd HH:mm:ss");
                            dataRow4["lastPursuitNum"]  = dataRow2["pursuitNum"].ToString();
                            dataRow4["avaliableNum"]    = string.Concat(ConvertUtils.ToInt64(num4 - num3));
                            dataTable.Rows.Add(dataRow4);
                            dataTable.AcceptChanges();
                        }
                    }
                }
            }
            this.initDGV(dataTable);
        }
 /// <summary>
 /// Determines whether a constant is defined.
 /// </summary>
 /// <param name="ctx">Current runtime context.</param>
 /// <param name="callerCtx">type of caller class. Used to resolve reserved type names if used in <paramref name="name"/>.</param>
 /// <param name="this">Optional. Reference to <c>$this</c> object. Used to resolve <c>static::</c> type reference.</param>
 /// <param name="name">The name of the constant. Might be a class constant.</param>
 /// <returns>Whether the constant is defined.</returns>
 public static bool defined(Context ctx, [ImportCallerClass] RuntimeTypeHandle callerCtx, QueryValue <ThisVariable> @this, string name)
 {
     return(TryGetConstant(ctx, callerCtx, @this.Value.This, name, out _));
 }
        /// <summary>
        /// Evaluates member method of a spatial instance.
        /// </summary>
        /// <param name="instance">The instance of query value object</param>
        /// <param name="resultType">The function result type.</param>
        /// <param name="methodName">The member method to evaluate.</param>
        /// <param name="arguments">Arguments for the function call.</param>
        /// <returns>Query value which is the result of function evaluation.</returns>
        public override QueryValue EvaluateMemberMethod(QueryValue instance, QueryType resultType, string methodName, params QueryValue[] arguments)
        {
            var value = base.EvaluateMemberMethod(instance, resultType, methodName, arguments);

            if (instance.IsDynamicPropertyValue() || arguments.Any(a => a.IsDynamicPropertyValue()))
            {
                value = value.AsDynamicPropertyValue();
            }

            return value;
        }
Example #43
0
        /// <summary>
        ///     将字段名、字段值、查询方式拼接成SQL查询字符串
        /// </summary>
        /// <returns>查询字符串</returns>
        public string toQueryString(string iIndex, out string returnStr)
        {
            returnStr = string.Empty;
            var QueryCondition = new StringBuilder();

            switch (EQueryType)
            {
            case QueryType.BETWEEN:
            {
                var pars = QueryValue.Split(',');
                if (pars.Length == 2)
                {
                    QueryCondition.Append(QueryRelatedTypeString);
                    QueryCondition.Append(QueryName);
                    QueryCondition.Append("  >= @");
                    QueryCondition.Append(QueryName);
                    QueryCondition.Append(iIndex);
                    QueryCondition.Append("1");
                    QueryCondition.Append(QueryRelatedTypeString);
                    QueryCondition.Append(QueryName);
                    QueryCondition.Append("  <= @");
                    QueryCondition.Append(QueryName);
                    QueryCondition.Append(iIndex);
                    QueryCondition.Append("2");
                }
                break;
            }

            case QueryType.等于:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                if (IsInnerQuery)
                {
                    QueryCondition.Append(" = ");
                    QueryCondition.Append(QueryValue);
                }
                else
                {
                    QueryCondition.Append(" = @");
                    QueryCondition.Append(QueryName);
                    QueryCondition.Append(iIndex);
                }
                break;
            }

            case QueryType.等于:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                if (IsInnerQuery)
                {
                    QueryCondition.Append(" <> ");
                    QueryCondition.Append(QueryValue);
                }
                else
                {
                    QueryCondition.Append("  <> @");
                    QueryCondition.Append(QueryName);
                    QueryCondition.Append(iIndex);
                }
                break;
            }

            case QueryType.大于:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                if (IsInnerQuery)
                {
                    QueryCondition.Append(" > ");
                    QueryCondition.Append(QueryValue);
                }
                else
                {
                    QueryCondition.Append("  > @");
                    QueryCondition.Append(QueryName);
                    QueryCondition.Append(iIndex);
                }
                break;
            }

            case QueryType.大于等于:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                if (IsInnerQuery)
                {
                    QueryCondition.Append(" >= ");
                    QueryCondition.Append(QueryValue);
                }
                else
                {
                    QueryCondition.Append("  >= @");
                    QueryCondition.Append(QueryName);
                    QueryCondition.Append(iIndex);
                }
                break;
            }

            case QueryType.小于:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                if (IsInnerQuery)
                {
                    QueryCondition.Append(" < ");
                    QueryCondition.Append(QueryValue);
                }
                else
                {
                    QueryCondition.Append(" < @");
                    QueryCondition.Append(QueryName);
                    QueryCondition.Append(iIndex);
                }
                break;
            }

            case QueryType.小于等于:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                if (IsInnerQuery)
                {
                    QueryCondition.Append(" <= ");
                    QueryCondition.Append(QueryValue);
                }
                else
                {
                    QueryCondition.Append(" <= @");
                    QueryCondition.Append(QueryName);
                    QueryCondition.Append(iIndex);
                }
                break;
            }

            case QueryType.LIKE:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                QueryCondition.Append(" LIKE @");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(iIndex);
                break;
            }

            case QueryType.左LIKE:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                QueryCondition.Append(" LIKE @");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(iIndex);
                break;
            }

            case QueryType.右LIKE:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                QueryCondition.Append(" LIKE @");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(iIndex);
                break;
            }

            case QueryType.包含:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);

                QueryCondition.AppendFormat(@" IN (SELECT * FROM @{0}table)",
                                            QueryName + iIndex);

                returnStr = string.Format(@"DECLARE @{0}table TABLE(SID VARCHAR(100));
                        INSERT INTO @{0}table (SID)
	                    SELECT WI.{0}.value('@i','varchar(100)') as Ids
	                    FROM @{0}.nodes('/es/e') WI({0});	"    , QueryName + iIndex);

                break;
            }

            case QueryType.包含:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);

                QueryCondition.AppendFormat(@" NOT IN (SELECT * FROM @{0}table)",
                                            QueryName + iIndex);

                returnStr = string.Format(@"DECLARE @{0}table TABLE(SID VARCHAR(100));
                        INSERT INTO @{0}table (SID)
	                    SELECT WI.{0}.value('@i','varchar(100)') as Ids
	                    FROM @{0}.nodes('/es/e') WI({0});	"    , QueryName + iIndex);
                break;
            }

            case QueryType.为空:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                QueryCondition.Append(" IS NOT NULL ");
                break;
            }

            case QueryType.为空:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(QueryName);
                QueryCondition.Append(" IS NULL ");
                break;
            }

            case QueryType.升序:
            {
                QueryCondition.Append(" ORDER BY ");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(" ASC ");
                break;
            }

            case QueryType.降序:
            {
                QueryCondition.Append(" ORDER BY ");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(" DESC ");
                break;
            }

            case QueryType.组合排序:
            {
                QueryCondition.Append(" ORDER BY ");
                QueryCondition.Append(QueryValue);
                break;
            }

            case QueryType.左括号:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(" ( ");
                break;
            }

            case QueryType.右括号:
            {
                QueryCondition.Append(" ) ");
                break;
            }

            case QueryType.或:
            {
                QueryCondition.Append(" OR ");
                break;
            }

            case QueryType.异或与:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(" ( ");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(" & @");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(iIndex);
                QueryCondition.Append(" = @");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(iIndex);
                QueryCondition.Append(" ) ");
                break;
            }

            case QueryType.非异或与:
            {
                QueryCondition.Append(QueryRelatedTypeString);
                QueryCondition.Append(" ( ");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(" & @");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(iIndex);
                QueryCondition.Append(" != @");
                QueryCondition.Append(QueryName);
                QueryCondition.Append(iIndex);
                QueryCondition.Append(" ) ");
                break;
            }
            }
            return(QueryCondition.ToString());
        }