/// <summary>
		/// The execute query simple.
		/// </summary>
		/// <param name="query">The query.</param>
		/// <param name="parameterValues">The parameter values.</param>
		/// <param name="version">The version.</param>
		/// <param name="progress">The progress.</param>
		/// <param name="groups">The groups.</param>
		/// <returns>
		/// The <see cref="QueryInstanceResultInfo" />.
		/// </returns>
		public QueryInstanceResultInfo ExecuteQuerySimple(
			QueryInfo                query,
			QueryExecutionParams     parameters,
			InstanceVersion          version,
			ProgressItem             progress,
			params GroupDefinition[] groups
		)
		{
			// Log.InfoFormat("73:query:'{0}'",
			// 	query
			// );

			QueryInstanceResultInfo result = new QueryInstanceResultInfo(this.Instance);
			QueryItemInfo queryItem        = query.Items.GetQueryItemForVersion(version);

			this.PrepareProgress(progress, groups);

			this.ExecuteQuery(
				query,
				parameters,
				progress,
				groups,
				result,
				queryItem
			);

			return result;
		}
        public void GetStatementTest()
        {
            var inf = new QueryInfo();
            var input1 = "select * from A";
            (inf.AsDynamic().GetStatement(input1) as string[]).IsStructuralEqual(new[] { "select * from A" });

            var input2 = "select * from A;";
            (inf.AsDynamic().GetStatement(input2) as string[]).IsStructuralEqual(new[] { "select * from A" });

            var input3 = "select * from A; select * from B";
            (inf.AsDynamic().GetStatement(input3) as string[]).IsStructuralEqual(new[] { "select * from A", "select * from B" });

            var input4 = @"" + Environment.NewLine +
                      @" create trigger set_foo_primary for foo" + Environment.NewLine +
                      @"before insert" + Environment.NewLine +
                      @"" + Environment.NewLine +
                      @"as begin" + Environment.NewLine +
                      @"" + Environment.NewLine +
                      @"new.a = gen_id(gen_foo, 1);" + Environment.NewLine +
                      @"end" + Environment.NewLine +
                      @";" + Environment.NewLine +
                      @"  select* from A;" + Environment.NewLine +
                      @" create table V(a integer, b nvarchar(5))";
            (inf.AsDynamic().GetStatement(input4) as string[]).IsStructuralEqual(new[] {
                  @"create trigger set_foo_primary for foo" + Environment.NewLine +
                      @"before insert" + Environment.NewLine +
                      @"" + Environment.NewLine +
                      @"as begin" + Environment.NewLine +
                      @"" + Environment.NewLine +
                      @"new.a = gen_id(gen_foo, 1);" + Environment.NewLine +
                      @"end" ,
                "select* from A", "create table V(a integer, b nvarchar(5))" });
        }
Пример #3
0
        /// <summary>
        /// Load the artist search.
        /// </summary>
        public override void Load(XmlDocument doc, QueryInfo query)
        {
            last_query = query;

            foreach (Widget widget in album_box.Children)
                album_box.Remove (widget);

            XmlNodeList list = doc.GetElementsByTagName ("getArtistResponse");
            if (list.Count == 0)
                return;

            string artist = null;
            XmlNodeList albums_node = null;

            //look for artist name
            foreach (XmlNode node in list[0].ChildNodes)
            {
                if (node.Name == "artist")
                {
                    artist = node.InnerText;
                    search_title.Markup = "<b><big><big>" + Utils.ParseMarkup (artist) + "</big></big></b>\n";
                }
                else if (node.Name == "albums")
                    albums_node = node.ChildNodes;
            }

            if (albums_node == null || albums_node.Count == 0)
                return;

            string name = null;
            string year = null;

            album_box.PackStart (new HSeparator (), false, false, 2);

            foreach (XmlNode node in albums_node)
            {
                switch (node.Name)
                {
                    case "album":
                        name = node.InnerText;
                        break;

                    case "year":
                        if (node.InnerText != "0")
                            year = node.InnerText;
                        break;

                    case "songs":
                        Album album = new Album (artist, name, year, node.ChildNodes);

                        album_box.PackStart (new AlbumBox (album, main), false ,false, 0);
                        album_box.PackStart (new HSeparator (), false, false, 2);

                        name = null;
                        year = null;
                        break;
                }
            }
        }
Пример #4
0
 public static Word GetModel(QueryInfo queryInfo)
 {
     List<Word> list = GetList(queryInfo);
     if (list == null || list.Count == 0)
         return null;
     else
         return list[0];
 }
Пример #5
0
        /// <summary>
        /// The query to execute.
        /// </summary>
        public override string GetQuery(QueryInfo query)
        {
            if (query.Equals (last_query, QueryField.Artist, QueryField.Title))
                return null;

            string url = "http://ws.audioscrobbler.com/1.0/track/{0}/{1}/similar.xml";
            return ParseQuery (url, query.Artist, query.Title);
        }
 public static ItemInCustomSmallType GetModel(QueryInfo queryInfo)
 {
     List<ItemInCustomSmallType> list = GetList(queryInfo);
     if (list == null || list.Count == 0)
         return null;
     else
         return list[0];
 }
Пример #7
0
 public static SmallClass GetModel(QueryInfo queryInfo)
 {
     List<SmallClass> list = GetList(queryInfo);
     if (list == null || list.Count == 0)
         return null;
     else
         return list[0];
 }
Пример #8
0
        /// <summary>
        /// The query to execute.
        /// </summary>
        public override string GetQuery(QueryInfo query)
        {
            if (query.Equals (last_query, QueryField.Artist, QueryField.Title))
                return null;

            string url = "http://lyricwiki.org/api.php?artist={0}&song={1}&fmt=xml";
            return ParseQuery (url, query.Artist, query.Title);
        }
Пример #9
0
        /// <summary>
        /// The query to execute.
        /// </summary>
        public override string GetQuery(QueryInfo query)
        {
            if (query.Equals (last_query, QueryField.Artist, QueryField.Album))
                return null;

            string url = "http://ws.audioscrobbler.com/1.0/album/{0}/{1}/info.xml";
            return ParseQuery (url, query.Artist, query.Album);
        }
Пример #10
0
        /// <summary>
        /// The query to execute.
        /// </summary>
        public override string GetQuery(QueryInfo query)
        {
            if (query.Equals (last_query, QueryField.Username))
                return null;

            string url = "http://ws.audioscrobbler.com/1.0/user/{0}/topartists.xml";
            return ParseQuery (url, query.Username);
        }
Пример #11
0
 public static CustomBigType GetModel(QueryInfo queryInfo)
 {
     List<CustomBigType> list = GetList(queryInfo);
     if (list == null || list.Count == 0)
         return null;
     else
         return list[0];
 }
Пример #12
0
        /// <summary>
        /// The query to execute.
        /// </summary>
        public override string GetQuery(QueryInfo query)
        {
            if (query.Equals (last_query, QueryField.Artist))
                return null;

            string url = "http://ws.audioscrobbler.com/1.0/artist/{0}/toptracks.xml";
            return ParseQuery (url, query.Artist);
        }
        /// <inheritdoc />
        protected override QueryItemInfo GetQueryForGroups(QueryInfo query, InstanceVersion version)
        {
            if (query.GroupSelect != null && query.GroupSelect.Count > 0)
            {
                return query.GroupSelect.GetQueryItemForVersion(version);
            }

            return query.DatabaseSelect.GetQueryItemForVersion(version);
        }
		/// <summary>
		/// The get groups.
		/// </summary>
		/// <param name="query">
		/// The query information.
		/// </param>
		/// <param name="parameterValues">
		/// The parameter values.
		/// </param>
		/// <param name="version">
		/// The version.
		/// </param>
		/// <returns>
		/// The <see cref="Dictionary{TKey,TValue}"/>.
		/// </returns>
		public virtual ICollection<GroupDefinition> GetGroups(
			QueryInfo                   query,
			IEnumerable<ParameterValue> parameterValues,
			InstanceVersion             version
		)
		{
			var groups = new List<GroupDefinition>();

			// TODO: Create GroupDefinition with childrens
			QueryItemInfo selectGroupsSql = this.GetQueryForGroups(query, version);

			if (selectGroupsSql != null)
			{
				try
				{
					var paramsArray = parameterValues as ParameterValue[] ?? parameterValues.ToArray();

					DataTable[] groupsTabels = this.ExecuteSqlFunction(
						this.Instance,
						selectGroupsSql,
						null,
						query.Parameters,
						paramsArray,
						null,
						true
					);

					foreach (DataTable groupTable in groupsTabels)
					{
						this.AddGroupsFromTable(groupTable, groups);
					}

					if (selectGroupsSql.ChildGroups.IsNullOrEmpty())
					{
						return groups;
					}

					foreach (GroupDefinition groupDefinition in groups)
					{
						this.GetChildGroupsDefinitions(selectGroupsSql, groupDefinition, paramsArray, version);
					}
				}
				catch (OperationCanceledException ex)
				{
					log.Error(ex);
					throw;
				}
				catch (Exception ex)
				{
					log.Error("instance=" + this.Instance.Name + " query=" + query, ex);
				}
			}

			return groups;
		}
        public void ExecuteQueryTest()
        {
            SetupTestDbFb2();
            var inf = new QueryInfo();
            inf.ExecuteQuery(GetFb2ConnectionString(), "select * from test").ToList()[0].View.Rows.Count.Is(0);

            var result = inf.ExecuteQuery(GetFb2ConnectionString(), "insert into test(int_test, char_test) values (1, 'aaaaaaaaaa');update test set varchar_test = 'testtesttesttest' where int_test = 1;select * from test").ToList();
            result[0].View.Rows[0].Is(x => ((string)x[0]).Contains("実行しました。"));
            result[1].View.Rows[0].Is(x => ((string)x[0]).Contains("更新しました。"));
            result[2].View.Rows.Count.Is(1);
        }
        public void ExecuteQueryTestFb3()
        {
            SetupTestDbFb3();
            var inf = new QueryInfo();
            var conStr = GetFb3ConnectionString();
            inf.ExecuteQuery(conStr, "select * from test").ToList()[0].View.Rows.Count.Is(0);

            var result = inf.ExecuteQuery(conStr, "insert into test values (1, 123456789000, null, '12asd', '2016-07-24', 50000, 2.5, 2.5555, 4500, 10, '10:00:00', current_timestamp, 'asdfghjk', true);update test set varchar_test = 'testtesttesttest' where int_test = 1;select * from test").ToList();
            result[0].View.Rows[0].Is(x => ((string)x[0]).Contains("実行しました。"));
            result[1].View.Rows[0].Is(x => ((string)x[0]).Contains("更新しました。"));
            result[2].View.Rows.Count.Is(1);
        }
 /// <inheritdoc />
 public override ICollection<GroupDefinition> GetGroups(QueryInfo query, IEnumerable<ParameterValue> values, InstanceVersion i)
 {
     return new List<GroupDefinition>()
                {
                    new GroupDefinition(this.Instance, string.Empty, string.Empty)
                        {
                            GroupType
                                =
                                QueryScope
                                .Instance
                        }
                };
 }
