Exemplo n.º 1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        bool displayLocal = WebDialogueContext.GetDialogueParameter<bool>("DisplayLocal", true);
        QueryData qd = new QueryData();
        qd.AddField("UserGroupId", DataValueType.IntegerType);
        qd.AddField("Name", DataValueType.ShortStringType);

        qd.AddRow(SystemUserGroupType.Anonymous, Local.Text("Web.WAF.Dialogues.Main.AccessUserGroup.BuiltInForAnonymous"));
        qd.AddRow(SystemUserGroupType.AllUsers, Local.Text("Web.WAF.Dialogues.Main.AccessUserGroup.BuiltInForSystemUsers"));
         qd.AddRow(SystemUserGroupType.Administrator, Local.Text("Web.WAF.Dialogues.Main.AccessUserGroup.BuiltInForAdmin"));

        if (displayLocal) {
            foreach (UserGroup g in WAFContext.Session.GetContents<UserGroup>(null, AqlUserGroup.Name).OrderBy(g => g.Name)) {
                qd.AddRow(g.NodeId, g.Name);
            }
        }
        contentList.IQuery = new DataQuery(qd);
        if (!displayLocal) {
            MainButton btnSearchLocal = new MainButton();
            Controls.Add(btnSearchLocal);
            btnSearchLocal.Text = "Search local groups...";
            btnSearchLocal.Click += new EventHandler(btnSearchLocal_Click);
            WebDialogueContext.AddDialogueButton(btnSearchLocal);
        }
        MainButton btn = new MainButton();
        Controls.Add(btn);
        btn.Text = "Select";
        btn.Click += new EventHandler(contentList_DblClick);
        WebDialogueContext.AddDialogueButton(btn);
    }
        public void TestUpdate()
        {
            var entityManager = new EntityManager("Manager", "#37!eert");
            QueryData careerJobCreditsQuery = new QueryData("CareerJobCredits");
            careerJobCreditsQuery.AddCriteria(CriteriaData.Equal("PartyId", "77755"));
            FindResultsData careerJobCredits = entityManager.Find(careerJobCreditsQuery);
            GenericEntityData data = (GenericEntityData)careerJobCredits.Result[0];
            data["J_Credits"] = 0;
            ValidateResultsData result = entityManager.Update(data);

        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NavMeshQuery"/> class.
        /// </summary>
        /// <param name="nav">The navigation mesh to query.</param>
        /// <param name="maxNodes">The maximum number of nodes that can be queued in a query.</param>
        /// <param name="rand">A random number generator for use in methods like <see cref="NavMeshQuery.FindRandomPoint()"/></param>
        public NavMeshQuery(TiledNavMesh nav, int maxNodes, Random rand)
        {
            this.nav = nav;

            nodePool = new NodePool(maxNodes/*, MathHelper.NextPowerOfTwo(maxNodes / 4)*/);
            tinyNodePool = new NodePool(64/*, 32*/);
            openList = new PriorityQueue<NavNode>(maxNodes);

            this.rand = rand;

            this.query = new QueryData();
        }
Exemplo n.º 4
0
		static QueryData GetQueryData(SelectQuery selectQuery)
		{
			var data = new QueryData { Query = selectQuery };

			new QueryVisitor().VisitParentFirst(selectQuery, e =>
			{
				switch (e.ElementType)
				{
					case QueryElementType.SqlField :
						{
							var field = (SqlField)e;

							if (field.Name.Length != 1 || field.Name[0] != '*')
								data.Fields.Add(field);

							break;
						}

					case QueryElementType.SqlQuery :
						{
							if (e != selectQuery)
							{
								data.Queries.Add(GetQueryData((SelectQuery)e));
								return false;
							}

							break;
						}

					case QueryElementType.Column :
						return ((SelectQuery.Column)e).Parent == selectQuery;

					case QueryElementType.SqlTable :
						return false;
				}

				return true;
			});

			return data;
		}
Exemplo n.º 5
0
        /// <summary>
        /// 查询方法
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public override Task <QueryData <TModel> > QueryAsync(QueryPageOptions option)
        {
            // 处理过滤与快捷搜索框逻辑
            var query = _db.Set <TModel>()
                        .Where(option.Searchs.GetFilterLambda <TModel>(FilterLogic.Or), option.Searchs.Any())
                        .Where(option.Filters.GetFilterLambda <TModel>(), option.Filters.Any())
                        .Sort(option.SortName !, option.SortOrder, !string.IsNullOrEmpty(option.SortName))
                        .Count(out var count)
                        .Page((option.PageIndex - 1) * option.PageItems, option.PageItems);

            // 注意:未处理搜索,此处设置 IsSearched=true 后会导致高级搜索按钮高亮
            var ret = new QueryData <TModel>()
            {
                TotalCount = count,
                Items      = query,
                IsSorted   = true,
                IsFiltered = true
            };

            return(Task.FromResult(ret));
        }
Exemplo n.º 6
0
        private static void CreateField(Hit hit, DataRow row, QueryData query)
        {
            if (query.DocValueFields == null)
            {
                return;
            }

            foreach (var docValueField in query.DocValueFields)
            {
                var value = row.Table.Columns.Contains(docValueField) ? row[docValueField] : null;
                if (value == null)
                {
                    continue;
                }

                // datetime fields are written as is, usually in UTC timezone.
                hit.Fields.Add(docValueField, new List <object> {
                    value
                });
            }
        }
Exemplo n.º 7
0
        private void InitData(OrderInfo order)
        {
            OrderEntity oe = new OrderEntity();


            List <ITextValueItem> queryList = new List <ITextValueItem>();

            QueryData qd = new QueryData();

            qd.Text                      = "待我审核的单据";
            qd.Value                     = "AuditedOrder";
            qd.QueryExpression           = QueryExpressionHelper.Equal("AuditedBy", DataCore.CurrentUser.Value.ToString());
            qd.QueryExpression.QueryType = order.Type;
            queryList.Add(qd);

            CommonFunction.FillComboBox(this.cbbQueryList, queryList);

            cbbQueryList.SelectedIndex = 0;

            GetOrders();
        }
Exemplo n.º 8
0
        /// <summary>
        /// Returns a list of dynamic objects that represent the data
        /// </summary>
        /// <param name="qd">The data</param>
        /// <returns></returns>
        public static List <dynamic> ToDynamicList(this QueryData qd)
        {
            List <dynamic> toReturn = new List <dynamic>();

            if (qd.QuerySuccessful)
            {
                foreach (QueryRow o in qd)
                {
                    dynamic newRecord = new ExpandoObject();
                    var     d         = newRecord as IDictionary <string, object>;
                    foreach (string s in qd.GetFields())
                    {
                        d.Add(s, o.GetDataForRowField(s));
                    }

                    toReturn.Add(newRecord);
                }
            }

            return(toReturn);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Generates the order by clause.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="data">The data.</param>
        /// <returns>Order by clause</returns>
        private string GenerateOrderByClause(Utils.TreeNode <Type> node, QueryData <TMappedClass> data)
        {
            var    Builder     = ObjectPool.Get();
            var    Splitter    = string.Empty;
            string ReturnValue = string.Empty;

            if (data.OrderByValues.Count == 0)
            {
                var Mapping = MappingInformation.Mappings[node.Data];
                for (int x = 0, nodeNodesCount = node.Nodes.Count; x < nodeNodesCount; x++)
                {
                    var ParentNode   = node.Nodes[x];
                    var ParentResult = GenerateOrderByClause(ParentNode, data);
                    if (!string.IsNullOrEmpty(ParentResult))
                    {
                        return(ParentResult);
                    }
                }
                foreach (var IDProperty in Mapping.IDProperties)
                {
                    Builder.Append(Splitter)
                    .Append(GetColumnName(IDProperty));
                    Splitter = ",";
                }
                ReturnValue = Builder.ToString();
                ObjectPool.Return(Builder);
                return(ReturnValue);
            }

            foreach (var Column in data.OrderByValues.OrderBy(x => x.Order))
            {
                Builder.Append(Splitter)
                .Append(Column.Property.Name)
                .Append(Column.Direction == Direction.Descending ? " DESC" : "");
                Splitter = ",";
            }
            ReturnValue = Builder.ToString();
            ObjectPool.Return(Builder);
            return(ReturnValue);
        }
Exemplo n.º 10
0
        public virtual QueryData Query(string query)
        {
            QueryData data = new QueryData();

            _command.CommandText = query;
            System.Data.Common.DbDataReader reader = _command.ExecuteReader();

            while (reader.Read())
            {
                Objects.DbObject row = new Objects.RowObject();
                for (int loop = 0; loop < reader.FieldCount; loop++)
                {
                    string name = reader.GetName(loop);
                    row.Data.Add(name, reader[loop]);
                }

                data.Add(row);
            }

            reader.Close();
            return(data);
        }
Exemplo n.º 11
0
        public async Task Test_MultiSelect_WithRefcursors()
        {
            QueryOptions options = new QueryOptions()
            {
                ConnectionFactory = () => new OracleConnection("DATA SOURCE=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ORCLCDB.localdomain)));USER ID=sys;PASSWORD=Oradoc_db1;DBA Privilege=SYSDBA"),
                Schemas           = DatabaseHelper.Default.Schemas,
            };

            QueryData query = new QueryData()
            {
                QueryText  = "BEGIN OPEN :P0 FOR SELECT 1 AS Item FROM dual; OPEN :P1 FOR SELECT 2 AS Item FROM dual; END;",
                Parameters = new IParameter[] { new Refcursor("P0"), new Refcursor("P1") },
            };

            QueryHandler handler = new QueryHandler(options);

            IList <int> result1 = handler.List <int>(query);
            IList <int> result2 = await handler.ListAsync <int>(query);

            result1.ShouldBe(new[] { 1, 2 });
            result2.ShouldBe(new[] { 1, 2 });
        }
Exemplo n.º 12
0
        public override ReplyData ExecuteQuery(string i_IP, int i_Port, ClientInfo clientInfo, object CurObj)
        {
            QueryData SysInfoQueryData = new QueryData();

            SysInfoQueryData.Type = Consts.SectionType.ExplorerLogicalDrive;


            if (CurObj == null || CurObj.ToString() == "")
            {
                SysInfoQueryData.ArrCounter.Add(new ObjectMetaData(CurObj.ToString(), "OSLogicalDrives"));
            }
            else
            {
                SysInfoQueryData.ArrCounter.Add(new ObjectMetaData(CurObj.ToString(), "ViewPath"));
            }
            SysInfoQueryData.CurrClient = clientInfo;
            string    QueryString  = SysInfoQueryData.Serialize();
            String    ReplyString  = Comm.SendQuery(i_IP, i_Port, QueryString);
            ReplyData ReplyDataObj = ReplyData.Deserialize(ReplyString);

            return(ReplyDataObj);
        }
Exemplo n.º 13
0
        public async Task <IActionResult> HealthTitleUpdate(HealthTitleUpdateViewModel model)
        {
            var query = new QueryData <HealthTitleUpdateQuery>()
            {
                Criteria = new HealthTitleUpdateQuery()
                {
                    TitleId    = model.TitleId,
                    Content    = model.Content,
                    Type       = model.Type,
                    IsMustFill = model.IsMustFill,
                    Sort       = model.Sort,
                    IsShow     = model.IsShow
                },
                Extend = new QueryExtend()
                {
                    UserNo = CurrentUser.UserNo
                }
            };
            var result = await _manager.HealthTitleUpdateAsync(query);

            return(Ok(result));
        }
Exemplo n.º 14
0
        private void GetOrders()
        {
            ShowProcess();
            QueryData       dataQueryList = cbbQueryList.SelectedItem as QueryData;
            QueryExpression qeTop         = new QueryExpression();

            qeTop.QueryType = this.OrderType;
            QueryExpression qe = qeTop;

            qe.RelatedType = QueryExpression.RelationType.And;

            if (dataQueryList != null)
            {
                qe.RelatedExpression = dataQueryList.QueryExpression;
                qe = qe.RelatedExpression;
            }
            if (qeTop.RelatedExpression != null)
            {
                qeTop = qeTop.RelatedExpression;
            }
            OrderSource.QueryFBEntities(qeTop);
        }
Exemplo n.º 15
0
        public async Task <DataResult <List <ISysGroupModel> > > GetGroupsPageAsync(QueryData <SysGroupQuery> query)
        {
            var lr = new DataResult <List <ISysGroupModel> >();

            StringBuilder builder      = new StringBuilder();
            string        sqlCondition = string.Empty;

            StringHelper.ParameterAdd(builder, "GroupNo = @GroupNo", query.Criteria.GroupNo);
            StringHelper.ParameterAdd(builder, "GroupName like concat('%',@GroupName,'%')", query.Criteria.GroupName);
            StringHelper.ParameterAdd(builder, "Code = @Code", query.Criteria.Code);
            StringHelper.ParameterAdd(builder, "ParentNo = @ParentNo", query.Criteria.ParentNo);
            StringHelper.ParameterAdd(builder, "AppNo = @AppNo", query.Criteria.AppNo);
            StringHelper.ParameterAdd(builder, "IsDelete = @IsDelete", query.Criteria.IsDelete);
            if (builder.Length > 0)
            {
                sqlCondition = " where " + builder.ToString();
            }
            string sql = @"select Id,GroupNo,GroupName,Code,Descr,ParentNo,AppNo,Access,Creator,CreateName,CreateTime,Updator,UpdateName,UpdateTime,IsDelete
                from sys_group"
                         + sqlCondition;

            using (IDbConnection dbConn = MysqlHelper.OpenMysqlConnection(ConfigOptions.MysqlSearchConn))
            {
                try
                {
                    var modelList = await MysqlHelper.QueryPageAsync <SysGroupModel>(dbConn, "GroupName asc", sql, query.PageModel, query.Criteria);

                    lr.Data     = modelList.ToList <ISysGroupModel>();
                    lr.PageInfo = query.PageModel;
                }
                catch (Exception ex)
                {
                    lr.SetErr(ex, -500);
                    lr.Data = null;
                }
            }

            return(lr);
        }
Exemplo n.º 16
0
        private void ParseRequestQueryParameters()
        {
            if (this.HasQueryString())
            {
                var parameters = this.Url.Split('?', '#')[1]
                                 .Split('&')
                                 .Select(plainQueryParameter => plainQueryParameter.Split('='))
                                 .ToList();

                foreach (var parameter in parameters)
                {
                    if (!QueryData.ContainsKey(parameter[0]))
                    {
                        QueryData.Add(parameter[0], new HashSet <string> {
                            (parameter[1])
                        });
                    }

                    QueryData[parameter[0]].Add(WebUtility.UrlDecode(parameter[1]));
                }
            }
        }
Exemplo n.º 17
0
        public async Task <ActionResult> GetUsersAllAsync(GetUserAllViewModel model)
        {
            var query = new QueryData <SysUserQuery>()
            {
                Criteria = new SysUserQuery()
                {
                    UserNo    = model.UserNo,
                    UserName  = model.UserName,
                    StaffNo   = model.StaffNo,
                    AdAccount = model.AdAccount,
                    Mobile    = model.Mobile,
                    Email     = model.Email,
                    RealName  = model.RealName,
                    CompanyNo = model.CompanyNo,
                    Access    = model.Access,
                    IsDelete  = model.IsDelete
                }
            };
            var result = await _manager.GetUserAllAsync(query);

            return(Ok(result));
        }
Exemplo n.º 18
0
        public async Task <DataResult <List <ISysModuleModel> > > GetModulesAllAsync(QueryData <SysModuleQuery> query)
        {
            var lr = new DataResult <List <ISysModuleModel> >();

            StringBuilder builder      = new StringBuilder();
            string        sqlCondition = string.Empty;

            StringHelper.ParameterAdd(builder, "ModuleNo = @ModuleNo", query.Criteria.ModuleNo);
            StringHelper.ParameterAdd(builder, "ModuleName like concat('%',@ModuleName,'%')", query.Criteria.ModuleName);
            StringHelper.ParameterAdd(builder, "IsDelete = @IsDelete", query.Criteria.IsDelete);
            StringHelper.ParameterAdd(builder, "AppNo = @AppNo", query.Criteria.AppNo);
            StringHelper.StringAdd(builder, "ParentNo = @ParentNo", query.Criteria.ParentNo);

            if (builder.Length > 0)
            {
                sqlCondition = " where " + builder.ToString();
            }
            string sql = @"select Id,ModuleNo,ModuleName,ParentNo,Icon,Url,Category,Target,AppNo,Creator,CreateName,CreateTime,Updator,UpdateName,UpdateTime,IsDelete,Sort,RouterName,
                (select count(Id) from sys_module where ParentNo=a.ModuleNo and IsDelete=false) ChildrenCount
                from sys_module a"
                         + sqlCondition;

            using (IDbConnection dbConn = MysqlHelper.OpenMysqlConnection(ConfigOptions.MysqlSearchConn))
            {
                try
                {
                    var modelList = await MysqlHelper.QueryListAsync <SysModuleModel>(dbConn, sql, "Sort asc", query.Criteria);

                    lr.Data = modelList.ToList <ISysModuleModel>();
                }
                catch (Exception ex)
                {
                    lr.SetErr(ex, -500);
                    lr.Data = null;
                }
            }

            return(lr);
        }
Exemplo n.º 19
0
        public static DataTable GetProductRelation(int Language, int ID, DBOperationManagment dbm)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append(@"select pcd.ProductDetailID RelatinProductDetailID,(pcd.Title+'+'+pcm.ProductModel) Title from ProductCenterDetail pcd
inner join ProductCenterModel pcm on pcd.ProductModelID=pcm.ProductModelID where 1=1  ");
            strSql.AppendFormat(" and pcd.Language={0} and pcd.ID!={1} ", Language == 0 ? 1 : Language, ID);
            QueryData exec = new QueryData();

            exec.SqlCommand = strSql.ToString();
            exec.Parameters = null;

            dbm.Execute(exec);
            if (exec.ResultData != null && exec.ResultData.Tables != null && exec.ResultData.Tables.Count > 0)
            {
                return(exec.ResultData.Tables[0]);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 20
0
            public void InvalidFilterPropertyNameIndicatesInvalidData()
            {
                const string expectedColumnName = "Valid";

                bool ValidateColumn(string s) => s == expectedColumnName;

                var fields  = new [] { expectedColumnName };
                var filters = new []
                {
                    new Filter // Badly named filter
                    {
                        Property = "Not_Valid",
                        Values   = new dynamic[] { 1 }
                    },
                };

                var(query, fakeValidColumns, fakeClauseFactory) = Builder.InitializeFakeItemsForQueryData(fields, filters, columnIsInvalid: ValidateColumn);
                var sut = new QueryData(query, fakeValidColumns.Object, fakeClauseFactory.Object, "MY_TABLE");

                Assert.False(sut.IsValid);
                Assert.True(sut.IsInvalid);
            }
Exemplo n.º 21
0
        public async Task <ActionResult> UserSaveOrUpdateAsync(UserSaveOrUpdateViewModel model)
        {
            var query = new QueryData <SysUserSaveOrUpdateQuery>()
            {
                Criteria = new SysUserSaveOrUpdateQuery()
                {
                    UserNo         = model.UserNo,
                    UserName       = model.UserName,
                    StaffNo        = model.StaffNo,
                    AdAccount      = model.AdAccount,
                    Mobile         = model.Mobile,
                    Email          = model.Email,
                    Pwd            = model.Pwd,
                    RealName       = model.RealName,
                    IsAdmin        = model.IsAdmin,
                    Icon           = model.Icon,
                    AppNo          = model.AppNo,
                    CompanyNo      = model.CompanyNo,
                    ApprovedBy     = model.ApprovedBy,
                    ApprovedName   = model.ApprovedName,
                    Descr          = model.Descr,
                    RejectedBy     = model.RejectedBy,
                    RejectedName   = model.RejectedName,
                    RejectedReason = model.RejectedReason,
                    Access         = model.Access,
                    IsDelete       = model.IsDelete
                },
                Extend = new QueryExtend()
                {
                    UserNo   = CurrentUser.UserNo,
                    UserName = CurrentUser.UserName,
                    IsAdmin  = CurrentUser.IsAdmin
                }
            };
            var result = await _manager.UserSaveOrUpdateAsync(query);

            return(Ok(result));
        }
Exemplo n.º 22
0
        /// <summary>
        /// 根据工号获取人员信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task <ErrData <HealthStaff> > GetHealthStaffInfoAsync(QueryData <GetHealthStaffInfoQuery> query)
        {
            var         result      = new ErrData <HealthStaff>();
            HealthStaff healthStaff = null;
            var         dt          = DateTime.Now;

            var res = await HealthMobileOperaters.Health_staffServiceOperater.GetHealthStaffInfo(query);

            if (res.HasErr)
            {
                result.SetInfo(res.ErrMsg, res.ErrCode);
            }
            else
            {
                if (res.Data.Count > 0)
                {
                    healthStaff                 = new HealthStaff();
                    healthStaff.AggLeader       = res.Data[0].AggLeader;
                    healthStaff.AggLeaderNo     = res.Data[0].AggLeaderNo;
                    healthStaff.CommandLeader   = res.Data[0].CommandLeader;
                    healthStaff.CommondLeaderNo = res.Data[0].CommondLeaderNo;
                    healthStaff.GroupLeader     = res.Data[0].GroupLeader;
                    healthStaff.GroupLeaderNo   = res.Data[0].GroupLeaderNo;
                    healthStaff.GroupType       = res.Data[0].GroupType;
                    healthStaff.HrLeader        = res.Data[0].HrLeader;
                    healthStaff.HrLeaderNo      = res.Data[0].HrLeaderNo;
                    healthStaff.Id              = res.Data[0].Id;
                    healthStaff.StaffName       = res.Data[0].StaffName;
                    healthStaff.StaffNo         = res.Data[0].StaffNo;
                }

                result.Data = healthStaff;
                result.SetInfo(healthStaff, "获取成功", 200);
            }

            result.ExpandSeconds = (DateTime.Now - dt).TotalSeconds;
            return(result);
        }
Exemplo n.º 23
0
        protected async override Task <int> ExecuteCommandAsync(StoreOptions options)
        {
            DirectoryInfo queriesDir = null;

            if (options.Global)
            {
                var appDir    = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
                var cosmicDir = appDir.CreateSubdirectory("cosmic");
                queriesDir = cosmicDir.CreateSubdirectory("queries");
            }
            else
            {
                queriesDir = new DirectoryInfo(".");
            }

            var parameters = new string[]
            {
                options.Value1, options.Value2, options.Value3,
                options.Value4, options.Value5, options.Value6,
                options.Value7, options.Value8, options.Value9
            };

            var query = new QueryData
            {
                Query      = options.Query,
                Parameters = parameters
                             .TakeWhile(x => x != null)
                             .Select(x => new ParameterData
                {
                    DefaultValue = x
                })
                             .ToArray()
            };

            await File.WriteAllTextAsync($"{queriesDir}/{options.Name}.json", JsonConvert.SerializeObject(query));

            return(0);
        }
Exemplo n.º 24
0
        internal static async Task <Tuple <int, int, int, List <InformationChartData> > > getGradeValuesByFilters(string GradeFolder, List <Tuple <string, string, string> > filters)
        {
            var queriesData = await HttpProvider.GetHttpRequest(StaticParams.TfsUrl, "Enterprise/_apis/wit/queries/Shared%20Queries/Release%20Dashboard/" + GradeFolder + "?$depth=1");

            QueriesDataRequest queriesDataObject = JsonConvert.DeserializeObject <QueriesDataRequest>(queriesData);
            List <QueryData>   Querieslst        = new List <QueryData>();

            foreach (var item in queriesDataObject.children)
            {
                var queryData = new QueryData()
                {
                    Id = item.id, Name = item.name
                };
                var workItemData = await GetWorkItemData(queryData.Id, filters);

                queryData.workItems = workItemData.Item1;
                var wiql = workItemData.Item2.Replace("=", "%3D");
                item._links.html.href = wiql;
                Querieslst.Add(queryData);
            }
            int critical = Querieslst.FirstOrDefault(q => q.Name.Contains("Critical #")).workItems.WorkItemCount;
            int high     = Querieslst.FirstOrDefault(q => q.Name.Contains("High #")).workItems.WorkItemCount;
            int medium   = Querieslst.FirstOrDefault(q => q.Name.Contains("Medium #")).workItems.WorkItemCount;

            var infoData = new List <InformationChartData> {
                new InformationChartData {
                    Data = critical.ToString(), DataName = "Critical", Wiql = queriesDataObject.children.FirstOrDefault(q => q.name.Contains("Critical #"))._links.html.href
                },
                new InformationChartData {
                    Data = high.ToString(), DataName = "High", Wiql = queriesDataObject.children.FirstOrDefault(q => q.name.Contains("High #"))._links.html.href
                },
                new InformationChartData {
                    Data = medium.ToString(), DataName = "Medium", Wiql = queriesDataObject.children.FirstOrDefault(q => q.name.Contains("Medium #"))._links.html.href
                }
            };

            return(new Tuple <int, int, int, List <InformationChartData> >(critical, high, medium, infoData));
        }
Exemplo n.º 25
0
        public void borrowBook(Book a)  // thoi gian muon trong 2 tuan
        {
            DateTime date = DateTime.Now;

            if (setBook.Count <= 2) // moi lan muon toi da 3 cuon sach
            {
                SqlConnection connect = QueryData.Connect_Server();

                String query = "INSERT INTO Bookitem (IDBook,IDUser,Title,Borrowed,Duedate,Bkstatus) VALUES('" + a.IDBook.ToString().Trim() + "','" + idUser.ToString().Trim() + "',N'" + a.Titletext.Trim() + "',CONVERT(datetime, '" + date.ToShortDateString().ToString() + "', 103)  ,  CONVERT(datetime, '" + date.AddDays(14).ToShortDateString().ToString() + "',103),'" + "Being borrowed" + "')";
                bool   kq    = QueryData.ExecuteNonQueryBook(connect, query); // thuc thi luu du lieu
                if (kq)
                {
                    setBook.Add(new Bookitem {
                        IDBook = a.IDBook, IDUser = idUser, Titletext = a.Titletext, Borrowtime = date, DueTime = date.AddDays(14), Statusbool = "Booked"
                    });
                    MessageBox.Show("Borrowed successfully !!!!");
                }
            }
            else
            {
                MessageBox.Show("Only borrow max three book");
            }
        }
Exemplo n.º 26
0
    void LoginValidationAPI()
    {
        QueryData serverRequestInfo = new QueryData
        {
            requestUpdateType = SERVER_UPDATE_REQUEST_TYPE.LOGIN
        };


        serverRequestInfo.keyValuePairs.Add(ServerConstants.USER_NAME, "srikanth");
        serverRequestInfo.keyValuePairs.Add(ServerConstants.PASSWORD, "srikanth");



        serverRequestInfo.statusResponseString.Add(ServerConstants.VALIDATION_RESULT);

        ServerAPIHandler.Instance.serverStateManager.UpdateGameState(serverRequestInfo, (object callBack) =>
        {
            //if (callBack == null || callBack.GetType().Equals(typeof(bool)))
            //{
            //    DisplayPopUP_InternetCheck();
            //}
        });
    }
Exemplo n.º 27
0
        /// <summary>
        /// Loads the object info.
        /// </summary>
        /// <param name="tables">The tables.</param>
        /// <param name="columns">The columns.</param>
        /// <param name="table">The table.</param>
        /// <returns></returns>
        protected virtual DBObject LoadObjectInfo(QueryRow table, QueryData columns)
        {
            DBObject t = new DBObject();

            ObjectBuilder.SetFieldData(_dstore, table, t);
            t.Columns = new List <Column>();

            foreach (QueryRow row in columns)         //all of the columns for all of the tables were returned, so we need to only get the one I'm working on...
            {
                if (row.FieldHasMapping("TableName")) //make sure the table name is present
                {
                    if (row.GetDataForRowField("TableName").ToString().Equals(t.Name, StringComparison.InvariantCultureIgnoreCase) &&
                        row.GetDataForRowField("Schema").ToString().Equals(t.Schema, StringComparison.InvariantCultureIgnoreCase)) //make sure its the right table
                    {
                        if (row.FieldHasMapping("ColumnName"))
                        {
                            AddColumnToDBObject(row, t);
                        }
                    }
                }
            }
            return(t);
        }
Exemplo n.º 28
0
        private static void CreateSort(Hit hit, DataRow row, QueryData query)
        {
            if (query.SortFields == null)
            {
                return;
            }

            foreach (var sortField in query.SortFields)
            {
                var value = row.Table.Columns.Contains(sortField) ? row[sortField] : null;
                if (value == null)
                {
                    continue;
                }

                if (value is DateTime)
                {
                    value = TimeUtils.ToEpochMilliseconds((DateTime)value);
                }

                hit.Sort.Add(value);
            }
        }
Exemplo n.º 29
0
        public User Check()
        {
            // ket noi database
            SqlConnection connect = QueryData.Connect_Server();

            // mo Database va viet cau truy van  , co dau cach nen co dong ngoac [User Name]
            String    query   = "Select * from Account where UseName = '" + textBox1.Text.Trim() + "' and passwordID = '" + textBox2.Text.Trim() + "'";
            DataTable dt      = QueryData.Queryresult(connect, query); // tra ra du lieu cua cau truy van
            User      userlog = null;

            if (dt.Rows.Count == 1)  // neu chi co 1 mau du lieu khop
            {
                userlog = new User(Int32.Parse(dt.Rows[0][0].ToString()), dt.Rows[0][1].ToString().Trim(), dt.Rows[0][2].ToString().Trim(), dt.Rows[0][3].ToString().Trim(), dt.Rows[0][4].ToString().Trim());


                return(userlog);// lay hang [0][0] cua Rows la UserName
            }
            else
            {
                MessageBox.Show("Username or password incorrect");  // thong bao khi dang nhap ko thanh coong
                return(userlog);
            }
        }
Exemplo n.º 30
0
        public async Task <ActionResult> AppSaveOrUpdateAsync(AppSaveOrUpdateViewModel model)
        {
            var query = new QueryData <SysAppSaveOrUpdateQuery>()
            {
                Criteria = new SysAppSaveOrUpdateQuery()
                {
                    AppNo    = model.AppNo,
                    AppName  = model.AppName,
                    Leader   = model.Leader,
                    Deploy   = model.Deploy,
                    Remark   = model.Remark,
                    IsDelete = model.IsDelete
                },
                Extend = new QueryExtend()
                {
                    UserNo   = CurrentUser.UserNo,
                    UserName = CurrentUser.UserName
                }
            };
            var result = await _manager.AppSaveOrUpdateAsync(query);

            return(Ok(result));
        }
Exemplo n.º 31
0
        public async Task <ErrData <byte[]> > HealthContentExcelExportAsync(QueryData <HealthContentQuery> query)
        {
            var result = new ErrData <byte[]>();
            var dt     = DateTime.Now;

            var table = await GetHealthContentPageAsyncEx(query);

            if (table.HasErr)
            {
                result.SetInfo(table.Msg, table.Code);
            }
            else
            {
                result.Data = EPPlusHelper.ExcelExport("体检表", table.Results[0]);
                if (result.Data == null || result.Data.Length == 0)
                {
                    result.SetInfo("无数据导出!", -102);
                }
            }

            result.ExpandSeconds = (DateTime.Now - dt).TotalSeconds;
            return(result);
        }
Exemplo n.º 32
0
        public async Task <ListResult <ISysAppModel> > GetAppAllAsync(QueryData <SysAppQuery> query)
        {
            var lr = new ListResult <ISysAppModel>();
            var dt = DateTime.Now;

            var res = await _service.GetAppsAllAsync(query);

            if (res.HasErr)
            {
                lr.SetInfo(res.ErrMsg, res.ErrCode);
            }
            else
            {
                foreach (var item in res.Data)
                {
                    lr.Results.Add(item);
                }
                lr.SetInfo("成功", 200);
            }

            lr.ExpandSeconds = (DateTime.Now - dt).TotalSeconds;
            return(lr);
        }
Exemplo n.º 33
0
        public async Task <ActionResult> RoleSaveOrUpdateAsync(RoleSaveOrUpdateViewModel model)
        {
            var query = new QueryData <SysRoleSaveOrUpdateQuery>()
            {
                Criteria = new SysRoleSaveOrUpdateQuery()
                {
                    RoleNo   = model.RoleNo,
                    RoleName = model.RoleName,
                    Descr    = model.Descr,
                    AppNo    = model.AppNo,
                    Access   = model.Access,
                    IsDelete = model.IsDelete
                },
                Extend = new QueryExtend()
                {
                    UserNo   = CurrentUser.UserNo,
                    UserName = CurrentUser.UserName
                }
            };
            var result = await _manager.RoleSaveOrUpdateAsync(query);

            return(Ok(result));
        }
Exemplo n.º 34
0
        public void MapRowsToHits_WithSort_ReturnsHitsWithSort(string field, object expectedValue)
        {
            // Arrange
            using var table = SampleData();
            var query = new QueryData(
                "myKQL",
                "myIndex",
                sortFields: new List <string> {
                field
            },
                highlightText: new Dictionary <string, string> {
                { "*", "boxes" },
            });

            // Assert
            var highlight = JToken.FromObject(new string[] { "FooboxesBar" });

            expected[0]["highlight"] = new JObject
            {
                ["label1"] = highlight,
                ["label2"] = highlight,
                ["label3"] = JToken.FromObject(
                    new string[]
                {
                    "FooboxesBar of FooboxesBar",
                }),
            };
            expected[0]["sort"]    = JToken.FromObject(new object[] { expectedValue });
            query.HighlightPreTag  = "Foo";
            query.HighlightPostTag = "Bar";

            // Act
            var hits = ReadHits(table, query);

            // Assert
            AssertHits(hits);
        }
        public void DuplicateQueryDetectionMessageFilter_GroupsAdjecentQueryMessages(QueryData queryData) {
            // given
            IMessageFilter messageFilter = new DuplicateQueryDetectionMessageFilter();

            // when
            Queue<Message> messages = new Queue<Message>(messageFilter.Filter(queryData.Messages));

            // then
            foreach (int msgCount in queryData.ReturnedMessages) {
                if (msgCount == Single) {
                    Message message = messages.Dequeue();

                    Assert.That(message, Is.Not.InstanceOf<DuplicateQueryMessage>(), "Expected a singular message to be returned");
                    continue;
                }

                // find group
                DuplicateQueryMessage groupMessage = (DuplicateQueryMessage)messages.Dequeue();

                // assert group size
                Assert.IsNotNull(groupMessage, "Cannot find grouped query - expected at least a group to be found of size "+msgCount);
                Assert.That(groupMessage.NumberOfQueries, Is.EqualTo(msgCount), "Incorrect query group message size");
            }
        }
Exemplo n.º 36
0
 void initFiles()
 {
     lstFiles.DblClick += new EventHandler(lstFiles_DblClick);
     QueryData qd = new QueryData();
     qd.AddField("guid", DataValueType.ShortStringType);
     qd.AddField("icon", DataValueType.ShortStringType);
     qd.AddField("path", DataValueType.ShortStringType);
     qd.AddField("errors", DataValueType.ShortStringType);
     qd.AddField("tooltip", DataValueType.LongStringType);
     foreach (string source in _sourceFiles.OrderBy(f => f)) {
         Guid guid = new Guid(Path.GetFileNameWithoutExtension(source));
         string tempPath = getTempFileName(guid);
         var relevantErrors = _errors.Where(er => String.Compare(er.FileName, tempPath, true) == 0).ToList();
         string path = HttpUtility.HtmlEncode(getShortFileName(guid));
         string icon;
         string tooltip;
         if (relevantErrors.Count > 0) {
             tooltip = relevantErrors.Count > 1 ? relevantErrors.Count + " errors:<br/><br/>" : "1 error:<br/><br/>";
             if (relevantErrors.Where(ee => !ee.IsWarning).Count() == 0) {
                 icon = "Images/Warning.png";
             } else {
                 icon = "Images/Error.png";
             }
             foreach (var err in relevantErrors) {
                 tooltip += replacePaths(err.ErrorText) + "<br/>Ln " + err.Line + " col " + err.Column + "<br/><br/>";
             }
         } else {
             path = "<span style='color:gray;'>" + path + "</span>";
             tooltip = "No errors";
             icon = WAFContext.GetUrlFromHostToFileExtensionIcon(".cs", WAFContext.UI.Skin.Url);
         }
         icon = "<img src='" + icon + "'/>";
         qd.AddRow(guid.ToString(), icon, path, relevantErrors.Count > 0 ? relevantErrors.Count.ToString() : "", tooltip);
     }
     lstFiles.IQuery = new DataQuery(qd);
 }
Exemplo n.º 37
0
        /// <summary>
        /// Initialize a sliced path, which is used mostly for crowd pathfinding.
        /// </summary>
        /// <param name="startPoint">The start point.</param>
        /// <param name="endPoint">The end point.</param>
        /// <returns>True if path initialized, false otherwise</returns>
        public bool InitSlicedFindPath(NavPoint startPoint, NavPoint endPoint)
        {
            //validate input
            if (startPoint.Polygon == PolyId.Null || endPoint.Polygon == PolyId.Null)
                return false;

            if (!nav.IsValidPolyRef(startPoint.Polygon) || !nav.IsValidPolyRef(endPoint.Polygon))
                return false;

            if (startPoint.Polygon == endPoint.Polygon)
            {
                query.Status = true;
                return true;
            }

            //init path state
            query = new QueryData();
            query.Status = false;
            query.Start = startPoint;
            query.End = endPoint;

            nodePool.Clear();
            openList.Clear();

            Node startNode = nodePool.GetNode(startPoint.Polygon);
            startNode.Pos = startPoint.Position;
            startNode.ParentIdx = 0;
            startNode.cost = 0;
            startNode.total = (endPoint.Position - startPoint.Position).Length() * H_SCALE;
            startNode.Id = startPoint.Polygon;
            startNode.Flags = NodeFlags.Open;
            openList.Push(startNode);

            query.Status = true;
            query.LastBestNode = startNode;
            query.LastBestNodeCost = startNode.total;

            return query.Status;
        }
Exemplo n.º 38
0
    void setQueryTreeList()
    {
        QueryData qd = new QueryData();
        qd.AddField("Value", DataValueType.ShortStringType);
        qd.AddField("Text", DataValueType.ShortStringType);

        qd.AddRow(((int)MessageStatus.Inbox).ToString(), Local.Text("Web.WAF.Edit.Messages.DefaultInbox"));

        qd.AddRow(((int)MessageStatus.Draft).ToString(), Local.Text("Web.WAF.Edit.Messages.DefaultDraft"));

        qd.AddRow(((int)MessageStatus.Outbox).ToString(), Local.Text("Web.WAF.Edit.Messages.DefaultOutbox"));

        qd.AddRow(((int)MessageStatus.Sendt).ToString(), Local.Text("Web.WAF.Edit.Messages.DefaultSendt"));
        foreach (IDataValue[] dv in qd.Data) {
            ShortStringDataValue s = (ShortStringDataValue)dv[1];
            s.Value = WAFContext.GetHtmlClassIcon(FileFolder.ContentClassId, "margin:0px 3px -4px 3px; ") + s.Value;
        }
        lstTree.BorderWidth = 0;
        lstTree.IQuery = new DataQuery(qd);
    }
Exemplo n.º 39
0
        /// <summary>
        /// Save the sliced path 
        /// </summary>
        /// <param name="path">The path in terms of polygon references</param>
        /// <param name="pathCount">The path length</param>
        /// <param name="maxPath">The maximum path length allowed</param>
        /// <returns>True if the path is saved, false if not</returns>
        public bool FinalizeSlicedFindPath(Path path)
        {
            path.Clear();

            if (query.Status == false)
            {
                query = new QueryData();
                return false;
            }

            int n = 0;

            if (query.Start.Polygon == query.End.Polygon)
            {
                //special case: the search starts and ends at the same poly
                path.Add(query.Start.Polygon);
            }
            else
            {
                //reverse the path
                NavNode prev = null;
                NavNode node = query.LastBestNode;
                NodeFlags prevRay = 0;
                do
                {
                    NavNode next = nodePool.GetNodeAtIdx(node.ParentIndex);
                    node.ParentIndex = nodePool.GetNodeIdx(prev);
                    prev = node;
                    NodeFlags nextRay = node.Flags & NodeFlags.ParentDetached;
                    node.Flags = (node.Flags & ~NodeFlags.ParentDetached) | prevRay;
                    prevRay = nextRay;
                    node = next;
                }
                while (node != null);

                //store path
                node = prev;
                do
                {
                    NavNode next = nodePool.GetNodeAtIdx(node.ParentIndex);
                    if ((node.Flags & NodeFlags.ParentDetached) != 0)
                    {
                        RaycastHit hit;
                        Path m = new Path();
                        NavPoint startPoint = new NavPoint(node.Id, node.Position);
                        bool result = Raycast(ref startPoint, ref next.Position, RaycastOptions.None, out hit, m);
                        path.AppendPath(m);

                        if (path[path.Count - 1] == next.Id)
                            path.RemoveAt(path.Count - 1);
                    }
                    else
                    {
                        path.Add(node.Id);
                    }

                    node = next;
                }
                while (node != null);
            }

            //reset query
            query = new QueryData();

            return true;
        }
Exemplo n.º 40
0
    protected QueryData GetSalesSummaryQuery()
    {
        QueryData qd = new QueryData();
        DateTime now = DateTime.Now;
        qd.AddField("PeriodName", DataValueType.ShortStringType);
        qd.AddField("NumOrders", DataValueType.ShortStringType);
        qd.AddField("TotalRevenue", DataValueType.ShortStringType);
        qd.AddField("AverageOrderValue", DataValueType.ShortStringType);
        qd.AddField("BiggestOrder", DataValueType.ShortStringType);
        qd.AddField("MostPopularProductRevenue", DataValueType.IntegerType);
        qd.AddField("MostPopularProductNumItems", DataValueType.IntegerType);

        //Fetch sales summary data
        //Today
        SalesSummaryData todaySalesData = WebshopStatistics.GetSalesSummaryData(GetReportPeriod(DefaultReportPeriod.Today));
        qd.AddRow(
              "Today",
               todaySalesData.NumberOfOrders.ToString(),
               todaySalesData.TotalRevenue.ToString("N2"),
               todaySalesData.AverageOrderValue.ToString("N2"),
               todaySalesData.BiggestOrder.ToString("N2"),
               todaySalesData.MostPopularProductRevenueNodeId,
               todaySalesData.MostPopularProductNumberOfItemsNodeId
               );
        //Yesterday
        SalesSummaryData yesterdaySalesData = WebshopStatistics.GetSalesSummaryData(GetReportPeriod(DefaultReportPeriod.Yesterday));
        qd.AddRow(
              "Yesterday",
               yesterdaySalesData.NumberOfOrders.ToString(),
               yesterdaySalesData.TotalRevenue.ToString("N2"),
               yesterdaySalesData.AverageOrderValue.ToString("N2"),
               yesterdaySalesData.BiggestOrder.ToString("N2"),
               yesterdaySalesData.MostPopularProductRevenueNodeId,
               yesterdaySalesData.MostPopularProductNumberOfItemsNodeId
               );
        //Last 7 days
        SalesSummaryData lastSevenDaysSalesData = WebshopStatistics.GetSalesSummaryData(GetReportPeriod(DefaultReportPeriod.Last7days));
        qd.AddRow(
              "Last 7 days",
               lastSevenDaysSalesData.NumberOfOrders.ToString(),
               lastSevenDaysSalesData.TotalRevenue.ToString("N2"),
               lastSevenDaysSalesData.AverageOrderValue.ToString("N2"),
               lastSevenDaysSalesData.BiggestOrder.ToString("N2"),
               lastSevenDaysSalesData.MostPopularProductRevenueNodeId,
               lastSevenDaysSalesData.MostPopularProductNumberOfItemsNodeId
               );
        //Last 30 days
        SalesSummaryData lastThirtyDaysSalesData = WebshopStatistics.GetSalesSummaryData(GetReportPeriod(DefaultReportPeriod.Last30Days));
        qd.AddRow(
              "Last 30 days",
               lastThirtyDaysSalesData.NumberOfOrders.ToString(),
               lastThirtyDaysSalesData.TotalRevenue.ToString("N2"),
               lastThirtyDaysSalesData.AverageOrderValue.ToString("N2"),
               lastThirtyDaysSalesData.BiggestOrder.ToString("N2"),
               lastThirtyDaysSalesData.MostPopularProductRevenueNodeId,
               lastThirtyDaysSalesData.MostPopularProductNumberOfItemsNodeId
               );
        //This Month
        SalesSummaryData thisMonthSalesData = WebshopStatistics.GetSalesSummaryData(GetReportPeriod(DefaultReportPeriod.ThisMonth));
        qd.AddRow(
              "This month",
               thisMonthSalesData.NumberOfOrders.ToString(),
               thisMonthSalesData.TotalRevenue.ToString("N2"),
               thisMonthSalesData.AverageOrderValue.ToString("N2"),
               thisMonthSalesData.BiggestOrder.ToString("N2"),
               thisMonthSalesData.MostPopularProductRevenueNodeId,
               thisMonthSalesData.MostPopularProductNumberOfItemsNodeId
               );
        //Last month
        SalesSummaryData lastMonthSalesData = WebshopStatistics.GetSalesSummaryData(GetReportPeriod(DefaultReportPeriod.LastMonth));
        qd.AddRow(
              "Last month",
               lastMonthSalesData.NumberOfOrders.ToString(),
               lastMonthSalesData.TotalRevenue.ToString("N2"),
               lastMonthSalesData.AverageOrderValue.ToString("N2"),
               lastMonthSalesData.BiggestOrder.ToString("N2"),
                lastMonthSalesData.MostPopularProductRevenueNodeId,
               lastMonthSalesData.MostPopularProductNumberOfItemsNodeId
               );
        //This year
        SalesSummaryData thisYearSalesData = WebshopStatistics.GetSalesSummaryData(GetReportPeriod(DefaultReportPeriod.ThisYear));
        qd.AddRow(
              "This year",
               thisYearSalesData.NumberOfOrders.ToString(),
               thisYearSalesData.TotalRevenue.ToString("N2"),
               thisYearSalesData.AverageOrderValue.ToString("N2"),
               thisYearSalesData.BiggestOrder.ToString("N2"),
               thisYearSalesData.MostPopularProductRevenueNodeId,
               thisYearSalesData.MostPopularProductNumberOfItemsNodeId
               );
        //Last year
        SalesSummaryData lastYearSalesData = WebshopStatistics.GetSalesSummaryData(GetReportPeriod(DefaultReportPeriod.LastYear));
        qd.AddRow(
              "Last year",
               lastYearSalesData.NumberOfOrders.ToString(),
               lastYearSalesData.TotalRevenue.ToString("N2"),
               lastYearSalesData.AverageOrderValue.ToString("N2"),
               lastYearSalesData.BiggestOrder.ToString("N2"),
               lastYearSalesData.MostPopularProductRevenueNodeId,
               lastYearSalesData.MostPopularProductNumberOfItemsNodeId
               );
        //Total
        SalesSummaryData allTimeSalesData = WebshopStatistics.GetSalesSummaryData(GetReportPeriod(DefaultReportPeriod.AllTime));
        qd.AddRow(
              "All time",
               allTimeSalesData.NumberOfOrders.ToString(),
               allTimeSalesData.TotalRevenue.ToString("N2"),
               allTimeSalesData.AverageOrderValue.ToString("N2"),
               allTimeSalesData.BiggestOrder.ToString("N2"),
               allTimeSalesData.MostPopularProductRevenueNodeId,
               allTimeSalesData.MostPopularProductNumberOfItemsNodeId
               );
        //Average pr day.
        qd.AddRow(
              "Avg per day",
               GetAverageNumberOfOrdersPerDay().ToString(),
               GetAverageRevenuePerDay().ToString("N2"),
               "",
               "",
               0,
               0
               );
        //(GetAverageRevenuePerDay() / (double)GetAverageNumberOfOrdersPerDay()).ToString("N2"),
        //Average pr month.
        qd.AddRow(
              "Avg per month",
               GetAverageNumberOfOrdersPerMonth().ToString(),
               GetAverageRevenuePerMonth().ToString("N2"),
               "",
               "",
               0,
               0
               );
        //qd.AddRow();
        return qd;
    }
Exemplo n.º 41
0
    void setQueries()
    {
        AqlQuery q = WAFContext.Session.CreateQuery();
        q.IncludeUnpublished = true;
        q.IncludeHiddenNodes = true;
        UniqueList<int> recent = WAFContext.Session.GetRecentlyEditedNodeIds();
        if (recent.Count > 0) {
            q.Where(Aql.In(AqlContent.NodeId, recent));
        } else {
            q.Where(AqlContent.NodeId == -1);
        }
        q.OrderBy(AqlContent.ChangeDate, true);
        lstRecent.Query = q;

        int userId = WAFContext.Session.UserId;
        AqlQuery qr = WAFContext.Session.CreateQuery();
        qr.From<ContentBase>();
        qr.Select<ContentBase>();
        qr.Select(AqlContent.NodeId);
        qr.IncludeHiddenNodes = false;
        qr.IncludeUnpublished = true;
        qr.Where(
            AqlContent.AuthorId == userId
            | AqlContent.CreatedById == userId
            | AqlContent.PublicationApprovedById == userId
            | AqlContent.ChangedById == userId
        );
        qr.OrderBy(AqlContent.ChangeDate, true);
        lstMyContent.Query = qr;

        QueryData qd = new QueryData();

        qd.AddField("FilterNam", DataValueType.ShortStringType);
        qd.AddField("Number", DataValueType.ShortStringType);
        qd.AddField("Name", DataValueType.ShortStringType);

        addRow(qd, "PublicationRequestToYou", RevisionStateRequest.AwaitingPublicationApproval, NodeStateRequest.None, true, "publication requests waiting for your approval. ", "publication request waiting for your approval. ");
        addRow(qd, "DeleteRequestToYou", RevisionStateRequest.AwaitingDeleteApproval, NodeStateRequest.None, true, "delete requests waiting for your approval. ", "delete request waiting for your approval. ");
        addRow(qd, "UnPublicationRequestToYou", RevisionStateRequest.AwaitingUnPublicationApproval, NodeStateRequest.None, true, "unpublication requests waiting for your approval. ", "unpublication request waiting for your approval. ");
        addRow(qd, "PublicationRequestFromYou", RevisionStateRequest.AwaitingPublicationApproval, NodeStateRequest.None, false, "publication requests from you. ", "publication request from you. ");
        addRow(qd, "DeleteRequestFromYou", RevisionStateRequest.AwaitingDeleteApproval, NodeStateRequest.None, false, "delete requests from you. ", "delete request from you. ");
        addRow(qd, "UnPublicationRequestFromYou", RevisionStateRequest.AwaitingUnPublicationApproval, NodeStateRequest.None, false, "unpublication requests from you. ", "unpublication request from you. ");

        addRow(qd, "NodeDeleteRequestToYou", RevisionStateRequest.None, NodeStateRequest.AwaitingDeleteApproval, true, "node delete requests waiting for your approval. ", "delete request waiting for your approval. ");
        addRow(qd, "NodeDeleteRequestFromYou", RevisionStateRequest.None, NodeStateRequest.AwaitingDeleteApproval, false, "node delete requests from you. ", "node delete request from you. ");
        addRow(qd, "NodeRestoreRequestToYou", RevisionStateRequest.None, NodeStateRequest.AwaitingRestoreApproval, true, "node restore requests waiting for your approval. ", "node restore request waiting for your approval. ");
        addRow(qd, "NodeRestoreRequestFromYou", RevisionStateRequest.None, NodeStateRequest.AwaitingRestoreApproval, false, "node restore requests from you. ", "node restore request from you. ");

        DataQuery q2 = new DataQuery(qd);
        lstTasks.IQuery = q2;
    }
Exemplo n.º 42
0
        public static ObservableCollection<Task> GetTasksInCollection(QueryData query, bool all = false)
        {
            SQLiteConnection connection = new SQLiteConnection(ConnectionString);
            if(!all)
            {
                query.Where += query.Where == null ? " (TASKS.IsDelete='False' or TASKS.IsDelete='0')" : " and (TASKS.IsDelete='False' or TASKS.IsDelete='0')";
            }
            string command = string.Concat(
                "select distinct * \r\nfrom TASKS ",
                string.IsNullOrEmpty(query.Join) ? "" : "\r\njoin " + query.Join,
                string.IsNullOrEmpty(query.Where) ? "" : "\r\nwhere " + query.Where);
            ObservableCollection<Task> tasks = new ObservableCollection<Task>();

            try
            {
                connection.Open();
                SQLiteCommand cmd = new SQLiteCommand(command, connection);
                if (query.Parameters != null)
                {
                    foreach (SQLiteParameter p in query.Parameters)
                    {
                        cmd.Parameters.Add(p);
                    }
                }
                SQLiteDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    string guid = reader.GetString(reader.GetOrdinal("GUID"));
                    object isNew = reader["IsNew"];
                    object isDelete = reader["IsDelete"];

                    Task task = new Task(false)
                    {
                        GUID = guid,
                        OrderDate = Convert.ToDateTime(reader.GetString(reader.GetOrdinal("OrderDate"))),
                        EndDate = Convert.ToDateTime(reader.GetString(reader.GetOrdinal("EndDate"))),
                        Performer = GetUserFromGUID(reader.GetString(reader.GetOrdinal("Performer"))),
                        Customer = GetUserFromGUID(reader.GetString(reader.GetOrdinal("Customer"))),
                        Topic = reader.GetString(reader.GetOrdinal("Topic")),
                        Description = reader.GetString(reader.GetOrdinal("Description")),
                        Priority = reader.GetByte(reader.GetOrdinal("Priority")),
                        Project = new Project(false) { GUID = reader.GetString(reader.GetOrdinal("Project")) },
                        TimePlan = reader.GetDouble(reader.GetOrdinal("TimePlan")),
                        TimeAdjustment = reader.GetDouble(reader.GetOrdinal("TimeAdjustment")),
                        TimeFact = reader.GetDouble(reader.GetOrdinal("TimeFact")),
                        Percents = reader.GetDouble(reader.GetOrdinal("Percents")),
                        IsImportant = GetImportantFlagForTask(guid),
                        IsNew = Convert.ToBoolean(isNew),
                        IsDelete = Convert.ToBoolean(isDelete)
                    };
                    tasks.Add(task);
                }
            }
            catch (Exception exc)
            {
                MessageWindows.Show("GetTasksInCollection:Exception", exc.Message);
                return tasks;
            }
            finally
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }
            }

            foreach (Task task in tasks)
            {
                task.Project = GetParentProjectFromGUID(task.Project.GUID, all);
            }

            return tasks;
        }
Exemplo n.º 43
0
    void updateList()
    {
        QueryData qd = new QueryData();
        qd.AddField("id", DataValueType.IntegerType);
        qd.AddField("icon", DataValueType.ShortStringType);
        qd.AddField("name", DataValueType.ShortStringType);
        qd.AddField("status", DataValueType.ShortStringType);
        qd.AddField("tooltip", DataValueType.LongStringType);
        qd.AddField("rec_action", DataValueType.ShortStringType);
        qd.AddField("sel_action", DataValueType.ShortStringType);

        int id = 0;
        foreach (var c in _comparisons) {
            string icon = WAFContext.UI.Skin.GetUrlIconFolder();
            switch (c.DefType) {
                case DefType.ContentClasses: icon += "ContentClass.png"; break;
                //case DefType.Property: icon += "Property.png"; break;
                case DefType.Relations: icon += "Relation.png"; break;
                case DefType.PropertyGroups: icon += "Panel.png"; break;
                case DefType.PropertyClasses: icon += "Property.png"; break;
                case DefType.Cultures: icon = WAFContext.GetUrlFromHostToCultureFlag(c.LCID); break;
                case DefType.Enumerations: icon += "Enum.png"; break;
                default: icon += ""; break;
            }
            icon = "<img src='" + icon + "'/>";
            string rec_action = getAction(c.RecommendedAction, c.Status, "<font color=gray>No recommendation</font>");
            string sel_action = getAction(c.SelectedAction, c.Status, "<font color=red>Unresolved</font>");
            qd.AddRow(id++, icon, c.Name, getStatus(c.Status), (c.Difference + "").Replace(Environment.NewLine, "<br/>").Replace(" ", "&nbsp;"), rec_action, sel_action);
        }
        lstComparisons.IQuery = new DataQuery(qd);
    }
Exemplo n.º 44
0
 void setQueryScheduledTask()
 {
     QueryData qd = new QueryData();
     qd.AddField("Value", DataValueType.ShortStringType);
     qd.AddField("Text", DataValueType.ShortStringType);
     qd.AddField("Enabled", DataValueType.ShortStringType);
     qd.AddField("LastRun", DataValueType.ShortStringType);
     qd.AddField("Description", DataValueType.ShortStringType);
     foreach (ScheduledTask task in WAFRuntime.Engine.SystemSession.Query<ScheduledTask>().OrderBy(AqlScheduledTask.Name).Execute()) {
         string icon = WAFContext.GetHtmlClassIcon(task.ClassId, "margin:0px 3px -4px 3px; "); ;
         string name = task.Name;
         string desc;
         switch (task.IntervalUnit) {
             case TaskShedulerIntervalUnit.Continuous:
                 desc = "Every " + Utils.GetTimespanString(new TimeSpan(0, 0, task.StartAt));
                 break;
             case TaskShedulerIntervalUnit.Minute:
                 desc = "" + Utils.GetTimespanString(new TimeSpan(0, 0, task.StartAt)) + " past the minute";
                 break;
             case TaskShedulerIntervalUnit.Hour:
                 desc = "" + Utils.GetTimespanString(new TimeSpan(0, 0, task.StartAt)) + " past the hour";
                 break;
             case TaskShedulerIntervalUnit.Day:
                 desc = "" + Utils.GetTimespanString(new TimeSpan(0, 0, task.StartAt)) + " past midnight";
                 break;
             case TaskShedulerIntervalUnit.Week:
                 desc = "" + Utils.GetTimespanString(new TimeSpan(0, 0, task.StartAt)) + " past every week start";
                 break;
             case TaskShedulerIntervalUnit.Month:
                 desc = "" + Utils.GetTimespanString(new TimeSpan(0, 0, task.StartAt)) + " past every month start";
                 break;
             case TaskShedulerIntervalUnit.Quarter:
                 desc = "" + Utils.GetTimespanString(new TimeSpan(0, 0, task.StartAt)) + " past every quarter";
                 break;
             case TaskShedulerIntervalUnit.Year:
                 desc = "" + Utils.GetTimespanString(new TimeSpan(0, 0, task.StartAt)) + " past every year start";
                 break;
             default:
                 desc = "";
                 break;
         }
         qd.AddRow(
             task.NodeId.ToString(),
             icon + name,
             task.Enabled ? "Yes" : "No",
             task.InProgress ? "In progress" : (task.LastStart.ToShortDateString() + " " + task.LastStart.ToShortTimeString()),
             desc
             );
     }
     lstTasks.BorderWidth = 0;
     lstTasks.IQuery = new DataQuery(qd);
 }
Exemplo n.º 45
0
    void updateList()
    {
        QueryData qd = new QueryData();
        qd.AddField("guid", DataValueType.ShortStringType);
        qd.AddField("icon", DataValueType.ShortStringType);
        qd.AddField("name", DataValueType.ShortStringType);
        qd.AddField("status", DataValueType.ShortStringType);
        qd.AddField("tooltip", DataValueType.LongStringType);
        qd.AddField("rec_action", DataValueType.ShortStringType);
        qd.AddField("sel_action", DataValueType.ShortStringType);

        foreach (var c in _difference) {
            var action = _actions[c.Key];
            var orgAction = _orgActions[c.Key];
            bool show = true;
            if (!_listIdentical) {
                if (c.Value.Status == ComparisonStatus.Identical || c.Value.Status == ComparisonStatus.DeletedLocallyAndExternally) {
                    show = false;
                }
            }
            if (action != SynchronizationAction.Nothing || orgAction != SynchronizationAction.Nothing) { // always show if any action
                show = true;
            }
            // c.Value.Status != ComparisonStatus.Identical || _listIdentical || (action != SynchronizationAction.Nothing || orgAction != SynchronizationAction.Nothing)
            if (show) {
                int classId;
                string icon;
                if (WAFRuntime.Definitions.TryGetClassId(c.Value.ClassName, out classId)) {
                    icon = WAFContext.GetUrlFromHostToClassIcon(classId);
                } else {
                    icon = WAFContext.GetUrlFromHostToClassIcon(0);
                }
                icon = "<img src='" + icon + "'/>";
                string guid = c.Key.ToString();
                string name = c.Value.Name;
                string status = getStatus(c.Value.Status);
                string tooltip = "Global GUID: " + c.Key + "</br>Local Node ID: " + c.Value.LocalNodeId + "</br>External Node ID: " + c.Value.ExternalNodeId;
                string rec_action = getAction(orgAction);
                string sel_action = "<b>" + getAction(action) + "</b>";

                qd.AddRow(guid, icon, name, status, tooltip, rec_action, sel_action);
            }
        }
        lstComparisons.IQuery = new DataQuery(qd);
    }
Exemplo n.º 46
0
        private void InitData(OrderInfo order)
        {
            OrderEntity oe = new OrderEntity();
            

            List<ITextValueItem> queryList = new List<ITextValueItem>();

            QueryData qd = new QueryData();
            qd.Text= "待我审核的单据";
            qd.Value = "AuditedOrder";
            qd.QueryExpression = QueryExpressionHelper.Equal("AuditedBy", DataCore.CurrentUser.Value.ToString());
            qd.QueryExpression.QueryType = order.Type;
            queryList.Add(qd);
            
            CommonFunction.FillComboBox(this.cbbQueryList, queryList);

            cbbQueryList.SelectedIndex = 0;

            GetOrders();
        }
Exemplo n.º 47
0
        // Основной метод
        public Response GetResponse(QueryData queryData)
        {
            Response response = new Response
            {
                StartDate = DateTime.Now,
                SourceId = SourceId,
                Status = RequestStatus.Processed
            };

            // Convert <int,string> to POST parameters <string,string>
            Dictionary<string, string> post = new Dictionary<string, string>();

            string name = queryData.QueryValues[101],
                   region = queryData.QueryValues[106],
                   ogrn = queryData.QueryValues[110],
                   date = queryData.QueryValues[116],
                   inn = queryData.QueryValues[113],
                   address = queryData.QueryValues[310];

            // Оставляем только ИНН или ОГРН, если они даны
            if (!(isEmpty(ogrn) || isEmpty(inn))) { region = ""; date = ""; address = ""; name = ""; }

            post.Add("num", isEmpty(ogrn) ? inn : ogrn);
            post.Add("name", toRequest(name));
            post.Add("region", toRequest(region));
            post.Add("address", toRequest(address));
            post.Add("date", toRequest(date));
            post.Add("action", "%C8%F1%EA%E0%F2%FC");

            HtmlDownloader downloader = new HtmlDownloader();
            string html = downloader.GetPage("http://egrul.nalog.ru/fns/index.php"); // Выполняем GET метод, чтобы получить Cookies
            html = downloader.GetPage("http://egrul.nalog.ru/fns/g.php", post); // Выполняем POST метод, чтобы получиьт результаты поиска

            HtmlDocument htmldocObject = new HtmlDocument();
            htmldocObject.LoadHtml(html);

            // Проверяем ответ на запрос
            HtmlNode found = htmldocObject.DocumentNode.SelectSingleNode("//div[@class='valaam']/p[not(*)]");
            if (found != null)
            {
                Regex regResults = new Regex(@"(?<countResults>\d+)");
                Match m = regResults.Match(found.InnerText);
                if (!m.Success)
                {
                    int count = int.Parse(m.Groups["countResults"].Value);
                    if (count != 0)
                    {
                        // Результаты поиска организации неоднозначны
                        response.Entities = new List<Entity>();
                        foreach (var page in htmldocObject.DocumentNode.SelectNodes("//div[@class='container']/div/div[10]/table/tr/td/a"))
                        {
                            Regex regex = new Regex(@"\d");
                            if (regex.Match(page.InnerText).Success)
                            {
                                string link = "http://egrul.nalog.ru" + page.GetAttributeValue("href", "");
                                HtmlDocument doc = new HtmlDocument();
                                doc.LoadHtml(downloader.GetPage(link));
                                HtmlNode mainAttributes = doc.DocumentNode.SelectSingleNode("//div[@class='valaam']/table/tbody/tr[1]");
                                var ambiguousEntities = getAmbiguousEntities(mainAttributes, doc);
                                foreach (var entity in ambiguousEntities) response.Entities.Add(entity);
                            }
                        }
                        response.Status = RequestStatus.Ambiguous;
                    }
                    else
                    {
                        // Ничего не найдено
                        response.Entities = new List<Entity>();
                        response.Status = RequestStatus.NotFound;
                    }
                }
            }
            else
            {
                // Найдена одна организация
                Entity singleEntity = new Entity() { Title = "Общая информация", TypeId = 1 };
                singleEntity.Properties = getMainProperties(htmldocObject);
                singleEntity.SubEntities = getSubEntities(htmldocObject);
                response.Entities.Add(singleEntity);
                response.Status = RequestStatus.Completed;
            }
            response.FinishDate = DateTime.Now;
            return response;
        }
        private void RegisterContentViews()
        {
            var templateKey = SampleUtilities.GetControlTemplateKey(typeof(Telerik.Sitefinity.Modules.News.Web.UI.MasterListView), SampleConstants.EducationNewsSummaryTemplateName);
            SampleUtilities.RegisterNewsFrontendView(SampleConstants.NewsFrontendContentViewControlName,
                templateKey,
                typeof(Telerik.Sitefinity.Modules.News.Web.UI.MasterListView),
                SampleConstants.EducationNewsSummaryContentViewName,
                6,
                false,
                new Guid(SampleConstants.NewsPageId));

            templateKey = SampleUtilities.GetControlTemplateKey(typeof(Telerik.Sitefinity.Modules.News.Web.UI.DetailsSimpleView), SampleConstants.EducationNewsFullItemTemplateName);

            SampleUtilities.RegisterNewsFrontendDetailsView("NewsFrontend", templateKey, typeof(Telerik.Sitefinity.Modules.News.Web.UI.DetailsSimpleView), SampleConstants.EducationNewsItemDetailView, true);

            templateKey = SampleUtilities.GetControlTemplateKey(typeof(Telerik.Sitefinity.Modules.Libraries.Web.UI.Videos.MasterThumbnailLightBoxView), SampleConstants.ThumbnailsOverlayLightBoxTemplateName);
            SampleUtilities.RegisterVideosFrontendView(SampleConstants.VideosFrontendContentViewControlName,
                templateKey,
                typeof(Telerik.Sitefinity.Modules.Libraries.Web.UI.Videos.MasterThumbnailLightBoxView),
                SampleConstants.VideosEducationFrontendLightBoxViewName,
                50,
                true,
                new Guid(SampleConstants.OnlineCoursesLibraryId));

            templateKey = SampleUtilities.GetControlTemplateKey(typeof(Telerik.Sitefinity.Modules.Libraries.Web.UI.Images.MasterThumbnailLightBoxView), "List of thumbnails and overlay dialog (lightbox)");

            QueryItem q = new QueryItem()
            {
                IsGroup = true,
                Ordinal = 0,
                Join = "AND",
                ItemPath = "_0",
                Value = null,
                Condition = null,
                Name = "Tags"
            };

            QueryItem q1 = new QueryItem()
            {
                IsGroup = false,
                Ordinal = 0,
                Join = "OR",
                ItemPath = "_0_0",
                Condition = new Condition()
                            {
                                FieldName = "Tags",
                                FieldType = "System.Guid",
                                Operator = "Contains",
                            },
                Name = "homepage",
                Value = "913E28AA-0DE2-470d-9C3F-000000000005"
            };

            List<QueryItem> queryItems = new List<QueryItem>();
            queryItems.Add(q);
            queryItems.Add(q1);

            QueryData additionalFilter1 = new QueryData()
            {
                QueryItems = queryItems.ToArray(),
                TypeProperties = new string[0],
                Title = null,
            };

            SampleUtilities.RegisterImagesFrontendView("ImagesFrontend", templateKey, typeof(Telerik.Sitefinity.Modules.Libraries.Web.UI.Images.MasterThumbnailLightBoxView), "ImagesFrontendEducationThumbnailsListLightBox", additionalFilter1);

            templateKey = SampleUtilities.GetControlTemplateKey(typeof(Telerik.Sitefinity.Modules.Events.Web.UI.Public.DetailsView), SampleConstants.EducationEventsSingleItemTemplateName);
            SampleUtilities.RegisterEventsFrontendDetailsView("EventsFrontend", templateKey, typeof(Telerik.Sitefinity.Modules.Events.Web.UI.Public.DetailsView), SampleConstants.EducationEventItemDetailView);
        }
Exemplo n.º 49
0
        /// <summary>
        /// Save a partial path
        /// </summary>
        /// <param name="existing">Existing path</param>
        /// <param name="existingSize">Existing path's length</param>
        /// <param name="path">New path</param>
        /// <param name="pathCount">New path's length</param>
        /// <param name="maxPath">Maximum path length allowed</param>
        /// <returns>True if path saved, false if not</returns>
        public bool FinalizedSlicedPathPartial(PolyId[] existing, int existingSize, PolyId[] path, ref int pathCount, int maxPath)
        {
            pathCount = 0;

            if (existingSize == 0)
            {
                return false;
            }

            if (query.Status == false)
            {
                query = new QueryData();
                return false;
            }

            int n = 0;

            if (query.Start.Polygon == query.End.Polygon)
            {
                //special case: the search starts and ends at the same poly
                path[n++] = query.Start.Polygon;
            }
            else
            {
                //find furthest existing node that was visited
                Node prev = null;
                Node node = null;
                for (int i = existingSize - 1; i >= 0; i--)
                {
                    node = nodePool.FindNode(existing[i]);
                    if (node != null)
                        break;
                }

                if (node == null)
                {
                    node = query.LastBestNode;
                }

                //reverse the path
                do
                {
                    Node next = nodePool.GetNodeAtIdx(node.ParentIdx);
                    node.ParentIdx = nodePool.GetNodeIdx(prev);
                    prev = node;
                    node = next;
                }
                while (node != null);

                //store path
                node = prev;
                do
                {
                    path[n++] = node.Id;
                    if (n >= maxPath)
                    {
                        break;
                    }

                    node = nodePool.GetNodeAtIdx(node.ParentIdx);
                }
                while (node != null);
            }

            //reset query
            query = new QueryData();

            //remember to update the path length
            pathCount = n;

            return true;
        }
Exemplo n.º 50
0
        static ISqlExpression GetColumn(QueryData data, SqlField field)
        {
            foreach (var query in data.Queries)
            {
                var q = query.Query;

                foreach (var table in q.From.Tables)
                {
                    var t = FindField(field, table);

                    if (t != null)
                    {
                        var n   = q.Select.Columns.Count;
                        var idx = q.Select.Add(field);

                        if (n != q.Select.Columns.Count)
                            if (!q.GroupBy.IsEmpty || q.Select.Columns.Any(c => IsAggregationFunction(c.Expression)))
                                q.GroupBy.Items.Add(field);

                        return q.Select.Columns[idx];
                    }
                }
            }

            return null;
        }
Exemplo n.º 51
0
        /// <summary>
        /// Save the sliced path 
        /// </summary>
        /// <param name="path">The path in terms of polygon references</param>
        /// <param name="pathCount">The path length</param>
        /// <param name="maxPath">The maximum path length allowed</param>
        /// <returns>True if the path is saved, false if not</returns>
        public bool FinalizeSlicedFindPath(PolyId[] path, ref int pathCount, int maxPath)
        {
            pathCount = 0;

            if (query.Status == false)
            {
                query = new QueryData();
                return false;
            }

            int n = 0;

            if (query.Start.Polygon == query.End.Polygon)
            {
                //special case: the search starts and ends at the same poly
                path[n++] = query.Start.Polygon;
            }
            else
            {
                //reverse the path
                Node prev = null;
                Node node = query.LastBestNode;
                do
                {
                    Node next = nodePool.GetNodeAtIdx(node.ParentIdx);
                    node.ParentIdx = nodePool.GetNodeIdx(prev);
                    prev = node;
                    node = next;
                }
                while (node != null);

                //store path
                node = prev;
                do
                {
                    path[n++] = node.Id;
                    if (n >= maxPath)
                        break;

                    node = nodePool.GetNodeAtIdx(node.ParentIdx);
                }
                while (node != null);
            }

            //reset query
            query = new QueryData();

            //remember to update the path length
            pathCount = n;

            return true;
        }
Exemplo n.º 52
0
        static void ResolveFields(QueryData data)
        {
            if (data.Queries.Count == 0)
                return;

            var dic = new Dictionary<ISqlExpression,ISqlExpression>();

            foreach (SqlField field in data.Fields)
            {
                if (dic.ContainsKey(field))
                    continue;

                var found = false;

                foreach (var table in data.Query.From.Tables)
                {
                    found = FindField(field, table) != null;

                    if (found)
                        break;
                }

                if (!found)
                {
                    var expr = GetColumn(data, field);

                    if (expr != null)
                        dic.Add(field, expr);
                }
            }

            if (dic.Count > 0)
                new QueryVisitor().VisitParentFirst(data.Query, e =>
                {
                    ISqlExpression ex;

                    switch (e.ElementType)
                    {
                        case QueryElementType.SqlQuery :
                            return e == data.Query;

                        case QueryElementType.SqlFunction :
                            {
                                var parms = ((SqlFunction)e).Parameters;

                                for (var i = 0; i < parms.Length; i++)
                                    if (dic.TryGetValue(parms[i], out ex))
                                        parms[i] = ex;

                                break;
                            }

                        case QueryElementType.SqlExpression :
                            {
                                var parms = ((SqlExpression)e).Parameters;

                                for (var i = 0; i < parms.Length; i++)
                                    if (dic.TryGetValue(parms[i], out ex))
                                        parms[i] = ex;

                                break;
                            }

                        case QueryElementType.SqlBinaryExpression :
                            {
                                var expr = (SqlBinaryExpression)e;
                                if (dic.TryGetValue(expr.Expr1, out ex)) expr.Expr1 = ex;
                                if (dic.TryGetValue(expr.Expr2, out ex)) expr.Expr2 = ex;
                                break;
                            }

                        case QueryElementType.ExprPredicate       :
                        case QueryElementType.NotExprPredicate    :
                        case QueryElementType.IsNullPredicate     :
                        case QueryElementType.InSubQueryPredicate :
                            {
                                var expr = (SelectQuery.Predicate.Expr)e;
                                if (dic.TryGetValue(expr.Expr1, out ex)) expr.Expr1 = ex;
                                break;
                            }

                        case QueryElementType.ExprExprPredicate :
                            {
                                var expr = (SelectQuery.Predicate.ExprExpr)e;
                                if (dic.TryGetValue(expr.Expr1, out ex)) expr.Expr1 = ex;
                                if (dic.TryGetValue(expr.Expr2, out ex)) expr.Expr2 = ex;
                                break;
                            }

                        case QueryElementType.LikePredicate :
                            {
                                var expr = (SelectQuery.Predicate.Like)e;
                                if (dic.TryGetValue(expr.Expr1,  out ex)) expr.Expr1  = ex;
                                if (dic.TryGetValue(expr.Expr2,  out ex)) expr.Expr2  = ex;
                                if (dic.TryGetValue(expr.Escape, out ex)) expr.Escape = ex;
                                break;
                            }

                        case QueryElementType.BetweenPredicate :
                            {
                                var expr = (SelectQuery.Predicate.Between)e;
                                if (dic.TryGetValue(expr.Expr1, out ex)) expr.Expr1 = ex;
                                if (dic.TryGetValue(expr.Expr2, out ex)) expr.Expr2 = ex;
                                if (dic.TryGetValue(expr.Expr3, out ex)) expr.Expr3 = ex;
                                break;
                            }

                        case QueryElementType.InListPredicate :
                            {
                                var expr = (SelectQuery.Predicate.InList)e;

                                if (dic.TryGetValue(expr.Expr1, out ex)) expr.Expr1 = ex;

                                for (var i = 0; i < expr.Values.Count; i++)
                                    if (dic.TryGetValue(expr.Values[i], out ex))
                                        expr.Values[i] = ex;

                                break;
                            }

                        case QueryElementType.Column :
                            {
                                var expr = (SelectQuery.Column)e;

                                if (expr.Parent != data.Query)
                                    return false;

                                if (dic.TryGetValue(expr.Expression, out ex)) expr.Expression = ex;

                                break;
                            }

                        case QueryElementType.SetExpression :
                            {
                                var expr = (SelectQuery.SetExpression)e;
                                if (dic.TryGetValue(expr.Expression, out ex)) expr.Expression = ex;
                                break;
                            }

                        case QueryElementType.GroupByClause :
                            {
                                var expr = (SelectQuery.GroupByClause)e;

                                for (var i = 0; i < expr.Items.Count; i++)
                                    if (dic.TryGetValue(expr.Items[i], out ex))
                                        expr.Items[i] = ex;

                                break;
                            }

                        case QueryElementType.OrderByItem :
                            {
                                var expr = (SelectQuery.OrderByItem)e;
                                if (dic.TryGetValue(expr.Expression, out ex)) expr.Expression = ex;
                                break;
                            }
                    }

                    return true;
                });

            foreach (var query in data.Queries)
                if (query.Queries.Count > 0)
                    ResolveFields(query);
        }
Exemplo n.º 53
0
        /// <summary>
        /// Deserialize the message
        /// </summary>
        /// <param name="map">An <see cref="OSDMap"/> containing the data</param>
        public void Deserialize(OSDMap map)
        {
            OSDArray agentDataArray = (OSDArray)map["AgentData"];

            OSDMap agentDataMap = (OSDMap)agentDataArray[0];
            AgentID = agentDataMap["AgentID"].AsUUID();
            QueryID = agentDataMap["QueryID"].AsUUID();

            OSDArray dataBlocksArray = (OSDArray)map["QueryData"];
            QueryDataBlocks = new QueryData[dataBlocksArray.Count];
            for (int i = 0; i < dataBlocksArray.Count; i++)
            {
                OSDMap dataMap = (OSDMap)dataBlocksArray[i];
                QueryData data = new QueryData();
                data.ActualArea = dataMap["ActualArea"].AsInteger();
                data.BillableArea = dataMap["BillableArea"].AsInteger();
                data.Description = dataMap["Desc"].AsString();
                data.Dwell = (float)dataMap["Dwell"].AsReal();
                data.Flags = dataMap["Flags"].AsInteger();
                data.GlobalX = (float)dataMap["GlobalX"].AsReal();
                data.GlobalY = (float)dataMap["GlobalY"].AsReal();
                data.GlobalZ = (float)dataMap["GlobalZ"].AsReal();
                data.Name = dataMap["Name"].AsString();
                data.OwnerID = dataMap["OwnerID"].AsUUID();
                data.Price = dataMap["Price"].AsInteger();
                data.SimName = dataMap["SimName"].AsString();
                data.SnapShotID = dataMap["SnapshotID"].AsUUID();
                data.ProductSku = dataMap["ProductSKU"].AsString();
                QueryDataBlocks[i] = data;
            }

            OSDArray transactionArray = (OSDArray)map["TransactionData"];
            OSDMap transactionDataMap = (OSDMap)transactionArray[0];
            TransactionID = transactionDataMap["TransactionID"].AsUUID();
        }
Exemplo n.º 54
0
 void setQuery()
 {
     AqlExpressionBuilder expStatus = new AqlExpressionBuilder();
     expStatus.Or(AqlUrlStatus.NodeId == -1);
     foreach (ListItem i in chkLinkStatus.Items) {
         if (i.Selected) expStatus.Or(AqlUrlStatus.Status == int.Parse(i.Value));
     }
     AqlExpressionBuilder expType = new AqlExpressionBuilder();
     expType.Or(AqlUrlStatus.NodeId == -1);
     foreach (ListItem i in chkLinkType.Items) {
         if (i.Selected) expType.Or(AqlUrlStatus.UrlType == int.Parse(i.Value));
     }
     AqlExpressionBoolean exp = null;
     if (!expStatus.IsEmpty) exp = expStatus;
     if (!expType.IsEmpty) {
         if (expStatus.IsEmpty) {
             exp = expType;
         } else {
             exp = new AqlExpressionAnd(expType, expStatus);
         }
     }
     if (!WAFContext.Session.Access.IsAdmin()) exp = exp & AqlUrlStatus.SiteId == WAFContext.Session.SiteId;
     var session = WAFContext.Session;
     IEnumerable<UrlStatus> urls = WAFContext.Engine.SystemSession.GetContents<UrlStatus>(exp);
     _links = WAFContext.Session.GetLinks(urls);
     _links = (
         from l in _links orderby l.Url, l.LinkType, l.Content.Name, l.PropertyName
         where session.Access.IsMember(l.Content.EditAccessGroupId)
         select l).ToList();
     QueryData qd = new QueryData();
     qd.AddField("Index", DataValueType.IntegerType);
     qd.AddField("Key", DataValueType.LongStringType);
     qd.AddField("Tooltip", DataValueType.LongStringType);
     for (int i = 0; i < _links.Count; i++) qd.AddRow(i, _links[i].Content.Key.ToString() + "_" + i + "_" + _links[i].Url.Replace("_", "###").Replace(Environment.NewLine, ""), getToolTip(_links[i]));
     lst.IQuery = new DataQuery(qd);
 }
Exemplo n.º 55
0
 void addRow(QueryData qd, string filter, RevisionStateRequest request, NodeStateRequest nodeRequest, bool toNotFrom, string textPlural, string textSingle)
 {
     int n = getRevisionCount(request, nodeRequest, toNotFrom);
     if (n > 0) {
         qd.AddRow(filter, "<strong>" + n + "</strong>", "<span style=\" font-weight:bold;\">" + (n == 1 ? textSingle : textPlural) + "</span>");
     } else {
         qd.AddRow(filter, "<span style=\"color:gray;\">0</span>", "<span style=\"color:gray;\">" + textPlural + "</span>");
     }
 }
Exemplo n.º 56
0
        /// <summary>
        /// Initialize a sliced path, which is used mostly for crowd pathfinding.
        /// </summary>
        /// <param name="startPoint">The start point.</param>
        /// <param name="endPoint">The end point.</param>
        /// <param name="filter">A filter for the navigation mesh.</param>
        /// <param name="options">Options for how the path should be found.</param>
        /// <returns>True if path initialized, false otherwise</returns>
        public bool InitSlicedFindPath(ref NavPoint startPoint, ref NavPoint endPoint, NavQueryFilter filter, FindPathOptions options)
        {
            //validate input
            if (startPoint.Polygon == NavPolyId.Null || endPoint.Polygon == NavPolyId.Null)
                return false;

            if (!nav.IsValidPolyRef(startPoint.Polygon) || !nav.IsValidPolyRef(endPoint.Polygon))
                return false;

            if (startPoint.Polygon == endPoint.Polygon)
            {
                query.Status = true;
                return true;
            }

            //init path state
            query = new QueryData();
            query.Status = false;
            query.Start = startPoint;
            query.End = endPoint;

            nodePool.Clear();
            openList.Clear();

            NavNode startNode = nodePool.GetNode(startPoint.Polygon);
            startNode.Position = startPoint.Position;
            startNode.ParentIndex = 0;
            startNode.PolyCost = 0;
            startNode.TotalCost = (endPoint.Position - startPoint.Position).Length() * HeuristicScale;
            startNode.Id = startPoint.Polygon;
            startNode.Flags = NodeFlags.Open;
            openList.Push(startNode);

            query.Status = true;
            query.LastBestNode = startNode;
            query.LastBestNodeCost = startNode.TotalCost;

            return query.Status;
        }
Exemplo n.º 57
0
    void setQuerySessionList()
    {
        QueryData qd = new QueryData();
        DateTime now = DateTime.Now;
        qd.AddField("Value", DataValueType.ShortStringType);
        qd.AddField("Text", DataValueType.LongStringType);
        qd.AddField("LastUsage", DataValueType.ShortStringType);
        qd.AddField("LastRequest", DataValueType.ShortStringType);
        qd.AddField("Origin", DataValueType.LongStringType);
        qd.AddField("Age", DataValueType.ShortStringType);
        qd.AddField("Timeout", DataValueType.ShortStringType);
        qd.AddField("Tooltip", DataValueType.LongStringType);
        qd.AddField("Type", DataValueType.LongStringType);
        var ss = from s in WAFRuntime.Engine.GetAllSessions() orderby s.LastUsage descending select s;
        List<WAFSession> sessions;
        if (ss.Count() > 50) {
            pnlOnline.Text = "Sessions. First 50 of " + ss.Count();
            sessions = ss.Take(50).ToList();
        } else {
            pnlOnline.Text = "Sessions";
            sessions = ss.ToList();
        }
        foreach (WAFSession session in sessions) {
            string icon = "";
            switch (session.Access.UserType) {
                case SystemUserType.Anonymous: icon = WAFContext.GetHtmlClassIcon(SystemUser.ContentClassId, "margin:0px 3px -4px 3px; "); break;
                case SystemUserType.Administrator: icon = WAFContext.GetHtmlClassIcon(SystemUser.ContentClassId, "margin:0px 3px -4px 3px; "); break;
                case SystemUserType.System: icon = WAFContext.GetHtmlClassIcon(SystemUser.ContentClassId, "margin:0px 3px -4px 3px; "); break;
                case SystemUserType.User: icon = WAFContext.GetHtmlClassIcon(session.GetUser().ClassId, "margin:0px 3px -4px 3px; "); break;
                default: break;
            }
            string name = "";
            switch (session.Access.UserType) {
                case SystemUserType.Anonymous: name = "[Anonymous]"; break;
                case SystemUserType.Administrator: name = session.GetUser().UserName; break;
                case SystemUserType.System:
                    if (session.SessionId == WAFRuntime.SystemSession.SessionId) {
                        name = "[System]"; break;
                    } else {
                        name = "[Master]"; break;
                    }
                case SystemUserType.User:
                    SystemUser su = session.GetUser();
                    name = su.UserName; break;
                default: break;
            }
            if (WAFContext.Session.SessionId == session.SessionId) name = name + "<span style=\"color:#FF8833;\"> [Me!]</span>";
            string tooltip =
                (session.UserId < -10 || session.UserId > 0 ? "User ID: " + session.UserId : "[" + session.Access.UserType + "]")
                + "<br /><br />Created: " + session.Created
                + ((session.InitUrl != null) ? ("<br /><br />First request: " + session.InitUrl.Split('?')[0]) : "")
                + ((session.InitUrl != null) ? ("<br /><br />Referrer url: " + (session.InitReferrer != null ? session.InitReferrer.Split('?')[0] : "")) : "")
                + ((session.LastPageviewUrl != null) ? ("<br /><br />Last request: " + session.LastPageviewUrl.Split('?')[0]) : "")
                + ((session.Access.IsStored) ? ("<br /><br />Name: " + session.GetUser().Name) : "");
            qd.AddRow(
                session.SessionId.ToString(),
                icon + name,
                Utils.GetTimespanStringShort(now.Subtract(session.LastUsage)),
                (session.LastPageview != Utils.DateTimeNull && session.LastPageview != DateTime.MinValue ? Utils.GetTimespanStringShort(now.Subtract(session.LastPageview)) : ""),
                Utils.GetFriendlyName(session.SessionBirthContext.ToString()),
                Utils.GetTimespanStringShort(now.Subtract(session.Created)),
                Utils.GetTimespanStringShort(WAFRuntime.Engine.SessionTimeout - now.Subtract(session.LastUsage)),
                tooltip,
                Utils.GetFriendlyName(session.Access.UserType.ToString())
                );
        }

        lstOnline.BorderWidth = 0;
        lstOnline.IQuery = new DataQuery(qd);
    }
Exemplo n.º 58
0
    void initErrors()
    {
        StringBuilder sb = new StringBuilder();
        QueryData qd = new QueryData();
        qd.AddField("id", DataValueType.ShortStringType);
        qd.AddField("icon", DataValueType.ShortStringType);
        qd.AddField("error", DataValueType.ShortStringType);
        qd.AddField("path", DataValueType.ShortStringType);
        qd.AddField("line", DataValueType.ShortStringType);
        qd.AddField("tooltip", DataValueType.LongStringType);
        int n = 0;
        foreach (var err in _errors) {
            string id = n.ToString();
            string icon = "<img src='Images/" + (err.IsWarning ? "Warning" : "Error") + ".png'/>";
            string error = replacePaths(err.ErrorText);
            string path = "";
            try {
                if (!String.IsNullOrEmpty(err.FileName)) path = getShortFileName(err.FileName);
            } catch { }
            string tooltip = error.Replace("\"", "'") + "<br/><br/>" + path + "<br/><br/>Ln " + err.Line + " Col " + err.Column;
            if (error.Length > 60) error = error.Substring(0, 60) + "...";
            if (path.Length > 35) path = "..." + path.Substring(path.Length - 35);
            qd.AddRow(id, icon, error, path, err.Line.ToString(), tooltip);
            n++;

        }
        lstErrors.IQuery = new DataQuery(qd);
        lstErrors.DblClick += new EventHandler(lstErrors_DblClick);
    }