Пример #18
0
        /// <summary>
        /// Load the artist list.
        /// </summary>
        public override void Load(XmlDocument doc, QueryInfo query)
        {
            last_query = query;
            list.Clear ();

            XmlNodeList node_list = doc.GetElementsByTagName ("topartists");
            if (node_list.Count == 0)
                return;

            foreach (XmlNode node in node_list[0].ChildNodes)
                if (node.LocalName == "artist")
                    list.Add (new TopArtist (node));

            page_navigator.UpdatePageNumber ();
            ShowPage ();
        }
Пример #19
0
        /// <summary>
        /// Load the top tracks.
        /// </summary>
        public override void Load(XmlDocument doc, QueryInfo query)
        {
            last_query = query;
            top_tracks.Clear ();

            XmlNodeList list = doc.GetElementsByTagName ("mostknowntracks");
            if (list.Count == 0)
                return;

            foreach (XmlNode node in list[0].ChildNodes)
                if (node.LocalName == "track")
                    top_tracks.Add (new TopTrack (node.ChildNodes));

            page_navigator.UpdatePageNumber ();
            ShowPage ();
        }
Пример #20
0
 protected void Page_Load(object sender, EventArgs e)
 {
     string searchWords = Request.QueryString["SearchWords"];
     string indexNames = Request.QueryString["IndexNames"];
     //Response.Write(searchWords);
     string hostname = ConfigurationManager.AppSettings["HostName"];
     int port = int.Parse(ConfigurationManager.AppSettings["PortNum"]);
     TcpClient client;
     NetworkStream ns;
     BinaryFormatter formater;
     DateTime now = DateTime.Now;
     try
     {
         client = new TcpClient(hostname, port);
         ns = client.GetStream();
         formater = new BinaryFormatter();
         SearchInfo sinfo = new SearchInfo();
         QueryInfo info = new QueryInfo();
         info.IndexNames = "";
         info.SearchWords = searchWords;
         info.IndexNames = indexNames;
         sinfo.Query = info;
         sinfo.PageSize = 10;
         formater.Serialize(ns, sinfo);
         SearchResult sr = (SearchResult)formater.Deserialize(ns);
         //WriteLog(Server.MapPath(".") + "searchutils.log", searchWords, indexNames, sr.Records.Count, sr);
         XmlSerializer xmlSerializer = new XmlSerializer(typeof(SearchResult));
         StringBuilder builder = new StringBuilder();
         StringWriter writer = new StringWriter(builder);
         xmlSerializer.Serialize(writer, sr);
         XmlDocument doc = new XmlDocument();
         doc.LoadXml(builder.ToString());
         writer.Close();
         ns.Close();
         Response.Write(doc.DocumentElement.OuterXml);
         //FileStream fs = new FileStream(@"result.xml", FileMode.Truncate);
         //xmlSerializer.Serialize(writer, fs);
         //fs.Close();
     }
     catch (Exception se)
     {
         Response.Write(se.StackTrace.ToString());
         return;
     }
 }
        public void GetStatementTest2()
        {
            var inf = new QueryInfo();
            var input1 =
            @"--comment1
            create trigger set_foo_primary for foo
            before insert
            as begin
            new.a = gen_id(gen_foo, 1);
            end;

            --comment2
            select *
            from test
            where a = 1;

            --comment3
            create trigger set_foo_primary for foo2
            before insert
            as begin
            new.a = gen_id(gen_foo, 1);
            end;

            select * from fuga where hoho = 'eeee'
            --comment4";

            (inf.AsDynamic().GetStatement(input1) as string[]).IsStructuralEqual(new[] {
            @"create trigger set_foo_primary for foo
            before insert
            as begin
            new.a = gen_id(gen_foo, 1);
            end",
            @"select *
            from test
            where a = 1",
            @"create trigger set_foo_primary for foo2
            before insert
            as begin
            new.a = gen_id(gen_foo, 1);
            end",
            @"select * from fuga where hoho = 'eeee'"
            });
        }
Пример #22
0
        public SitecoreSearchResultCollection FieldSearch(QueryInfo[] qis, int maxResults)
        {
            HighResTimer timer = new HighResTimer(true);
            var combinedQuery = new CombinedQuery();
            foreach (var qi in qis)
            {
                var q = GetQuery(qi);
                if (q != null)
                    combinedQuery.Add(q, qi.SitecoreSearchQueryOccurance);
            }

            SearchResultCollection results = null;

            if (combinedQuery.Clauses.Count > 0)
                results = GetSearchHits(combinedQuery, maxResults);

            return results != null
                    ? new SitecoreSearchResultCollection(results, timer.Elapsed())
                    : null;
        }
 public void QueryExecution(string query, long elapsedTime, bool sequentialSearch)  
 {
     lock (this)
     {
         QueryInfo info = (QueryInfo)profile[query];
         if (info == null) 
         {
             info = new QueryInfo();
             info.query = query;
             profile[query] = info;
         }
         if (info.maxTime < elapsedTime) 
         { 
             info.maxTime = elapsedTime;
         }
         info.totalTime += elapsedTime;
         info.count += 1;
         info.sequentialSearch |= sequentialSearch;
     }        
 }
Пример #24
0
        private QueryBase GetQuery(QueryInfo qi)
        {
            if (String.IsNullOrEmpty(qi.SearchString) ||
                String.IsNullOrEmpty(qi.FieldName) ||
                Index == null)
            {
                return null;
            }

            QueryBase query = null;

            switch (qi.QueryType)
            {
                case "FieldQuery":
                    query = new FieldQuery(qi.FieldName, qi.SearchString);
                    break;

                default:
                    query = new FullTextQuery(qi.SearchString);
                    break;
            }

            return query;
        }
		/// <inheritdoc />
		protected override void ExecuteQuery(
			QueryInfo               query,
			QueryExecutionParams    parameters,
			QueryInstanceResultInfo result,
			QueryItemInfo           queryItem,
			GroupDefinition         group,
			ProgressItem            subProgress
		)
		{
			var tempValues = new List<ParameterValue>(parameters.Values);

			foreach (var parameter in group.GroupParameters)
			{
				tempValues.Add(new ParameterValue
					{
						Name        = "@" + parameter.Key,
						StringValue = parameter.Value
					}
				);
			}

			QueryDatabaseResultInfo databaseResult = this.ExecuteQueryItemFunction.Invoke(
				this.Instance,
				queryItem,
				null,
				null,
				query.Parameters,
				tempValues,
				subProgress
			);

			databaseResult.Database   = group.Name;
			databaseResult.DatabaseId = group.Id;

			result.AddDatabaseResult(databaseResult);
		}
Пример #26
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="query"></param>
 public Queryable(QueryInfo query)
 {
     Provider   = new QueryProvider(query);
     Expression = Expression.Constant(this);
     Query      = query;
 }
        public static IReadOnlyList <Range <string> > GetProvidedPartitionKeyRanges(
            SqlQuerySpec querySpec,
            bool enableCrossPartitionQuery,
            bool parallelizeCrossPartitionQuery,
            bool isContinuationExpected,
            bool hasLogicalPartitionKey,
            PartitionKeyDefinition partitionKeyDefinition,
            QueryPartitionProvider queryPartitionProvider,
            string clientApiVersion,
            out QueryInfo queryInfo)
        {
            if (querySpec == null)
            {
                throw new ArgumentNullException("querySpec");
            }

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

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

            PartitionedQueryExecutionInfo queryExecutionInfo = null;

            queryExecutionInfo = queryPartitionProvider.GetPartitionedQueryExecutionInfo(
                querySpec: querySpec,
                partitionKeyDefinition: partitionKeyDefinition,
                requireFormattableOrderByQuery: VersionUtility.IsLaterThan(clientApiVersion, HttpConstants.Versions.v2016_11_14),
                isContinuationExpected: isContinuationExpected,
                allowNonValueAggregateQuery: false,
                hasLogicalPartitionKey: hasLogicalPartitionKey);

            if (queryExecutionInfo == null ||
                queryExecutionInfo.QueryRanges == null ||
                queryExecutionInfo.QueryInfo == null ||
                queryExecutionInfo.QueryRanges.Any(range => range.Min == null || range.Max == null))
            {
                DefaultTrace.TraceInformation("QueryPartitionProvider returned bad query info");
            }

            bool isSinglePartitionQuery = queryExecutionInfo.QueryRanges.Count == 1 && queryExecutionInfo.QueryRanges[0].IsSingleValue;

            bool queryFansOutToMultiplePartitions = partitionKeyDefinition.Paths.Count > 0 && !isSinglePartitionQuery;

            if (queryFansOutToMultiplePartitions)
            {
                if (!enableCrossPartitionQuery)
                {
                    throw new BadRequestException(RMResources.CrossPartitionQueryDisabled);
                }
                else
                {
                    bool queryNotServiceableByGateway = parallelizeCrossPartitionQuery ||
                                                        queryExecutionInfo.QueryInfo.HasTop ||
                                                        queryExecutionInfo.QueryInfo.HasOrderBy ||
                                                        queryExecutionInfo.QueryInfo.HasAggregates ||
                                                        queryExecutionInfo.QueryInfo.HasDistinct ||
                                                        queryExecutionInfo.QueryInfo.HasOffset ||
                                                        queryExecutionInfo.QueryInfo.HasLimit;

                    if (queryNotServiceableByGateway)
                    {
                        if (!IsSupportedPartitionedQueryExecutionInfo(queryExecutionInfo, clientApiVersion))
                        {
                            throw new BadRequestException(RMResources.UnsupportedCrossPartitionQuery);
                        }
                        else if (queryExecutionInfo.QueryInfo.HasAggregates && !IsAggregateSupportedApiVersion(clientApiVersion))
                        {
                            throw new BadRequestException(RMResources.UnsupportedCrossPartitionQueryWithAggregate);
                        }
                        else
                        {
                            DocumentClientException exception = new DocumentClientException(
                                RMResources.UnsupportedCrossPartitionQuery,
                                HttpStatusCode.BadRequest,
                                SubStatusCodes.CrossPartitionQueryNotServable);

                            exception.Error.AdditionalErrorInfo = JsonConvert.SerializeObject(queryExecutionInfo);
                            throw exception;
                        }
                    }
                }
            }
            else
            {
                if (queryExecutionInfo.QueryInfo.HasAggregates && !isContinuationExpected)
                {
                    // For single partition query with aggregate functions and no continuation expected,
                    // we would try to accumulate the results for them on the SDK, if supported.

                    if (IsAggregateSupportedApiVersion(clientApiVersion))
                    {
                        DocumentClientException exception = new DocumentClientException(
                            RMResources.UnsupportedQueryWithFullResultAggregate,
                            HttpStatusCode.BadRequest,
                            SubStatusCodes.CrossPartitionQueryNotServable);

                        exception.Error.AdditionalErrorInfo = JsonConvert.SerializeObject(queryExecutionInfo);
                        throw exception;
                    }
                    else
                    {
                        throw new BadRequestException(RMResources.UnsupportedQueryWithFullResultAggregate);
                    }
                }
                else if (queryExecutionInfo.QueryInfo.HasDistinct)
                {
                    // If the query has distinct then we have to reject it since the backend only returns
                    // elements that are distinct within a page and we need the client to do post distinct processing
                    DocumentClientException exception = new DocumentClientException(
                        RMResources.UnsupportedCrossPartitionQuery,
                        HttpStatusCode.BadRequest,
                        SubStatusCodes.CrossPartitionQueryNotServable);

                    exception.Error.AdditionalErrorInfo = JsonConvert.SerializeObject(queryExecutionInfo);
                    throw exception;
                }
            }

            queryInfo = queryExecutionInfo.QueryInfo;
            return(queryExecutionInfo.QueryRanges);
        }
Пример #28
0
        public override List<CustomSmallType> GetCustomSmallTypeList( QueryInfo queryInfo)
        {
            List<SqlParameter> list = new List<SqlParameter>();

            StringBuilder strSql = new StringBuilder();
            strSql.Append("Select * ");
            strSql.Append(" From CustomSmallType ");
            strSql.Append(" Where 1=1 ");

            SqlQueryInfo sqi = sqlHelper.ParseQueryInfo(queryInfo);
            if (sqi != null)
            {
                strSql.Append(" " + sqi.WhereClause);

                if (!Globals.IsNullorEmpty(sqi.OrderClause))
                    strSql.Append(" Order By " + sqi.OrderClause);

                list.AddRange(sqi.Parameters);
            }

            List<CustomSmallType> listCustomSmallType = new List<CustomSmallType>();

            SqlDataReader dr;

            try
            {
                dr = DbHelperSQL.ExecuteReader(strSql.ToString(),list.ToArray());
                while (dr.Read())
                {
                    listCustomSmallType.Add(PopulateCustomSmallTypeFromIDataReader(dr));
                }
                dr.Close();
            }
            catch (SqlException ex)
            {
                throw ex;
            }

            return listCustomSmallType;
        }
Пример #29
0
 public virtual PageInfo GetPageInfo(QueryInfo Query)
 {
     return(MyDAL.GetPageInfo(Query));
 }
Пример #30
0
    //获取品牌信息列表
    public string GetBrands()
    {
        string    keyword = tools.CheckStr(Request["keyword"]);
        QueryInfo Query   = new QueryInfo();

        Query.PageSize    = tools.CheckInt(Request["rows"]);
        Query.CurrentPage = tools.CheckInt(Request["page"]);
        if (keyword.Length > 0)
        {
            Query.ParamInfos.Add(new ParamInfo("AND", "str", "BrandInfo.Brand_Name", "like", keyword));
        }
        Query.ParamInfos.Add(new ParamInfo("AND", "str", "BrandInfo.Brand_Site", "=", Public.GetCurrentSite()));
        Query.OrderInfos.Add(new OrderInfo(tools.CheckStr(Request["sidx"]), tools.CheckStr(Request["sord"])));
        PageInfo          pageinfo = brand.GetPageInfo(Query, Public.GetUserPrivilege());
        IList <BrandInfo> Brands   = brand.GetBrands(Query, Public.GetUserPrivilege());

        if (Brands != null)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{\"page\":" + pageinfo.CurrentPage + ",\"total\":" + pageinfo.PageCount + ",\"records\":" + pageinfo.RecordCount + ",\"rows\"");
            jsonBuilder.Append(":[");
            foreach (BrandInfo entity in Brands)
            {
                jsonBuilder.Append("{\"BrandInfo.Brand_ID\":" + entity.Brand_ID + ",\"cell\":[");
                //各字段
                jsonBuilder.Append("\"");
                jsonBuilder.Append(entity.Brand_ID);
                jsonBuilder.Append("\",");

                jsonBuilder.Append("\"");
                jsonBuilder.Append(Public.JsonStr(entity.Brand_Name));
                jsonBuilder.Append("\",");

                jsonBuilder.Append("\"");
                jsonBuilder.Append(entity.Brand_Sort);
                jsonBuilder.Append("\",");

                jsonBuilder.Append("\"");

                if (Public.CheckPrivilege("9592b436-454a-42cf-83f4-0d9ce83c339a"))
                {
                    jsonBuilder.Append("<img src=\\\"/images/icon_edit.gif\\\"> <a href=\\\"brand_edit.aspx?brand_id=" + entity.Brand_ID + "\\\" title=\\\"修改\\\">修改</a>");
                }
                if (Public.CheckPrivilege("3297a5d3-44e6-4318-aa23-4d31288a291b"))
                {
                    jsonBuilder.Append(" <img src=\\\"/images/icon_del.gif\\\"> <a href=\\\"javascript:void(0);\\\" onclick=\\\"confirmdelete('brand_do.aspx?action=move&brand_id=" + entity.Brand_ID + "')\\\" title=\\\"删除\\\">删除</a>");
                }
                jsonBuilder.Append("\",");

                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("]},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return(jsonBuilder.ToString());
        }
        else
        {
            return(null);
        }
    }
Пример #31
0
    //网站公告右侧列表 /**/
    public void Notice_List(int cateid)
    {
        int page = tools.CheckInt(Request["page"]);

        if (page < 1)
        {
            page = 1;
        }
        NoticeCateInfo CateInfo = MyNoticeCate.GetNoticeCateByID(cateid, pub.CreateUserPrivilege("fb3e87ba-3d4d-480d-934e-80048bcc0100"));

        if (CateInfo != null)
        {
            Response.Write("<div id=\"help-right\">");
            Response.Write("  <h3>" + CateInfo.Notice_Cate_Name + "</h3>");
            Response.Write("  <div id=\"help-rightwen1\">");
            Response.Write("  <ul>");
            QueryInfo Query = new QueryInfo();
            Query.PageSize    = 20;
            Query.CurrentPage = page;
            Query.ParamInfos.Add(new ParamInfo("AND", "int", "NoticeInfo.Notice_IsAudit", "=", "1"));
            Query.ParamInfos.Add(new ParamInfo("AND", "str", "NoticeInfo.Notice_Site", "=", "CN"));
            Query.ParamInfos.Add(new ParamInfo("AND", "int", "NoticeInfo.Notice_Cate", "=", CateInfo.Notice_Cate_ID.ToString()));
            Query.OrderInfos.Add(new OrderInfo("NoticeInfo.Notice_ID", "DESC"));
            IList <NoticeInfo> notices = Webnotice.GetNotices(Query, pub.CreateUserPrivilege("9d4d1366-35ab-4eb6-b88e-e49e6bfae9d7"));
            if (notices != null)
            {
                foreach (NoticeInfo entity in notices)
                {
                    Response.Write("<li><span style=\"color:#535353;\">[ " + entity.Notice_Addtime.ToString("yy-MM-dd") + " ]</span><a href=\"/notice/detail.aspx?notice_id=" + entity.Notice_ID + "\">" + tools.CutStr(entity.Notice_Title, 35) + "</a></li>");
                }
            }
            else
            {
                Response.Write("<div height=\"50\"  style=\" height:50px; text-align:center;line-height:50px; color:#707070;\">信息正在维护中...</div>");
            }
            Response.Write("</ul>");

            PageInfo pageinfo = Webnotice.GetPageInfo(Query, pub.CreateUserPrivilege("9d4d1366-35ab-4eb6-b88e-e49e6bfae9d7"));
            if (pageinfo != null && pageinfo.RecordCount >= 1)
            {
                string url = "/notice/index.aspx?cate_id=" + CateInfo.Notice_Cate_ID;
                Response.Write("<div style=\" float:right; padding-right:30px; padding-bottom:5px;\">");
                pub.Page(pageinfo.PageCount, pageinfo.CurrentPage, url, pageinfo.PageSize, pageinfo.RecordCount);
                Response.Write("</div>");
            }

            Response.Write("  </div>");
            Response.Write("</div>");
        }
        else
        {
            Response.Write("<div id=\"help-right\">");
            Response.Write("  <h3>热点公告</h3>");
            Response.Write("  <div id=\"help-rightwen1\">");
            Response.Write("  <ul>");
            QueryInfo Query = new QueryInfo();
            Query.PageSize    = 20;
            Query.CurrentPage = 1;
            Query.ParamInfos.Add(new ParamInfo("AND", "int", "NoticeInfo.Notice_IsAudit", "=", "1"));
            Query.ParamInfos.Add(new ParamInfo("AND", "int", "NoticeInfo.Notice_IsHot", "=", "1"));
            Query.ParamInfos.Add(new ParamInfo("AND", "str", "NoticeInfo.Notice_Site", "=", "CN"));
            Query.OrderInfos.Add(new OrderInfo("NoticeInfo.Notice_ID", "DESC"));
            IList <NoticeInfo> notices = Webnotice.GetNotices(Query, pub.CreateUserPrivilege("9d4d1366-35ab-4eb6-b88e-e49e6bfae9d7"));

            if (notices != null)
            {
                foreach (NoticeInfo entity in notices)
                {
                    Response.Write("<li><span>[ " + entity.Notice_Addtime.ToString("yy-MM-dd") + " ]</span><a href=\"/notice/detail.aspx?notice_id=" + entity.Notice_ID + "\">" + tools.CutStr(entity.Notice_Title, 35) + "</a></li>");
                }
            }
            else
            {
                Response.Write("<div height=\"50\"  style=\" height:50px; text-align:center;line-height:50px; color:#707070;\">信息正在维护中...</div>");
            }
            Response.Write("  </ul>");
            PageInfo pageinfo = Webnotice.GetPageInfo(Query, pub.CreateUserPrivilege("9d4d1366-35ab-4eb6-b88e-e49e6bfae9d7"));
            if (pageinfo != null && pageinfo.RecordCount > 0)
            {
                string url = "/notice/index.aspx?cate_id=0";
                Response.Write("<div style=\" float:right; padding-right:30px; padding-bottom:5px;\">");
                pub.Page(pageinfo.PageCount, pageinfo.CurrentPage, url, pageinfo.PageSize, pageinfo.RecordCount);
                Response.Write("</div>");
            }
            Response.Write("  </div>");
            Response.Write("</div>");
        }
    }
Пример #32
0
 protected override void SetQuerySelect(QueryInfo query)
 {
     query.SelectExp = "Id,Name,RealName";
 }
Пример #33
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="query"></param>
 public GroupByExpression(QueryInfo query)
 {
     Query = query;
 }
Пример #34
0
        /// <summary>
        /// 返回指定类型,支持强类型和匿名类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <param name="queryInfo"></param>
        /// <returns></returns>
        internal static List <T> DataReaderToSpecifiedList <T>(DbDataReader reader, QueryInfo <T> queryInfo)
        {
            var    mapping        = queryInfo.Mapping;
            var    list           = new List <T>();
            string columnCacheKey = queryInfo.selectKey;
            var    leftColumns    = new Dictionary <string, int>();
            var    dicColumns     = new Dictionary <string, int>();
            var    a = columnCache.TryGetValue(columnCacheKey, out leftColumns);

            if (!a)
            {
                leftColumns = new Dictionary <string, int>();
                dicColumns  = new Dictionary <string, int>();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    var name = reader.GetName(i).ToLower();
                    var find = mapping.Count(b => b.QueryName.ToLower() == name);
                    if (find == 0)
                    {
                        leftColumns.Add(name, i);
                    }
                    dicColumns.Add(name, i);
                }
                columnCache[columnCacheKey]      = leftColumns;
                queryColumnCache[columnCacheKey] = dicColumns;
            }
            dicColumns = queryColumnCache[columnCacheKey];
            queryInfo.CreateObjCreater(dicColumns);
            var objCreater      = queryInfo.GetObjCreater();
            int leftColumnCount = leftColumns.Count;
            var type            = typeof(T);

            while (reader.Read())
            {
                var dataContainer = new DataContainer(reader, type);
                var detailItem    = objCreater(dataContainer);
                #region 剩下的放索引
                //按IModel算
                if (leftColumnCount > 0)
                {
                    var model = detailItem as IModel;
                    foreach (var item in leftColumns)
                    {
                        var col = item.Key;
                        var n   = col.LastIndexOf("__");
                        if (n == -1)
                        {
                            continue;
                        }
                        var mapingName = col.Substring(n + 2);
                        var val        = reader.GetValue(item.Value);
                        model.SetIndexData(mapingName, val);
                    }
                }
                #endregion
                list.Add(detailItem);
            }
            reader.Close();
            reader.Dispose();
            return(list);
        }
Пример #35
0
 public virtual IList <OrdersInvoiceInfo> GetOrdersInvoices(QueryInfo Query)
 {
     return(MyDAL.GetOrdersInvoices(Query));
 }
Пример #36
0
 /// <summary>
 /// 执行
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="query"></param>
 /// <returns></returns>
 public virtual T Execute <T>(QueryInfo query)
 {
     return(Repository.Execute <T>(query));
 }
Пример #37
0
 /// <summary>
 /// 查询对象
 /// </summary>
 /// <param name="query"></param>
 /// <returns></returns>
 public virtual IList <T> GetEntities <T>(QueryInfo query)
 {
     return(Repository.GetEntities <T>(query));
 }
Пример #38
0
        /// <summary>
        /// 得到读的路由
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public virtual IList <QueryInfo> GetRouteQueries(QueryInfo query)
        {
            if (string.IsNullOrEmpty(query.Object.RouteName) || !DbRoutes.ContainsKey(query.Object.RouteName))
            {
                return(null);
            }
            var dbRoute = DbRoutes[query.Object.RouteName];

            query.DbRoute = dbRoute;
            var handleQueries = GetHandleQueries(dbRoute, query);

            if (handleQueries != null && handleQueries.Count > 0)
            {
                return(handleQueries);
            }
            if (dbRoute.Rules == null || dbRoute.Rules.Count == 0 || dbRoute.Shardings == null || dbRoute.Shardings.Count == 0)
            {
                return(null);
            }
            var names = query.GetRouteParameters(query.WhereExp);

            if (names != null && names.Count > 0)
            {
                foreach (var rule in dbRoute.Rules)
                {
                    if (!names.ContainsKey(rule.PropertyName))
                    {
                        continue;
                    }
                    var paramterValues = names[rule.PropertyName];
                    var result         = new List <QueryInfo>();
                    foreach (var paramterValue in paramterValues)
                    {
                        if (paramterValue is Array)
                        {
                            var arr = paramterValue as Array;
                            foreach (var ar in arr)
                            {
                                if (ar == null)
                                {
                                    continue;
                                }
                                var value     = rule.IsHash ? GenerateLongId(ar.ToString()) : ar;
                                var shardings = GetShardings(dbRoute, rule.PropertyName, value, false);
                                if (shardings == null || shardings.Count == 0)
                                {
                                    continue;
                                }
                                foreach (var sharding in shardings)
                                {
                                    var cloneQuery = GetQuery(dbRoute, query, sharding);
                                    if (cloneQuery != null &&
                                        result.Count(
                                            it =>
                                            it.GetDataBase == cloneQuery.GetDataBase &&
                                            it.GetTableName == cloneQuery.GetTableName) == 0)
                                    {
                                        result.Add(cloneQuery);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (paramterValue == null)
                            {
                                continue;
                            }
                            var value     = rule.IsHash ? GenerateLongId(paramterValue.ToString()) : paramterValue;
                            var shardings = GetShardings(dbRoute, rule.PropertyName, value, false);
                            if (shardings == null || shardings.Count == 0)
                            {
                                continue;
                            }
                            AppendQueryByShardings(result, dbRoute, shardings, query);
                        }
                    }
                    if (result.Count == 1)
                    {
                        result[0].PageIndex = query.PageIndex;
                        result[0].PageSize  = query.PageSize;
                    }
                    else if (result.Count > 1 && dbRoute.TopCount > 0 && (query.PageSize + query.PageIndex * query.PageSize) > dbRoute.TopCount)
                    {
                        throw new LimitCountOverflowException(string.Format("Limit Count Is {0}", dbRoute.TopCount));
                    }
                    if (result.Count > 0)
                    {
                        return(result);
                    }
                }
            }
            if (dbRoute.TopCount > 0 && (query.PageSize + query.PageIndex * query.PageSize) > dbRoute.TopCount)
            {
                throw new LimitCountOverflowException(string.Format("Limit Count Is {0}", dbRoute.TopCount));
            }

            return(GetAllQueries(dbRoute, query));
        }
Пример #39
0
 /// <summary>
 /// 合并查询
 /// </summary>
 /// <param name="result"></param>
 /// <param name="dbRoute"></param>
 /// <param name="query"></param>
 /// <param name="shardings"></param>
 /// <returns></returns>
 protected virtual void MergeQueries(IList <QueryInfo> result, DbRouteInfo dbRoute, QueryInfo query,
                                     IList <ShardingInfo> shardings)
 {
     foreach (var sharding in shardings)
     {
         var cloneQuery = GetQuery(dbRoute, query, sharding);
         if (cloneQuery != null &&
             result.Count(
                 it => it.GetDataBase == cloneQuery.GetDataBase && it.GetTableName == cloneQuery.GetTableName) ==
             0)
         {
             result.Add(cloneQuery);
         }
     }
 }
Пример #40
0
 /// <summary>
 /// 根据账户加载
 /// </summary>
 /// <param name="accountId"></param>
 public virtual void LoadData(long accountId)
 {
     Query = new QueryInfo();
     Query.Query <FreightEntity>().Where(it => it.Account.Id == accountId);
     LoadData();
 }
Пример #41
0
 protected override void SetQueryWhere(QueryInfo query)
 {
     query.Query <PropertyEntity>().Where(it => it.Node.Id == NodeId);
     base.SetQueryWhere(query);
 }
Пример #42
0
        public string BuildPagingSQL(QueryInfo info)
        {
            #region re-calculate limition
            int iCount       = info.TotalCount;
            int iStartRecord = info.StartRecord;
            int iPageSize    = info.PageSize;

            if (iCount > -1)
            {
                //startRecord excceed maxRecord,reset
                if (iCount <= iStartRecord)
                {
                    iStartRecord     = iCount / iPageSize; //2.3=>2 取整
                    iStartRecord     = iStartRecord * iPageSize;
                    info.StartRecord = iStartRecord;       //Start Index changed.
                }

                //Should Reset Last Page's PageSize?
                //存在仅Take数据, 未预先查询count值
                //int iLasPageSize = iCount - iStartRecord;
                //if (iLasPageSize > 0 && iLasPageSize < iPageSize)
                //    iPageSize = iLasPageSize;
            }
            #endregion
            if (ConnectionManager.ParamPrefix != "?")
            {
                if (ConnectionManager.ConnectionTypeName.StartsWith("MySql."))
                {
                    return(string.Format("{0} {1} LIMIT {2},{3}",
                                         info.ToSQLString(),
                                         info.ToOrderBy(),
                                         iStartRecord, iPageSize));
                }
                else if (ConnectionManager.ParamPrefix == ":")//ORACLE
                {
                    return(string.Format("SELECT r2.* FROM ( SELECT rownum rn,r1.* FROM ( {2} ) r1 WHERE rownum <= {0} ) r2 WHERE r2.rn > {1}"
                                         , iStartRecord + iPageSize, iStartRecord, info.ToSQLString() + info.ToOrderBy()));
                }
                else//SQL Server?
                {
                    return(string.Format(@"SELECT r2.* FROM ( SELECT ROW_NUMBER() OVER (ORDER BY {1}) AS rn,{0} ) r2 WHERE r2.rn BETWEEN {2} AND {3}"
                                         , info.ToSQLString().Substring(6)           //trim select
                                         , string.Join(",", info.OrderBys.ToArray()) //then get order by
                                         , iStartRecord + 1, iStartRecord + iPageSize));

                    #region Trim all dots and Reverse Order
                    //if (info.OrderBy.Count == 0)
                    //    throw new Exception("'order by' must be supplied for sql server 2000 paging.");
                    ////A.USER_CDE DESC => USER_CDE ASC
                    //System.Text.StringBuilder sbOriginalOrder = new System.Text.StringBuilder();
                    //System.Text.StringBuilder sbReversedOrder = new System.Text.StringBuilder();
                    //for (int i = 0; i < info.OrderBy.Count; i++)
                    //{
                    //    string ord = info.OrderBy[i];
                    //    if (ord.IndexOf(".") > 0)
                    //        ord = ord.Substring(ord.IndexOf(".") + 1);//trim table alias

                    //    sbOriginalOrder.Append(ord);
                    //    if (ord.IndexOf(" DESC") > -1)
                    //        sbReversedOrder.Append(ord.Replace(" DESC", " ASC"));
                    //    else if (ord.IndexOf(" ASC") > -1)
                    //        sbReversedOrder.Append(ord.Replace(" ASC", " DESC"));
                    //    else
                    //        sbReversedOrder.Append(ord + " DESC");

                    //    sbOriginalOrder.Append(",");
                    //    sbReversedOrder.Append(",");
                    //}
                    //sbOriginalOrder.Remove(sbOriginalOrder.Length - 1, 1);
                    //sbReversedOrder.Remove(sbReversedOrder.Length - 1, 1);//trim last ','
                    #endregion
                    //return string.Format("SELECT r2.* FROM(SELECT TOP {0} r1.* FROM(SELECT TOP {1} {2}) r1 ORDER BY {3})r2 ORDER BY {4}"
                    //, iPageSize, iStartRecord + iPageSize, info.ToSQLString().Substring(6) + info.ToOrderBy(), sbReversedOrder, sbOriginalOrder);//Substring(6):trim 'SELECT' in QueryObject
                }
            }
            return(info.ToSQLString() + info.ToOrderBy());
        }
Пример #43
0
 protected override void SetQuery(QueryInfo query)
 {
     query.Query <ImageEntity>().Where(it => it.Folder.Id == FolderId && it.Account.Id == 0);
     base.SetQuery(query);
 }
        /// <summary>
        /// Call from CefClient::OnProcessMessageReceived. Returns true if the message
        /// is handled by this router or false otherwise.
        /// </summary>
        public bool OnProcessMessageReceived(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage message)
        {
            Helpers.RequireUIThread();

            var messageName = message.Name;

            if (messageName == _queryMessageName)
            {
                var args = message.Arguments;
                Debug.Assert(args.Count == 6);

                var frameId    = Helpers.Int64Set(args.GetInt(0), args.GetInt(1));
                var contextId  = args.GetInt(2);
                var requestId  = args.GetInt(3);
                var request    = args.GetString(4);
                var persistent = args.GetBool(5);

                if (_handlerSet.Count == 0)
                {
                    // No handlers so cancel the query.
                    CancelUnhandledQuery(browser, contextId, requestId);
                    return(true);
                }

                var browserId = browser.Identifier;
                var queryId   = _queryIdGenerator.GetNextId();

                var frame    = browser.GetFrame(frameId);
                var callback = new Callback(this, browserId, queryId, persistent);

                // Make a copy of the handler list in case the user adds or removes a
                // handler while we're iterating.
                var handlers = _handlerSet.ToArray();

                var     handled = false;
                Handler handler = null;
                foreach (var x in handlers)
                {
                    handled = x.OnQuery(browser, frame, queryId, request, persistent, callback);
                    if (handled)
                    {
                        handler = x;
                        break;
                    }
                }

                // If the query isn't handled nothing should be keeping a reference to
                // the callback.
                // DCHECK(handled || callback->GetRefCt() == 1);
                // Debug.Assert(handled && handler != null);
                // We don't need this assertion, in GC environment.
                // There is client responsibility to do not reference callback, if request is not handled.

                if (handled)
                {
                    // Persist the query information until the callback executes.
                    // It's safe to do this here because the callback will execute
                    // asynchronously.
                    var info = new QueryInfo
                    {
                        Browser    = browser,
                        FrameId    = frameId,
                        ContextId  = contextId,
                        RequestId  = requestId,
                        Persistent = persistent,
                        Callback   = callback,
                        Handler    = handler,
                    };
                    _browserQueryInfoMap.Add(browserId, queryId, info);
                }
                else
                {
                    // Invalidate the callback.
                    callback.Detach();

                    // No one chose to handle the query so cancel it.
                    CancelUnhandledQuery(browser, contextId, requestId);
                }

                return(true);
            }
            else if (messageName == _cancelMessageName)
            {
                var args = message.Arguments;
                Debug.Assert(args.Count == 2);

                var browserId = browser.Identifier;
                var contextId = args.GetInt(0);
                var requestId = args.GetInt(1);

                CancelPendingRequest(browserId, contextId, requestId);
                return(true);
            }

            return(false);
        }
Пример #45
0
 public virtual IList <OrdersAccompanyingGoodsInfo> GetOrdersAccompanyingGoodss(QueryInfo Query)
 {
     return(MyDAL.GetOrdersAccompanyingGoodss(Query));
 }
Пример #46
0
        //a track was selected
        private void track_clicked(object o, ButtonReleaseEventArgs args)
        {
            LinkLabel label = (LinkLabel)o;

            QueryInfo query = new QueryInfo (Key.Artist(main.Artist), Key.Title(label.Link));
            main.LoadContent (query, typeof (SimilarTracks));
        }
Пример #47
0
        public virtual IList <SupplierPriceReportDetailInfo> GetSupplierPriceReportDetails(QueryInfo Query)
        {
            int PageSize;
            int CurrentPage;
            IList <SupplierPriceReportDetailInfo> entitys = null;
            SupplierPriceReportDetailInfo         entity = null;
            string        SqlList, SqlField, SqlOrder, SqlParam, SqlTable;
            SqlDataReader RdrList = null;

            try
            {
                CurrentPage = Query.CurrentPage;
                PageSize    = Query.PageSize;
                SqlTable    = "Supplier_PriceReport_Detail";
                SqlField    = "*";
                SqlParam    = DBHelper.GetSqlParam(Query.ParamInfos);
                SqlOrder    = DBHelper.GetSqlOrder(Query.OrderInfos);
                SqlList     = DBHelper.GetSqlPage(SqlTable, SqlField, SqlParam, SqlOrder, CurrentPage, PageSize);
                RdrList     = DBHelper.ExecuteReader(SqlList);
                if (RdrList.HasRows)
                {
                    entitys = new List <SupplierPriceReportDetailInfo>();
                    while (RdrList.Read())
                    {
                        entity                         = new SupplierPriceReportDetailInfo();
                        entity.Detail_ID               = Tools.NullInt(RdrList["Detail_ID"]);
                        entity.Detail_PriceReportID    = Tools.NullInt(RdrList["Detail_PriceReportID"]);
                        entity.Detail_PurchaseID       = Tools.NullInt(RdrList["Detail_PurchaseID"]);
                        entity.Detail_PurchaseDetailID = Tools.NullInt(RdrList["Detail_PurchaseDetailID"]);
                        entity.Detail_Amount           = Tools.NullInt(RdrList["Detail_Amount"]);
                        entity.Detail_Price            = Tools.NullDbl(RdrList["Detail_Price"]);

                        entitys.Add(entity);
                        entity = null;
                    }
                }
                return(entitys);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (RdrList != null)
                {
                    RdrList.Close();
                    RdrList = null;
                }
            }
        }
Пример #48
0
        protected override bool WfExecReport(Stimulsoft.Report.StiReport pReport)
        {
            //DataSet ds;
            vw_invr337       invr337Model;
            StringBuilder    sbSql   = null;
            string           sqlBody = "";
            DataTable        dtIlaTb;
            List <QueryInfo> queryInfoList;
            QueryInfo        queryModel;
            string           strQueryRange, strWhere;
            StringBuilder    sbQuerySingle = null;

            List <SqlParameter> sqlParmList;
            List <Master>       resultList = null;

            try
            {
                invr337Model  = DrMaster.ToItem <vw_invr337>();
                resultList    = new List <Master>();
                queryInfoList = new List <QueryInfo>();
                #region range 處理
                if (!GlobalFn.varIsNull(invr337Model.ifa01))
                {
                    queryModel            = new QueryInfo();
                    queryModel.TableName  = "ifa_tb";
                    queryModel.ColumnName = "ifa01";
                    queryModel.ColumnType = TabMaster.DtSource.Columns["ifa01"].DataType.Name;
                    queryModel.Value      = invr337Model.ifa01;
                    queryInfoList.Add(queryModel);
                }
                if (!GlobalFn.varIsNull(invr337Model.ifa03))
                {
                    queryModel            = new QueryInfo();
                    queryModel.TableName  = "ifa_tb";
                    queryModel.ColumnName = "ifa03";
                    queryModel.ColumnType = TabMaster.DtSource.Columns["ifa03"].DataType.Name;
                    queryModel.Value      = invr337Model.ifa03;
                    queryInfoList.Add(queryModel);
                }
                if (!GlobalFn.varIsNull(invr337Model.ifa04))
                {
                    queryModel            = new QueryInfo();
                    queryModel.TableName  = "ifa_tb";
                    queryModel.ColumnName = "ifa04";
                    queryModel.ColumnType = TabMaster.DtSource.Columns["ifa04"].DataType.Name;
                    queryModel.Value      = invr337Model.ifa04;
                    queryInfoList.Add(queryModel);
                }
                if (!GlobalFn.varIsNull(invr337Model.ifa06))
                {
                    queryModel            = new QueryInfo();
                    queryModel.TableName  = "ifa_tb";
                    queryModel.ColumnName = "ifa06";
                    queryModel.ColumnType = TabMaster.DtSource.Columns["ifa06"].DataType.Name;
                    queryModel.Value      = invr337Model.ifa04;
                    queryInfoList.Add(queryModel);
                }
                sqlParmList   = new List <SqlParameter>();
                strQueryRange = BoMaster.WfGetQueryString(queryInfoList, out sqlParmList);
                #endregion

                #region single 處理
                sbQuerySingle = new StringBuilder();
                if (!GlobalFn.varIsNull(invr337Model.ifa02_s))
                {
                    sbQuerySingle.AppendLine("AND ifa02>=@ifa02_s");
                    sqlParmList.Add(new SqlParameter("@ifa02_s", invr337Model.ifa02_s));
                }
                if (!GlobalFn.varIsNull(invr337Model.ifa02_e))
                {
                    sbQuerySingle.AppendLine("AND ifa02<=@ifa02_e");
                    sqlParmList.Add(new SqlParameter("@ifa02_s", invr337Model.ifa02_e));
                }

                if (invr337Model.doc_status != "0")
                {
                    if (invr337Model.doc_status == "1") //撥出在途
                    {
                        sbQuerySingle.AppendLine("AND ISNULL(ifa09,'N') = 'N'");
                    }
                    if (invr337Model.doc_status == "2") //撥入確認
                    {
                        sbQuerySingle.AppendLine("AND ifaconf = 'Y'");
                    }
                }
                #endregion

                strWhere = strQueryRange + " " + sbQuerySingle.ToString();
                var strSecurity = WfGetSecurityString();        //取得權限字串
                if (!GlobalFn.varIsNull(strSecurity))
                {
                    strWhere += strSecurity;
                }

                //取得單頭
                sqlBody = @"
                              SELECT 
                                ifa01,ifa02,ifa03,bec02 as ifa03_c ,
                                ifa04,beb03 AS ifa04_c,ifa05,ifa06,
                                ifa09,ifaconf,
                                ifb02,ifb03,ifb04,ifb05,'' as ifb05_str,ifb06,
                                bej03,ifb07,
                                ifb08,'' as ifb08_str,ifb09,ifb10,
                                ica03
                              FROM ifa_tb
                                    LEFT JOIN ifb_tb ON ifa01=ifb01
                                    LEFT JOIN bec_tb ON ifa03=bec01
                                    LEFT JOIN beb_tb ON ifa04=beb01
                                    LEFT JOIN bej_tb ON ifb06=bej01
                                    LEFT JOIN ica_tb ON ifb03=ica01
                              WHERE ifa00='2'
                                AND ifb01 IS NOT NULL
                                AND ifaconf='Y'
                                ";

                dtIlaTb           = BoMaster.OfGetDataTable(string.Concat(sqlBody, strWhere), sqlParmList.ToArray());
                dtIlaTb.TableName = "Master";
                if (dtIlaTb != null)
                {
                    resultList.AddRange(dtIlaTb.ToList <Master>());
                }

                if (resultList == null || resultList.Count == 0)
                {
                    WfShowErrorMsg("查無資料,請重新過濾條件!");
                    return(false);
                }

                foreach (Master masterModel in resultList)
                {
                    //數量處理
                    masterModel.ifb05_str = string.Format("{0:N" + masterModel.bej03 + "}", masterModel.ifb05); //數量
                    masterModel.ifb08_str = string.Format("{0:N" + masterModel.bej03 + "}", masterModel.ifb08); //數量
                }

                pReport.RegData("master", resultList);
                pReport.CacheAllData = true;

                pReport.Compile();
                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #49
0
        public override DataTable GetCustomSmallTypeData( QueryInfo queryInfo)
        {
            List<SqlParameter> list = new List<SqlParameter>();

            StringBuilder strSql = new StringBuilder();
            strSql.Append("Select * ");
            strSql.Append(" From CustomSmallType ");
            strSql.Append(" Where 1=1 ");

            SqlQueryInfo sqi = sqlHelper.ParseQueryInfo(queryInfo);
            if (sqi != null)
            {
                strSql.Append(" " + sqi.WhereClause);

                if (!Globals.IsNullorEmpty(sqi.OrderClause))
                    strSql.Append(" Order By " + sqi.OrderClause);

                list.AddRange(sqi.Parameters);
            }

            DataSet ds;

            try
            {
                ds = DbHelperSQL.Query(strSql.ToString(),list.ToArray());
            }
            catch (SqlException ex)
            {
                throw ex;
            }

            return ds.Tables[0];
        }
Пример #50
0
 protected override void SetQueryWhere(QueryInfo query)
 {
     query.Query <AbilityEntity>().Where(
         it => it.RoleAbilities.Count(s => s.Role.Id == Request["roleid"].Convert <long>()) == 0 && it.Menu.Subsystem.Url.StartsWith("PresentationAdmin"));
     base.SetQueryWhere(query);
 }
 /// <inheritdoc />
 protected override QueryItemInfo GetQueryForGroups(QueryInfo query, InstanceVersion version)
 {
     return query.GroupSelect.GetQueryItemForVersion(version);
 }
Пример #52
0
 /// <summary>
 /// Applies the order filter.
 /// </summary>
 /// <param name="query">The query.</param>
 /// <param name="info">The information.</param>
 /// <returns></returns>
 protected abstract IQueryable ApplyOrderFilter(IQueryable query, QueryInfo info);
Пример #53
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="query"></param>
 /// <param name="provider"></param>
 /// <param name="expression"></param>
 public Queryable(QueryInfo query, QueryProvider provider, Expression expression)
 {
     Provider   = provider;
     Expression = expression;
     Query      = query;
 }
Пример #54
0
 /// <summary>
 /// Applies the where filter.
 /// </summary>
 /// <param name="query">The query.</param>
 /// <param name="info">The information.</param>
 /// <returns></returns>
 protected abstract IQueryable ApplyWhereFilter(IQueryable query, QueryInfo info);
 private void SendQuerySuccess(QueryInfo info, string response)
 {
     SendQuerySuccess(info.Browser, info.ContextId, info.RequestId, response);
 }
Пример #56
0
 /// <summary>
 /// 得到查询
 /// </summary>
 /// <param name="dbRoute"></param>
 /// <param name="shardings"></param>
 /// <param name="query"></param>
 /// <param name="result"></param>
 /// <returns></returns>
 protected virtual void AppendQueryByShardings(IList <QueryInfo> result, DbRouteInfo dbRoute, IList <ShardingInfo> shardings, QueryInfo query)
 {
     if (shardings.Count == 1)
     {
         var sharding = shardings[0];
         query.TableIndex = string.IsNullOrWhiteSpace(sharding.TableIndex)
             ? sharding.TableIndex
             : sharding.TableIndex.ToLower();
         query.GetDataBase = string.IsNullOrWhiteSpace(sharding.GetDataBase)
             ? sharding.GetDataBase
             : sharding.GetDataBase.ToLower();
         result.Add(query);
     }
     else
     {
         foreach (var sharding in shardings)
         {
             var cloneQuery = GetQuery(dbRoute, query, sharding);
             if (cloneQuery != null &&
                 result.Count(
                     it =>
                     it.GetDataBase == cloneQuery.GetDataBase &&
                     it.GetTableName == cloneQuery.GetTableName) == 0)
             {
                 result.Add(cloneQuery);
             }
         }
     }
 }
Пример #57
0
        protected override bool WfExecReport(Stimulsoft.Report.StiReport pReport)
        {
            vw_invr402       invr402Model;
            StringBuilder    sbSql      = null;
            string           sqlBody    = "";
            string           sqlOrderBy = "";
            DataTable        dtMaster;
            List <Master>    masterList;
            List <QueryInfo> queryInfoList;
            QueryInfo        queryModel;
            string           strQueryRange, strWhere;
            StringBuilder    sbQuerySingle = null;

            List <SqlParameter> sqlParmList;

            try
            {
                if (Vw_Invr402 != null) //他窗引用時
                {
                    invr402Model = Vw_Invr402;
                }
                else
                {
                    invr402Model = DrMaster.ToItem <vw_invr402>();
                }

                queryInfoList = new List <QueryInfo>();
                #region range 處理
                if (!GlobalFn.varIsNull(invr402Model.ima01))
                {
                    queryModel            = new QueryInfo();
                    queryModel.TableName  = "ima_tb";
                    queryModel.ColumnName = "ima01";
                    queryModel.ColumnType = TabMaster.DtSource.Columns["ima01"].DataType.Name;
                    queryModel.Value      = invr402Model.ima01;
                    queryInfoList.Add(queryModel);
                }
                if (!GlobalFn.varIsNull(invr402Model.ima03))
                {
                    queryModel            = new QueryInfo();
                    queryModel.TableName  = "ima_tb";
                    queryModel.ColumnName = "ima03";
                    queryModel.ColumnType = TabMaster.DtSource.Columns["ima03"].DataType.Name;
                    queryModel.Value      = invr402Model.ima03;
                    queryInfoList.Add(queryModel);
                }
                sqlParmList   = new List <SqlParameter>();
                strQueryRange = BoMaster.WfGetQueryString(queryInfoList, out sqlParmList);
                #endregion

                #region single 處理
                sbQuerySingle = new StringBuilder();
                if (!GlobalFn.varIsNull(invr402Model.ima02_s))
                {
                    sbQuerySingle.AppendLine("AND ima02>=@ima02_s");
                    sqlParmList.Add(new SqlParameter("@ima02_s", invr402Model.ima02_s));
                }
                if (!GlobalFn.varIsNull(invr402Model.ima02_e))
                {
                    sbQuerySingle.AppendLine("AND ima02<=@ima02_e");
                    sqlParmList.Add(new SqlParameter("@ima02_e", invr402Model.ima02_e));
                }
                #endregion

                strWhere = strQueryRange + " " + sbQuerySingle.ToString();
                var strSecurity = WfGetSecurityString();        //取得權限字串
                if (!GlobalFn.varIsNull(strSecurity))
                {
                    strWhere += strSecurity;
                }

                //取得單頭
                sqlBody = @"SELECT ima_tb.*,
                                sca02 as ima03_c,
                                bec02 as ima04_c,
                                beb02 as ima05_c,
                                bab02 as ima01_c,
                                imb02,imb03,imb04,imb05,imb06,
                                imb11,imb12,imb17,imb18,imb19,
                                bej03
                            FROM ima_tb                                
                                LEFT JOIN imb_tb ON ima01=imb01
	                            LEFT JOIN sca_tb ON ima03=sca01	--客戶
	                            LEFT JOIN bec_tb ON ima04=bec01	--員工
	                            LEFT JOIN beb_tb ON ima05=beb01	--部門
	                            LEFT JOIN baa_tb ON 1=1	
	                            LEFT JOIN bab_tb ON substring(ima01,1,baa06)=bab01
                                LEFT JOIN ica_tb ON imb03=ica01
                                LEFT JOIN bej_tb ON imb03=bej01
                            WHERE 1=1 
                                AND imaconf='Y'
                           ";
                //處理排序
                switch (invr402Model.order_by)
                {
                case "1":    //1.依借出日期
                    sqlOrderBy = " ORDER BY ima02";
                    break;

                case "2":    //2.依客戶
                    sqlOrderBy = " ORDER BY ima03";
                    break;
                }
                dtMaster           = BoMaster.OfGetDataTable(string.Concat(sqlBody, strWhere, sqlOrderBy), sqlParmList.ToArray());
                dtMaster.TableName = "Master";

                if (dtMaster == null || dtMaster.Rows.Count == 0)
                {
                    WfShowErrorMsg("查無資料,請重新過濾條件!");
                    return(false);
                }
                masterList = dtMaster.ToList <Master>(true);
                foreach (Master masterModel in masterList)
                {
                    masterModel.imb05_str = string.Format("{0:N" + masterModel.bej03 + "}", masterModel.imb05);//數量
                }

                pReport.RegData("Master", masterList);
                pReport.CacheAllData = true;
                ////處理跳頁
                StiGroupFooterBand footerBand1 = (StiGroupFooterBand)pReport.GetComponents()["GroupFooterBand1"];
                if (invr402Model.jump_yn.ToUpper() == "Y")
                {
                    footerBand1.NewPageAfter    = true;
                    footerBand1.ResetPageNumber = true;
                }
                else
                {
                    footerBand1.NewPageAfter    = false;
                    footerBand1.ResetPageNumber = false;
                }

                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 private void SendQueryFailure(QueryInfo info, int errorCode, string errorMessage)
 {
     SendQueryFailure(info.Browser, info.ContextId, info.RequestId, errorCode, errorMessage);
 }
        private void DoSearch(bool explain)
        {
            var search = new SitecoreSearcher(SessionManager.Instance.CurrentIndex);
            var infos = new QueryInfo[]
                {
                    new QueryInfo()
                    {
                        FieldName = txtFieldName1.Text,
                        SearchString = txtSearchWord1.Text,
                        QueryType = SitecoreQueryType1.Dropdown.SelectedValue,
                        QueryOccurance = QueryOccurance1.Dropdown.SelectedValue
                    },
                    new QueryInfo()
                    {
                        FieldName = txtFieldName2.Text,
                        SearchString = txtSearchWord2.Text,
                        QueryType = SitecoreQueryType2.Dropdown.SelectedValue,
                        QueryOccurance = QueryOccurance2.Dropdown.SelectedValue
                    },
                    new QueryInfo()
                    {
                        FieldName = txtFieldName3.Text,
                        SearchString = txtSearchWord3.Text,
                        QueryType = SitecoreQueryType3.Dropdown.SelectedValue,
                        QueryOccurance = QueryOccurance3.Dropdown.SelectedValue
                    }
                };

            if (explain)
                search.Explain = SearchResultGrid.SelectedIndex;

            SessionManager.Instance.SitecoreSearchResult = search.FieldSearch(infos, 200);

            txtExplanation.Text = explain ? search.Explanation.ToString() : string.Empty;
        }
Пример #60
0
        public async Task TestCosmosOrderByQueryExecutionContextWithFailurePageAsync(bool createInitialContinuationToken)
        {
            int maxPageSize = 5;

            List <MockPartitionResponse[]> mockResponsesScenario = MockQueryFactory.GetFailureScenarios();

            Mock <CosmosQueryClient> mockQueryClient = new Mock <CosmosQueryClient>();

            foreach (MockPartitionResponse[] mockResponse in mockResponsesScenario)
            {
                string initialContinuationToken = null;
                string fullContinuationToken    = null;
                if (createInitialContinuationToken)
                {
                    ToDoItem itemToRepresentPreviousQuery = ToDoItem.CreateItems(
                        1,
                        "itemToRepresentPreviousQuery",
                        MockQueryFactory.DefaultCollectionRid).First();

                    initialContinuationToken = $" - RID:{itemToRepresentPreviousQuery._rid} ==#RT:1#TRC:1";
                    CompositeContinuationToken compositeContinuation = new CompositeContinuationToken()
                    {
                        Range = new Documents.Routing.Range <string>(
                            min: MockQueryFactory.DefaultPartitionKeyRange.MinInclusive,
                            max: MockQueryFactory.DefaultPartitionKeyRange.MaxExclusive,
                            isMaxInclusive: false,
                            isMinInclusive: true),
                        Token = initialContinuationToken
                    };

                    List <OrderByItem> orderByItems = new List <OrderByItem>()
                    {
                        new OrderByItem(CosmosObject.CreateFromBuffer(Encoding.UTF8.GetBytes("{\"item\":\"2c4ce711-13c3-4c93-817c-49287b71b6c3\"}")))
                    };

                    OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken(
                        compositeContinuationToken: compositeContinuation,
                        orderByItems: orderByItems,
                        rid: itemToRepresentPreviousQuery._rid,
                        skipCount: 0,
                        filter: null);

                    fullContinuationToken = CosmosArray.Create(
                        new List <CosmosElement>()
                    {
                        OrderByContinuationToken.ToCosmosElement(orderByContinuationToken)
                    }).ToString();
                }

                IList <ToDoItem> allItems = MockQueryFactory.GenerateAndMockResponse(
                    mockQueryClient,
                    isOrderByQuery: true,
                    sqlQuerySpec: MockQueryFactory.DefaultQuerySpec,
                    containerRid: MockQueryFactory.DefaultCollectionRid,
                    initContinuationToken: initialContinuationToken,
                    maxPageSize: maxPageSize,
                    mockResponseForSinglePartition: mockResponse,
                    cancellationTokenForMocks: this.cancellationToken);

                // Order by drains the partitions until it finds an item
                // If there are no items then it's not possible to have a continuation token
                if (allItems.Count == 0 && createInitialContinuationToken)
                {
                    continue;
                }

                CosmosQueryContext context = MockQueryFactory.CreateContext(
                    mockQueryClient.Object);

                QueryInfo queryInfo = new QueryInfo()
                {
                    OrderBy            = new SortOrder[] { SortOrder.Ascending },
                    OrderByExpressions = new string[] { "id" }
                };

                CosmosCrossPartitionQueryExecutionContext.CrossPartitionInitParams initParams = new CosmosCrossPartitionQueryExecutionContext.CrossPartitionInitParams(
                    sqlQuerySpec: MockQueryFactory.DefaultQuerySpec,
                    collectionRid: MockQueryFactory.DefaultCollectionRid,
                    partitionedQueryExecutionInfo: new PartitionedQueryExecutionInfo()
                {
                    QueryInfo = queryInfo
                },
                    partitionKeyRanges: new List <PartitionKeyRange>()
                {
                    MockQueryFactory.DefaultPartitionKeyRange
                },
                    initialPageSize: maxPageSize,
                    maxConcurrency: null,
                    maxItemCount: maxPageSize,
                    maxBufferedItemCount: null,
                    returnResultsInDeterministicOrder: true,
                    testSettings: new TestInjections(simulate429s: false, simulateEmptyPages: false));

                TryCatch <IDocumentQueryExecutionComponent> tryCreate = await CosmosOrderByItemQueryExecutionContext.TryCreateAsync(
                    context,
                    initParams,
                    fullContinuationToken != null?CosmosElement.Parse(fullContinuationToken) : null,
                    this.cancellationToken);

                if (tryCreate.Succeeded)
                {
                    IDocumentQueryExecutionComponent executionContext = tryCreate.Result;

                    Assert.IsTrue(!executionContext.IsDone);

                    // Read all the pages from both splits
                    List <ToDoItem>   itemsRead = new List <ToDoItem>();
                    QueryResponseCore?failure   = null;
                    while (!executionContext.IsDone)
                    {
                        QueryResponseCore queryResponse = await executionContext.DrainAsync(
                            maxPageSize,
                            this.cancellationToken);

                        if (queryResponse.IsSuccess)
                        {
                            string responseContinuationToken = queryResponse.ContinuationToken;
                            foreach (CosmosElement element in queryResponse.CosmosElements)
                            {
                                string   jsonValue = element.ToString();
                                ToDoItem item      = JsonConvert.DeserializeObject <ToDoItem>(jsonValue);
                                itemsRead.Add(item);
                            }
                        }
                        else
                        {
                            Assert.IsNull(failure, "There should only be one error");
                            failure = queryResponse;
                        }
                    }

                    Assert.IsNotNull(failure);
                    Assert.AreEqual((HttpStatusCode)429, failure.Value.StatusCode);
                    Assert.IsNotNull(failure.Value.CosmosException.ToString());

                    Assert.AreEqual(0 /*We don't get any items, since we don't buffer the failure anymore*/, itemsRead.Count);

                    //CollectionAssert.AreEqual(allItems.ToList(), itemsRead, new ToDoItemComparer());
                }
                else
                {
                    QueryResponseCore queryResponseCore = QueryResponseFactory.CreateFromException(tryCreate.Exception);
                    Assert.AreEqual((HttpStatusCode)429, queryResponseCore.StatusCode);
                }
            }
        }