Esempio n. 1
0
 /// <summary>
 /// Convert FilterRule to our custom FilterRuleBuilder which will be displayed in form controls  
 /// </summary>
 /// <param name="param">Parameter to which the FilterRule is applied.</param>
 /// <param name="rule">FilterRule to be converted.</param>
 /// <returns>Custom FilterRuleBuilder data converted from FilterRule</returns>
 public static FilterRuleBuilder CreateFilterRuleBuilder(BuiltInParameter param, FilterRule rule)
 {
     // Maybe FilterRule is inverse rule, we need to find its inner rule(FilterValueRule)
     // Note that the rule may be inversed more than once.
     bool inverted = false;
     FilterRule innerRule = ReflectToInnerRule(rule, out inverted);
     if (innerRule is FilterStringRule)
     {
         FilterStringRule strRule = innerRule as FilterStringRule;
         FilterStringRuleEvaluator evaluator = strRule.GetEvaluator();
         return new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), strRule.RuleString, strRule.CaseSensitive);
     }
     else if (innerRule is FilterDoubleRule)
     {
         FilterDoubleRule dbRule = innerRule as FilterDoubleRule;
         FilterNumericRuleEvaluator evaluator = dbRule.GetEvaluator();
         return new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), dbRule.RuleValue, dbRule.Epsilon);
     }
     else if (innerRule is FilterIntegerRule)
     {
         FilterIntegerRule intRule = innerRule as FilterIntegerRule;
         FilterNumericRuleEvaluator evaluator = intRule.GetEvaluator();
         return new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), intRule.RuleValue);
     }
     else if (innerRule is FilterElementIdRule)
     {
         FilterElementIdRule idRule = innerRule as FilterElementIdRule;
         FilterNumericRuleEvaluator evaluator = idRule.GetEvaluator();
         return new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), idRule.RuleValue);
     }
     //
     // for other rule, not supported yet
     throw new System.NotImplementedException("The filter rule is not recognizable and supported yet!");
 }
Esempio n. 2
0
        public void Constructor_WhenInvoked_InitializesProperties()
        {
            var filter = new AnyFilter<object>();
            var filterRule = new FilterRule<object>(FilterRuleType.Exclusion, filter);

            Assert.AreEqual(FilterRuleType.Exclusion, filterRule.RuleType);
            Assert.AreEqual(filter, filterRule.Filter);
        }
Esempio n. 3
0
        public void Evaluate_Always_ConsidersRulesInOrder(FilterSetResult expectedResult, FilterRuleType[] ruleTypes, bool[] states)
        {
            FilterRule<object>[] filterRules = new FilterRule<object>[ruleTypes.Length];
            for (int i = 0; i < ruleTypes.Length; i++)
                filterRules[i] = new FilterRule<object>(ruleTypes[i],
                    states[i] ? (Filter<object>)new AnyFilter<object>() : new NoneFilter<object>());

            FilterSet<object> filterSet = new FilterSet<object>(filterRules);
            Assert.AreEqual(expectedResult, filterSet.Evaluate(null));
        }
Esempio n. 4
0
        public void GetExpressionTest()
        {
            IQueryable<TestEntity> source = Entities.AsQueryable();

            //空条件
            Expression<Func<TestEntity, bool>> predicate = FilterHelper.GetExpression<TestEntity>();
            Assert.True(source.Where(predicate).SequenceEqual(source));

            //单条件,属性不存在
            FilterRule rule = new FilterRule("Name1", "5", FilterOperate.EndsWith);
            FilterRule rule1 = rule;
            Assert.Throws<InvalidOperationException>(() => FilterHelper.GetExpression<TestEntity>(rule1));

            //单条件
            rule = new FilterRule("Name", "5", FilterOperate.EndsWith);
            predicate = FilterHelper.GetExpression<TestEntity>(rule);
            Assert.True(source.Where(predicate).SequenceEqual(source.Where(m => m.Name.EndsWith("5"))));

            //二级条件
            rule = new FilterRule("Name.Length", 5, FilterOperate.Greater);
            predicate = FilterHelper.GetExpression<TestEntity>(rule);
            Assert.True(source.Where(predicate).SequenceEqual(source.Where(m => m.Name.Length > 5)));

            //多条件,异常
            Assert.Throws<InvalidOperationException>(() => new FilterGroup
            {
                Rules = new List<FilterRule> { rule, new FilterRule("IsDeleted", true) },
                Operate = FilterOperate.Equal
            });

            //多条件
            FilterGroup group = new FilterGroup
            {
                Rules = new List<FilterRule> { rule, new FilterRule("IsDeleted", true) },
                Operate = FilterOperate.And
            };
            predicate = FilterHelper.GetExpression<TestEntity>(group);
            Assert.True(source.Where(predicate).SequenceEqual(source.Where(m => m.Name.Length > 5 && m.IsDeleted)));

            //条件组嵌套
            DateTime dt = DateTime.Now;
            group = new FilterGroup
            {
                Rules = new List<FilterRule>
                {
                    new FilterRule("AddDate", dt, FilterOperate.Greater)
                },
                Groups = new List<FilterGroup> { group },
                Operate = FilterOperate.Or
            };
            predicate = FilterHelper.GetExpression<TestEntity>(group);
            Assert.True(source.Where(predicate).SequenceEqual(source.Where(m => m.AddDate > dt || m.Name.Length > 5 && m.IsDeleted)));

        }
 public FilterRuleTests()
 {
     _filterRule = new FilterRule <FakeEntity, int>();
 }
Esempio n. 6
0
        /// <summary>
        /// Método privado para processamento do método 'user.resetpassword'
        /// </summary>
        /// <param name="sqlConnection">Conexão com o banco de dados MS-SQL</param>
        /// <param name="parameters">Dicionário (String, Object) contendo todos os parâmetros necessários</param>
        private Dictionary <String, Object> newfilter(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            if (!parameters.ContainsKey("name"))
            {
                Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null);
                return(null);
            }

            String name = parameters["name"].ToString();

            if (String.IsNullOrWhiteSpace(name))
            {
                Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null);
                return(null);
            }


            DbParameterCollection par2 = new DbParameterCollection();

            par2.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId;
            par2.Add("@filter_name", typeof(String)).Value  = name;

            DataTable dtF1 = database.ExecuteDataTable("select * from filters with(nolock) where enterprise_id = @enterprise_id and name = @filter_name", CommandType.Text, par2, null);

            if ((dtF1 != null) && (dtF1.Rows.Count > 0))
            {
                Error(ErrorType.InvalidRequest, "Filter with the same name already exists.", "", null);
                return(null);
            }


            List <String> log              = new List <String>();
            Boolean       updateName       = false;
            Boolean       updateConditions = false;
            FilterRule    filterData       = getFilterData(database, "", parameters, log, out updateName, out updateConditions);

            if (filterData == null)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(filterData.FilterName))
            {
                Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null);
                return(null);
            }

            if (filterData.FilterGroups.Count == 0)
            {
                Error(ErrorType.InvalidRequest, "Filter conditions is empty.", "", null);
                return(null);
            }

            DataTable dtFilter = null;

            SqlTransaction trans = (SqlTransaction)(SqlTransaction)database.BeginTransaction();

            try
            {
                DbParameterCollection par = new DbParameterCollection();
                par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId;
                par.Add("@filter_name", typeof(String)).Value  = filterData.FilterName;

                dtFilter = database.ExecuteDataTable("sp_new_filter", CommandType.StoredProcedure, par, trans);
                if ((dtFilter == null) && (dtFilter.Rows.Count == 0))
                {
                    Error(ErrorType.InvalidRequest, "Error on insert filter.", "", null);
                    return(null);
                }

                if (updateConditions && filterData.FilterGroups.Count > 0)
                {
                    foreach (FilterGroup g in filterData.FilterGroups)
                    {
                        foreach (FilterCondition f in g.FilterRules)
                        {
                            DbParameterCollection p2 = new DbParameterCollection();
                            p2.Add("@filter_id", typeof(Int64)).Value       = (Int64)dtFilter.Rows[0]["id"];
                            p2.Add("@group_id", typeof(String)).Value       = g.GroupId;
                            p2.Add("@group_selector", typeof(String)).Value = g.Selector.ToString();
                            p2.Add("@field_id", typeof(String)).Value       = f.FieldId;
                            p2.Add("@text", typeof(String)).Value           = f.DataString;
                            p2.Add("@condition", typeof(String)).Value      = f.ConditionType.ToString();
                            p2.Add("@selector", typeof(String)).Value       = f.Selector.ToString();

                            log.Add("Condition inserted: group = " + g.GroupId + ", condition = " + f.ToString());

                            database.ExecuteNonQuery("insert into filters_conditions ([filter_id] ,[group_id] ,[group_selector] ,[field_id] ,[text] ,[condition] ,[selector]) VALUES (@filter_id,@group_id,@group_selector,@field_id,@text,@condition,@selector)", CommandType.Text, p2, trans);
                        }
                    }
                    log.Add("");
                }

                database.AddUserLog(LogKey.Filter_Inserted, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Filter added", String.Join("\r\n", log), Acl.EntityId, trans);

                trans.Commit();
                trans = null;
            }
            catch (Exception ex)
            {
                Error(ErrorType.InvalidRequest, "Error on insert filter", "", null);
                return(null);
            }
            finally
            {
                //Saída sem aviso, ou seja, erro
                if (trans != null)
                {
                    trans.Rollback();
                }
            }



            Dictionary <String, Object> parameters2 = new Dictionary <string, object>();

            parameters2.Add("filterid", dtFilter.Rows[0]["id"]);

            return(get(database, parameters2));
        }
        public void GetExpressionTest()
        {
            IQueryable <TestEntity> source = Entities.AsQueryable();

            //空条件
            FilterRule rule = null;
            Expression <Func <TestEntity, bool> > predicate = FilterHelper.GetExpression <TestEntity>(rule);

            Assert.True(source.Where(predicate).SequenceEqual(source));

            //单条件,属性不存在
            rule = new FilterRule("Name1", "5", FilterOperate.EndsWith);
            Assert.Throws <InvalidOperationException>(() => FilterHelper.GetExpression <TestEntity>(rule));

            //单条件
            rule      = new FilterRule("Name", "5", FilterOperate.EndsWith);
            predicate = FilterHelper.GetExpression <TestEntity>(rule);
            Assert.True(source.Where(predicate).SequenceEqual(source.Where(m => m.Name.EndsWith("5"))));

            //二级条件
            rule      = new FilterRule("Name.Length", 5, FilterOperate.Greater);
            predicate = FilterHelper.GetExpression <TestEntity>(rule);
            Assert.True(source.Where(predicate).SequenceEqual(source.Where(m => m.Name.Length > 5)));

            //多条件,异常
            Assert.Throws <InvalidOperationException>(() => new FilterGroup
            {
                Rules = new List <FilterRule> {
                    rule, new FilterRule("IsDeleted", true)
                },
                Operate = FilterOperate.Equal
            });

            //多条件
            FilterGroup group = new FilterGroup
            {
                Rules = new List <FilterRule> {
                    rule, new FilterRule("IsDeleted", true)
                },
                Operate = FilterOperate.And
            };

            predicate = FilterHelper.GetExpression <TestEntity>(group);
            Assert.True(source.Where(predicate).SequenceEqual(source.Where(m => m.Name.Length > 5 && m.IsDeleted)));

            //条件组嵌套
            DateTime dt = DateTime.Now;

            group = new FilterGroup
            {
                Rules = new List <FilterRule>
                {
                    new FilterRule("AddDate", dt, FilterOperate.Greater)
                },
                Groups = new List <FilterGroup> {
                    group
                },
                Operate = FilterOperate.Or
            };
            predicate = FilterHelper.GetExpression <TestEntity>(group);
            Assert.True(source.Where(predicate).SequenceEqual(source.Where(m => m.AddDate > dt || m.Name.Length > 5 && m.IsDeleted)));
        }
        public async Task <ActionResult> GetSelectWorkLogList(int?FilePath)
        {
            GridRequest request     = new GridRequest(Request);
            FilterRule  rule        = request.FilterGroup.Rules.FirstOrDefault(x => x.Field == "RealName");
            string      strRealName = string.Empty;

            if (rule != null)
            {
                strRealName = rule.Value.ToString();
                request.FilterGroup.Rules.Remove(rule);
            }
            FilterRule rule_file = request.FilterGroup.Rules.FirstOrDefault(x => x.Field == "FilePath");

            if (rule_file != null)
            {
                request.FilterGroup.Rules.Remove(rule_file);
            }
            FilterRule        rule_workLogAttributeId = request.FilterGroup.Rules.FirstOrDefault(x => x.Field == "WorkLogAttributeId");
            IEnumerable <int> workLogAttributeIds     = new int[] { };

            if (rule_workLogAttributeId != null)
            {
                request.FilterGroup.Rules.Remove(rule_workLogAttributeId);
                GetWorkLogIds(Convert.ToInt32(rule_workLogAttributeId.Value), true, ref workLogAttributeIds).ToArray();
            }
            Expression <Func <WorkLog, bool> > predicate = FilterHelper.GetExpression <WorkLog>(request.FilterGroup);
            //只有是部门领导才可以查看部门下的工作
            int           adminId = AuthorityHelper.OperatorId ?? 0;
            Administrator admin   = _adminContract.View(adminId);
            List <int>    listId  = new List <int>()
            {
                adminId
            };

            if (admin != null && admin.JobPosition.IsLeader == true)
            {
                ICollection <Administrator> listAdmins = admin.Department.Administrators;
                if (!string.IsNullOrEmpty(strRealName))
                {
                    listAdmins = listAdmins.Where(x => x.Member.RealName.Contains(strRealName)).ToList();
                }
                listId = listAdmins.Select(x => x.Id).ToList();
            }

            if (FilePath.HasValue)
            {
                if (FilePath.Value == 1)
                {
                    predicate = predicate.And(p => !string.IsNullOrEmpty(p.FilePath));
                }
                else
                {
                    predicate = predicate.And(p => string.IsNullOrEmpty(p.FilePath));
                }
            }

            if (workLogAttributeIds != null && workLogAttributeIds.Count() > 0)
            {
                predicate = predicate.And(p => workLogAttributeIds.Contains(p.WorkLogAttributeId));
            }

            var data = await Task.Run(() =>
            {
                int count;
                IQueryable <WorkLog> listWorkLog = _workLogContract.WorkLogs;
                if (listId != null && listId.Count() > 0)
                {
                    listWorkLog = listWorkLog.Where(x => listId.Contains(x.StaffId ?? 0));
                }
                var list = listWorkLog.Where <WorkLog, int>(predicate, request.PageCondition, out count).Select(m => new
                {
                    m.WorkLogName,
                    m.Id,
                    m.IsDeleted,
                    m.IsEnabled,
                    m.Sequence,
                    m.UpdatedTime,
                    m.Operator.Member.MemberName,
                    WorkLogAttributeName = m.WorkLogAttribute.WorkLogAttributeName,
                    m.FilePath,
                    RealName = m.StaffId == null ? string.Empty : m.Staff.Member.RealName,
                    m.Keys,
                    m.Notes,
                    m.WorkLogAttributeId
                }).ToList();

                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
Esempio n. 9
0
 public RelativePathMatcher(FilterRule rule) : this()
 {
     this.Rule = rule;
 }
Esempio n. 10
0
 public RelativePathMatcher(Regex regex, FilterRule rule, string description = null) : this()
 {
     this.regex       = regex;
     this.description = description ?? $"Regex({regex})";
     this.Rule        = rule;
 }
Esempio n. 11
0
        public static ElementFilter createParameterFilter(Document doc, ParameterData parameter, string operation, string ruleString)
        {
            ElementId parameterId              = parameter.Id;
            ParameterValueProvider fvp         = new ParameterValueProvider(parameterId);
            StorageType            storageType = parameter.StorageType;
            FilterRule             fRule       = null;
            FilterInverseRule      fInvRule    = null;
            ElementParameterFilter filter      = null;


            switch (storageType)
            {
            case StorageType.String:
            case StorageType.Integer:
                FilterStringRuleEvaluator fsre = null;
                switch (operation)
                {
                case "равно":
                    fsre   = new FilterStringEquals();
                    fRule  = new FilterStringRule(fvp, fsre, ruleString, true);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не равно":
                    fsre     = new FilterStringEquals();
                    fRule    = new FilterStringRule(fvp, fsre, ruleString, true);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;

                case "содержит":
                    fsre   = new FilterStringContains();
                    fRule  = new FilterStringRule(fvp, fsre, ruleString, true);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не содержит":
                    fsre     = new FilterStringContains();
                    fRule    = new FilterStringRule(fvp, fsre, ruleString, true);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;

                case "начинается с":
                    fsre   = new FilterStringBeginsWith();
                    fRule  = new FilterStringRule(fvp, fsre, ruleString, true);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не начинается с":
                    fsre     = new FilterStringBeginsWith();
                    fRule    = new FilterStringRule(fvp, fsre, ruleString, true);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;

                case "заканчивается на":
                    fsre   = new FilterStringEndsWith();
                    fRule  = new FilterStringRule(fvp, fsre, ruleString, true);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не заканчивается на":
                    fsre     = new FilterStringEndsWith();
                    fRule    = new FilterStringRule(fvp, fsre, ruleString, true);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;
                }
                break;

            case StorageType.Double:
                FilterNumericRuleEvaluator fnre = null;
                double ruleValue = Convert.ToDouble(ruleString);
                switch (operation)
                {
                case "равно":
                    fnre   = new FilterNumericEquals();
                    fRule  = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не равно":
                    fnre     = new FilterNumericEquals();
                    fRule    = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;

                case "больше":
                    fnre   = new FilterNumericGreater();
                    fRule  = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "больше или равно":
                    fnre   = new FilterNumericGreaterOrEqual();
                    fRule  = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "меньше":
                    fnre   = new FilterNumericLess();
                    fRule  = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "меньше или равно":
                    fnre   = new FilterNumericLessOrEqual();
                    fRule  = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    filter = new ElementParameterFilter(fRule);
                    break;
                }
                break;

            case StorageType.ElementId:

                var       levels = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).ToElements();
                var       level  = levels.Where(i => i.Name == ruleString).FirstOrDefault();
                ElementId ruleId = level.Id;

                fnre = null;
                switch (operation)
                {
                case "равно":
                    fnre   = new FilterNumericEquals();
                    fRule  = new FilterElementIdRule(fvp, fnre, ruleId);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не равно":
                    fnre     = new FilterNumericEquals();
                    fRule    = new FilterElementIdRule(fvp, fnre, ruleId);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;

                case "выше":
                    fnre   = new FilterNumericGreater();
                    fRule  = new FilterElementIdRule(fvp, fnre, ruleId);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "ровно или выше":
                    fnre   = new FilterNumericGreaterOrEqual();
                    fRule  = new FilterElementIdRule(fvp, fnre, ruleId);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "ниже":
                    fnre   = new FilterNumericLess();
                    fRule  = new FilterElementIdRule(fvp, fnre, ruleId);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "ровно или ниже":
                    fnre   = new FilterNumericLessOrEqual();
                    fRule  = new FilterElementIdRule(fvp, fnre, ruleId);
                    filter = new ElementParameterFilter(fRule);
                    break;
                }
                break;
            }
            return(filter);
        }
Esempio n. 12
0
        private FilterRule GetFilterByForm(out WebJsonResponse contentRet)
        {
            contentRet = null;

            String name = Request.Form["filter_name"];

            if (String.IsNullOrEmpty(name))
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("invalid_name"), 3000, true);
                return(null);
            }

            String filters = Request.Form["filter_name"];

            if (String.IsNullOrEmpty(name))
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("invalid_name"), 3000, true);
                return(null);
            }

            //Verifica e trata as regras

            if (String.IsNullOrEmpty(Request.Form["filter_id"]))
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("conditions_is_empty"), 3000, true);
                return(null);
            }

            String rData = JSON.Serialize2(new
            {
                jsonrpc    = "1.0",
                method     = "field.list",
                parameters = new
                {
                    page_size = Int32.MaxValue
                },
                id = 1
            });
            //SqlConnection //conn = DB.GetConnection();
            String jData = "";

            try
            {
                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData);
            }
            finally
            {
            }

            List <FieldData> fieldList = new List <FieldData>();
            FieldListResult  flR       = JSON.Deserialize <FieldListResult>(jData);

            if ((flR != null) && (flR.error == null) && (flR.result != null))
            {
                fieldList = flR.result;
            }

            if (fieldList.Count == 0)
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("field_not_found"), 3000, true);
                return(null);
            }

            FilterRule newItem = new FilterRule(name);


            String[] fIds = Request.Form["filter_id"].Split(",".ToCharArray());
            foreach (String fid in fIds)
            {
                if (String.IsNullOrEmpty(Request.Form["filter_" + fid + "_group"]))
                {
                    contentRet = new WebJsonResponse("", "Grupo não localizado na condição " + fid, 3000, true);
                    break;
                }

                if (String.IsNullOrEmpty(Request.Form["filter_" + fid + "_field_id"]))
                {
                    contentRet = new WebJsonResponse("", "ID do campo não localizado na condição " + fid, 3000, true);
                    break;
                }

                String fGroup = Request.Form["filter_" + fid + "_group"].Split(",".ToCharArray())[0];

                FieldData fieldData = null;
                try
                {
                    Int64 tmp = Int64.Parse(Request.Form["filter_" + fid + "_field_id"].Split(",".ToCharArray())[0]);
                    foreach (FieldData fd in fieldList)
                    {
                        if (fd.field_id == tmp)
                        {
                            fieldData = fd;
                        }
                    }

                    if (fieldData == null)
                    {
                        throw new Exception();
                    }
                }
                catch
                {
                    contentRet = new WebJsonResponse("", "ID do campo inválido na condição " + fid, 3000, true);
                    break;
                }

                FilterSelector filterSelector = FilterSelector.AND;

                if (!String.IsNullOrEmpty(Request.Form["filter_" + fid + "_selector"]))
                {
                    switch (Request.Form["filter_" + fid + "_selector"].Split(",".ToCharArray())[0].ToLower())
                    {
                    case "or":
                        filterSelector = FilterSelector.OR;
                        break;

                    default:
                        filterSelector = FilterSelector.AND;
                        break;
                    }
                }

                FilterConditionType condition = FilterConditionType.Equal;
                switch (fieldData.data_type)
                {
                case "numeric":
                    if (String.IsNullOrEmpty(Request.Form["filter_" + fid + "_condition_numeric"]))
                    {
                        contentRet = new WebJsonResponse("", "Condição de comparação não localizada na condição " + fid, 3000, true);
                        break;
                    }

                    if (String.IsNullOrEmpty(Request.Form["filter_" + fid + "_text_numeric"]))
                    {
                        contentRet = new WebJsonResponse("", "Valor não localizado na condição " + fid, 3000, true);
                        break;
                    }

                    Int64 nValue = 0;
                    try
                    {
                        nValue = Int64.Parse(Request.Form["filter_" + fid + "_text_numeric"].Split(",".ToCharArray())[0]);
                    }
                    catch
                    {
                        contentRet = new WebJsonResponse("", "Valor inválido na condição " + fid, 3000, true);
                        break;
                    }

                    String c1 = Request.Form["filter_" + fid + "_condition_numeric"].Split(",".ToCharArray())[0].ToLower();
                    foreach (FilterConditionType ft in IAM.Filters.FilterCondition.ConditionByDataType(DataType.Numeric))
                    {
                        if (c1 == ft.ToString().ToLower())
                        {
                            condition = ft;
                        }
                    }

                    newItem.AddCondition(fGroup, FilterSelector.AND, fieldData.field_id, "", DataType.Numeric, nValue.ToString(), condition, filterSelector);

                    break;

                case "datetime":
                    if (String.IsNullOrEmpty(Request.Form["filter_" + fid + "_condition_datetime"]))
                    {
                        contentRet = new WebJsonResponse("", "Condição de comparação não localizada na condição " + fid, 3000, true);
                        break;
                    }

                    if (String.IsNullOrEmpty(Request.Form["filter_" + fid + "_text_date"]))
                    {
                        contentRet = new WebJsonResponse("", "Valor de data não localizado na condição " + fid, 3000, true);
                        break;
                    }

                    if (String.IsNullOrEmpty(Request.Form["filter_" + fid + "_text_time"]))
                    {
                        contentRet = new WebJsonResponse("", "Valor de hora não localizado na condição " + fid, 3000, true);
                        break;
                    }

                    String dtValue = "";
                    try
                    {
                        if (Request.Form["filter_" + fid + "_text_date"].Split(",".ToCharArray())[0].ToLower() == "now")
                        {
                            dtValue = "now";
                        }
                        else
                        {
                            DateTime tmp = DateTime.Parse(Request.Form["filter_" + fid + "_text_date"].Split(",".ToCharArray())[0] + " " + Request.Form["filter_" + fid + "_text_time"].Split(",".ToCharArray())[0]);
                            dtValue = tmp.ToString("o");
                        }
                    }
                    catch
                    {
                        contentRet = new WebJsonResponse("", "Valor de data e hora inválidos na condição " + fid, 3000, true);
                        break;
                    }

                    String c2 = Request.Form["filter_" + fid + "_condition_datetime"].Split(",".ToCharArray())[0].ToLower();
                    foreach (FilterConditionType ft in IAM.Filters.FilterCondition.ConditionByDataType(DataType.DateTime))
                    {
                        if (c2 == ft.ToString().ToLower())
                        {
                            condition = ft;
                        }
                    }

                    newItem.AddCondition(fGroup, FilterSelector.AND, fieldData.field_id, "", DataType.DateTime, dtValue, condition, filterSelector);

                    break;

                default:
                    if (String.IsNullOrEmpty(Request.Form["filter_" + fid + "_condition_string"]))
                    {
                        contentRet = new WebJsonResponse("", "Condição de comparação não localizada na condição " + fid, 3000, true);
                        break;
                    }

                    if (String.IsNullOrEmpty(Request.Form["filter_" + fid + "_text_string"]))
                    {
                        contentRet = new WebJsonResponse("", "Valor não localizado na condição " + fid, 3000, true);
                        break;
                    }


                    String c3 = Request.Form["filter_" + fid + "_condition_string"].Split(",".ToCharArray())[0].ToLower();
                    foreach (FilterConditionType ft in IAM.Filters.FilterCondition.ConditionByDataType(DataType.Text))
                    {
                        if (c3 == ft.ToString().ToLower())
                        {
                            condition = ft;
                        }
                    }

                    newItem.AddCondition(fGroup, FilterSelector.AND, fieldData.field_id, "", DataType.Text, Request.Form["filter_" + fid + "_text_string"].Split(",".ToCharArray())[0], condition, filterSelector);
                    break;
                }
            }

            //Atualiza os seletores dos grupos caso haja mais de 1 grupo
            if (newItem.FilterGroups.Count > 1)
            {
                foreach (FilterGroup g in newItem.FilterGroups)
                {
                    if (!String.IsNullOrEmpty(Request.Form["group_" + g.GroupId + "_selector"]))
                    {
                        switch (Request.Form["group_" + g.GroupId + "_selector"].Split(",".ToCharArray())[0].ToLower())
                        {
                        case "and":
                            g.Selector = FilterSelector.AND;
                            break;

                        default:
                            g.Selector = FilterSelector.OR;
                            break;
                        }
                    }
                }
            }

            return(newItem);
        }
Esempio n. 13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse contentRet = null;


            String action = "";

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["action"]))
            {
                action = (String)RouteData.Values["action"];
            }

            Int64 filterId = 0;

            if (action != "add_filter")
            {
                try
                {
                    filterId = Int64.Parse((String)RouteData.Values["id"]);

                    if (filterId < 0)
                    {
                        filterId = 0;
                    }
                }
                catch { }

                if (filterId == 0)
                {
                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("filter_not_found"), 3000, true);
                    action     = "";
                }
            }

            String rData = "";
            //SqlConnection //conn = DB.GetConnection();
            String jData = "";

            try
            {
                switch (action)
                {
                case "delete":

                    var reqDel = new
                    {
                        jsonrpc    = "1.0",
                        method     = "filter.delete",
                        parameters = new
                        {
                            filterid = filterId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqDel);

                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData);

                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    FieldDeleteResult retDel = JSON.Deserialize <FieldDeleteResult>(jData);
                    if (retDel == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("filter_not_found"), 3000, true);
                    }
                    else if (retDel.error != null)
                    {
                        contentRet = new WebJsonResponse("", retDel.error.data, 3000, true);
                    }
                    else if (!retDel.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("filter_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;

                case "add_filter":

                    contentRet = null;
                    FilterRule newItem = GetFilterByForm(out contentRet);
                    if ((contentRet != null) || (newItem == null))
                    {
                        break;
                    }

                    rData = JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "filter.new",
                        parameters = newItem.ToJsonObject(),
                        id         = 1
                    });

                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData);

                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    FilterGetResult retN = JSON.Deserialize <FilterGetResult>(jData);
                    if (retN == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("filter_not_found"), 3000, true);
                    }
                    else if (retN.error != null)
                    {
                        contentRet = new WebJsonResponse("", retN.error.data, 3000, true);
                    }
                    else if (retN.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("filter_not_found"), 3000, true);
                    }
                    else if (retN.result == null || retN.result.info == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("filter_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/filter/" + retN.result.info.filter_id + "/");
                    }
                    break;

                case "change":

                    contentRet = null;
                    FilterRule newItem1 = GetFilterByForm(out contentRet);
                    if ((contentRet != null) || (newItem1 == null))
                    {
                        break;
                    }

                    Dictionary <String, Object> par = newItem1.ToJsonObject();
                    par.Add("filterid", filterId);

                    rData = JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "filter.change",
                        parameters = par,
                        id         = 1
                    });

                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData);

                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    FilterGetResult retC = JSON.Deserialize <FilterGetResult>(jData);
                    if (retC == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("filter_not_found"), 3000, true);
                    }
                    else if (retC.error != null)
                    {
                        contentRet = new WebJsonResponse("", retC.error.data, 3000, true);
                    }
                    else if (retC.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("filter_not_found"), 3000, true);
                    }
                    else if (retC.result == null || retC.result.info == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("filter_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet             = new WebJsonResponse("", MessageResource.GetMessage("info_saved"), 3000, false);
                        contentRet.redirectURL = Session["ApplicationVirtualPath"] + "admin/filter/" + retC.result.info.filter_id + "/";
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
            }
            finally
            {
            }

            if (contentRet != null)
            {
                if (!String.IsNullOrWhiteSpace((String)Request["cid"]))
                {
                    contentRet.callId = (String)Request["cid"];
                }


                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Esempio n. 14
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            // Door variables.
            string doorName = string.Empty;
            string itemType = string.Empty;
            string doorType = string.Empty;
            int    height   = 0;
            int    width    = 0;
            string props    = string.Empty;

            // Find the right door family.
            FilteredElementCollector collector =
                new FilteredElementCollector(doc);

            FilterRule famNameRule = ParameterFilterRuleFactory
                                     .CreateBeginsWithRule(
                new ElementId((int)BuiltInParameter.ALL_MODEL_FAMILY_NAME),
                "A-M3-ConceptualDoor", true);

            FilterRule typeNameRule = ParameterFilterRuleFactory
                                      .CreateEqualsRule(
                new ElementId((int)BuiltInParameter.ALL_MODEL_TYPE_NAME),
                "Default", true);

            ElementParameterFilter famNameFlt =
                new ElementParameterFilter(famNameRule);

            ElementParameterFilter typeNameFlt =
                new ElementParameterFilter(typeNameRule);

            LogicalAndFilter andFilter =
                new LogicalAndFilter(famNameFlt, typeNameFlt);

            Func <FamilySymbol, bool> singleLeaf =
                (fs) => fs.FamilyName == "A-M3-ConceptualDoorSingleLeaf-LOD2";

            Func <FamilySymbol, bool> doubleLeaf =
                (fs) => fs.FamilyName == "A-M3-ConceptualDoorDoubleLeaf-LOD2";

            IEnumerable <FamilySymbol> doors = collector
                                               .OfCategory(BuiltInCategory.OST_Doors)
                                               .WhereElementIsElementType()
                                               .WherePasses(andFilter)
                                               .Cast <FamilySymbol>();

            FamilySymbol singleLeafDoor = doors
                                          .Where(singleLeaf)
                                          .FirstOrDefault();

            FamilySymbol doubleLeafDoor = doors
                                          .Where(doubleLeaf)
                                          .FirstOrDefault();

            if (singleLeafDoor == null)
            {
                TaskDialog.Show("No door family",
                                "Please load the family: A-M3-ConceptualDoorSingleLeaf-LOD2");
                return(Result.Failed);
            }

            // Show the custom window
            RussianDoorWnd win = new RussianDoorWnd();

            win.btnCreate.Click += delegate(object sender, RoutedEventArgs e) {
                doorName = win.lbg6629.Content.ToString();

                itemType = ((ComboBoxItem)win.itemType.SelectedItem).Content.ToString();
                doorType = ((ComboBoxItem)win.doorType.SelectedItem).Content.ToString();
                height   = Int16.Parse((string)((ComboBoxItem)win.height.SelectedItem).Content) * 100;
                width    = Int16.Parse((string)((ComboBoxItem)win.width.SelectedItem).Content) * 100;
                props    = ((ComboBoxItem)win.props.SelectedItem).Content.ToString();

                win.Close();

                try {
                    using (TransactionGroup tg = new TransactionGroup(doc, "Create new type")) {
                        ElementType newType;

                        tg.Start();

                        using (Transaction t1 = new Transaction(doc, "Create new type")) {
                            t1.Start();
                            if (width <= 1200)
                            {
                                newType = singleLeafDoor.Duplicate(doorName);
                            }
                            else
                            {
                                newType = doubleLeafDoor.Duplicate(doorName);
                            }
                            t1.Commit();
                        }

                        using (Transaction t2 = new Transaction(doc, "Set params")) {
                            t2.Start();

                            switch (doorType)
                            {
                            case "Г":
                                newType.LookupParameter("Solid Leaf").Set(1);
                                newType.LookupParameter("Glazed Leaf").Set(0);
                                newType.LookupParameter("Leaf with Vent Grille").Set(0);
                                break;

                            case "О":
                                newType.LookupParameter("Solid Leaf").Set(0);
                                newType.LookupParameter("Glazed Leaf").Set(1);
                                newType.LookupParameter("Leaf with Vent Grille").Set(0);
                                break;
                            }

                            newType.LookupParameter("Door Leaf Height")
                            .Set(RvtCnvt.ConvertToInternalUnits((height - 100), DisplayUnitType.DUT_MILLIMETERS));

                            newType.LookupParameter("Door Leaf Width")
                            .Set(RvtCnvt.ConvertToInternalUnits((width - 100), DisplayUnitType.DUT_MILLIMETERS));

                            if (props.Contains('Л'))
                            {
                                newType.LookupParameter("RH").Set(0);
                            }
                            else
                            {
                                newType.LookupParameter("RH").Set(1);
                            }

                            if (props.Contains('П'))
                            {
                                newType.LookupParameter("Threshold").Set(1);
                            }
                            else
                            {
                                newType.LookupParameter("Threshold").Set(0);
                            }

                            t2.Commit();
                        }

                        tg.Assimilate();
                    }
                }
                catch (Autodesk.Revit.Exceptions.ArgumentException ex) {
                    if (ex.ParamName == "name")
                    {
                        TaskDialog.Show("ArgumentError",
                                        string.Format("This type already exists."));
                    }
                }
                catch (Exception ex) {
                    TaskDialog.Show("Exception", ex.StackTrace);
                }
            };

            win.ShowDialog();

            return(Result.Succeeded);
        }
Esempio n. 15
0
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);

            string     applicantName     = "";
            FilterRule ruleApplicantName = request.FilterGroup.Rules.FirstOrDefault(x => x.Field == "ApplicantName");

            if (ruleApplicantName != null)
            {
                applicantName = ruleApplicantName.Value.ToString();
                request.FilterGroup.Rules.Remove(ruleApplicantName);
            }
            string     departmentName = "";
            FilterRule ruleDepartment = request.FilterGroup.Rules.FirstOrDefault(x => x.Field == "Department");

            if (ruleDepartment != null)
            {
                departmentName = ruleDepartment.Value.ToString();
                request.FilterGroup.Rules.Remove(ruleDepartment);
            }
            string     workOrderTitlee    = "";
            FilterRule ruleWorkOrderTitle = request.FilterGroup.Rules.FirstOrDefault(x => x.Field == "WorkOrderTitle");

            if (ruleWorkOrderTitle != null)
            {
                workOrderTitlee = ruleWorkOrderTitle.Value.ToString();
                request.FilterGroup.Rules.Remove(ruleWorkOrderTitle);
            }
            int        workOrderCategoryId     = 0;
            FilterRule ruleWorkOrderCategoryId = request.FilterGroup.Rules.FirstOrDefault(x => x.Field == "WorkOrderCategoryId");

            if (ruleWorkOrderCategoryId != null)
            {
                workOrderCategoryId = ruleWorkOrderCategoryId.Value != null?Convert.ToInt32(ruleWorkOrderCategoryId.Value) : 0;

                request.FilterGroup.Rules.Remove(ruleWorkOrderCategoryId);
            }
            Expression <Func <WorkOrderDealtWith, bool> > predicate = FilterHelper.GetExpression <WorkOrderDealtWith>(request.FilterGroup);

            var data = await Task.Run(() =>
            {
                if (!string.IsNullOrEmpty(applicantName))
                {
                    predicate = predicate.And(p => p.WorkOrder != null && p.WorkOrder.Applicant != null && p.WorkOrder.Applicant.Member != null && p.WorkOrder.Applicant.Member.RealName.Contains(applicantName));
                }

                if (!string.IsNullOrEmpty(departmentName))
                {
                    predicate = predicate.And(p => p.WorkOrder != null && p.WorkOrder.DepartmentId.Equals(departmentName));
                }

                if (!string.IsNullOrEmpty(workOrderTitlee))
                {
                    predicate = predicate.And(p => p.WorkOrder != null && p.WorkOrder.WorkOrderTitle.Contains(workOrderTitlee));
                }

                if (workOrderCategoryId != 0)
                {
                    predicate = predicate.And(p => p.WorkOrder != null && p.WorkOrder.WorkOrderCategoryId.Equals(workOrderCategoryId));
                }
                int count;
                var list = (from s in _workOrderDealtWithContract.Entities.Where <WorkOrderDealtWith, int>(predicate, request.PageCondition, out count)
                            select new
                {
                    s.Id,
                    s.IsDeleted,
                    s.IsEnabled,
                    s.WorkOrder.CreatedTime,
                    s.WorkOrder.WorkOrderTitle,
                    s.Status,
                    DepartmentName = s.WorkOrder.Department != null ? s.WorkOrder.Department.DepartmentName : "",
                    ApplicantName = s.WorkOrder.Applicant != null && s.WorkOrder.Applicant.Member != null ? s.WorkOrder.Applicant.Member.RealName : "",
                    WorkOrderCategoryName = s.WorkOrder.WorkOrderCategory != null ? s.WorkOrder.WorkOrderCategory.WorkOrderCategoryName : "",
                    OperationName = s.Operator != null && s.Operator.Member != null ? s.Operator.Member.RealName : "",
                    HandleName = s.WorkOrder.Handler != null && s.WorkOrder.Handler.Member != null ? s.WorkOrder.Handler.Member.RealName : "",
                    s.WorkOrder.DealtTime,
                    s.WorkOrder.FinishTime
                }).ToList();

                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
Esempio n. 16
0
        public async Task SetQueueConfigurationTests()
        {
            var filterRule = new FilterRule("Prefix", "test/");

            using (var sqsClient = new AmazonSQSClient())
            {
                string topicName      = UtilityMethods.GenerateName("events-test");
                var    createResponse = await sqsClient.CreateQueueAsync(topicName);

                var bucketName = await UtilityMethods.CreateBucketAsync(Client, "SetQueueConfigurationTests");

                try
                {
                    var queueArn = await sqsClient.AuthorizeS3ToSendMessageAsync(createResponse.QueueUrl, bucketName);

                    PutBucketNotificationRequest putRequest = new PutBucketNotificationRequest
                    {
                        BucketName          = bucketName,
                        QueueConfigurations = new List <QueueConfiguration>
                        {
                            new QueueConfiguration
                            {
                                Id     = "the-queue-test",
                                Queue  = queueArn,
                                Events = { EventType.ObjectCreatedPut },
                                Filter = new Filter
                                {
                                    S3KeyFilter = new S3KeyFilter
                                    {
                                        FilterRules = new List <FilterRule>
                                        {
                                            filterRule
                                        }
                                    }
                                }
                            }
                        }
                    };

                    await Client.PutBucketNotificationAsync(putRequest);

                    var getResponse = WaitUtils.WaitForComplete(
                        () =>
                    {
                        return(Client.GetBucketNotificationAsync(bucketName).Result);
                    },
                        (r) =>
                    {
                        return(r.QueueConfigurations.Count > 0);
                    });

                    Assert.Equal(1, getResponse.QueueConfigurations.Count);
                    Assert.Equal(1, getResponse.QueueConfigurations[0].Events.Count);
                    Assert.Equal(EventType.ObjectCreatedPut, getResponse.QueueConfigurations[0].Events[0]);

                    Assert.NotNull(getResponse.QueueConfigurations[0].Filter);
                    Assert.NotNull(getResponse.QueueConfigurations[0].Filter.S3KeyFilter);
                    Assert.NotNull(getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules);
                    Assert.Equal(1, getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules.Count);
                    Assert.Equal(filterRule.Name, getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules[0].Name);
                    Assert.Equal(filterRule.Value, getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules[0].Value);

                    Assert.Equal("the-queue-test", getResponse.QueueConfigurations[0].Id);
                    Assert.Equal(queueArn, getResponse.QueueConfigurations[0].Queue);

                    // Purge queue to remove test message sent configuration was setup.
                    await sqsClient.PurgeQueueAsync(createResponse.QueueUrl);

                    // make sure the queue is really clear
                    WaitUtils.WaitForComplete(
                        () =>
                    {
                        return(sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest()
                        {
                            QueueUrl = createResponse.QueueUrl
                        }).Result);
                    },
                        (r) =>
                    {
                        return(r.Messages.Count == 0);
                    });

                    var putObjectRequest = new PutObjectRequest
                    {
                        BucketName  = bucketName,
                        Key         = "test/data.txt",
                        ContentBody = "Important Data"
                    };
                    await Client.PutObjectAsync(putObjectRequest);

                    var response = WaitUtils.WaitForComplete(
                        () =>
                    {
                        return(sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest
                        {
                            QueueUrl = createResponse.QueueUrl,
                            WaitTimeSeconds = 20
                        }).Result);
                    },
                        (r) =>
                    {
                        return(r.Messages.Count > 0);
                    });

                    var evnt = S3EventNotification.ParseJson(response.Messages[0].Body);

                    Assert.Equal(1, evnt.Records.Count);
                    Assert.Equal(putObjectRequest.BucketName, evnt.Records[0].S3.Bucket.Name);
                    Assert.Equal(putObjectRequest.Key, evnt.Records[0].S3.Object.Key);
                    Assert.Equal(putObjectRequest.ContentBody.Length, evnt.Records[0].S3.Object.Size);
                }
                finally
                {
                    await sqsClient.DeleteQueueAsync(createResponse.QueueUrl);

                    await UtilityMethods.DeleteBucketWithObjectsAsync(Client, bucketName);
                }
            }
        }
Esempio n. 17
0
        private string TranslateRule(FilterRule rule)
        {
            var strBuilder = new StringBuilder();

            if (rule == null)
            {
                return(" 1=1 ");
            }
            if (currentParamMath.Contains(rule.Field))
            {
                strBuilder.Append(GetCurrentRule(rule));
                return(strBuilder.ToString());
            }

            switch (rule.Op)
            {
            case FilterRuleOp.Equal:
            case FilterRuleOp.Greater:
            case FilterRuleOp.GreaterOrEqual:
            case FilterRuleOp.Less:
            case FilterRuleOp.LessOrEqual:
            case FilterRuleOp.NotEqual:
                strBuilder.Append(rule.Field);
                strBuilder.Append(GetFilterRuleOpQueryText(rule.Op));
                strBuilder.Append(GetParamToken());
                AddParam(rule);
                break;

            case FilterRuleOp.Like:
                strBuilder.Append(rule.Field);
                strBuilder.Append($".Contains({GetParamToken()})");
                ListParams.Add(rule.Value);
                break;

            case FilterRuleOp.StartWith:
                strBuilder.Append(rule.Field);
                strBuilder.Append($".StartsWith({GetParamToken()})");
                ListParams.Add(rule.Value);
                break;

            case FilterRuleOp.EndWith:
                strBuilder.Append(rule.Field);
                strBuilder.Append($".EndsWith({GetParamToken()})");
                ListParams.Add(rule.Value);
                break;

            case FilterRuleOp.In:
                strBuilder.Append($"{GetParamToken()}.Contains(outerIt.{rule.Field})");
                AddArrayParam(rule);
                break;

            case FilterRuleOp.Notin:
                strBuilder.Append($"!{GetParamToken()}.Contains(outerIt.{rule.Field})");
                AddArrayParam(rule);
                break;

            default:
                break;
            }
            return(strBuilder.ToString());
        }
Esempio n. 18
0
        public void SetQueueConfigurationTests()
        {
            var filterRule = new FilterRule("Prefix", "test/");
            var s3Config   = new AmazonS3Config();

            using (var s3Client = new AmazonS3Client(s3Config))
                using (var sqsClient = new AmazonSQSClient())
                {
                    var createResponse = sqsClient.CreateQueue("events-test-" + DateTime.Now.Ticks);
                    var bucketName     = S3TestUtils.CreateBucket(s3Client);
                    try
                    {
                        var queueArn = sqsClient.AuthorizeS3ToSendMessage(createResponse.QueueUrl, bucketName);

                        PutBucketNotificationRequest putRequest = new PutBucketNotificationRequest
                        {
                            BucketName          = bucketName,
                            QueueConfigurations = new List <QueueConfiguration>
                            {
                                new QueueConfiguration
                                {
                                    Id     = "the-queue-test",
                                    Queue  = queueArn,
                                    Events = { EventType.ObjectCreatedPut },
                                    Filter = new Filter
                                    {
                                        S3KeyFilter = new S3KeyFilter
                                        {
                                            FilterRules = new List <FilterRule>
                                            {
                                                filterRule
                                            }
                                        }
                                    }
                                }
                            }
                        };

                        s3Client.PutBucketNotification(putRequest);

                        var getResponse = s3Client.GetBucketNotification(bucketName);

                        Assert.AreEqual(1, getResponse.QueueConfigurations.Count);
                        Assert.AreEqual(1, getResponse.QueueConfigurations[0].Events.Count);
                        Assert.AreEqual(EventType.ObjectCreatedPut, getResponse.QueueConfigurations[0].Events[0]);

                        Assert.IsNotNull(getResponse.QueueConfigurations[0].Filter);
                        Assert.IsNotNull(getResponse.QueueConfigurations[0].Filter.S3KeyFilter);
                        Assert.IsNotNull(getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules);
                        Assert.AreEqual(1, getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules.Count);
                        Assert.AreEqual(filterRule.Name, getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules[0].Name);
                        Assert.AreEqual(filterRule.Value, getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules[0].Value);

                        Assert.AreEqual("the-queue-test", getResponse.QueueConfigurations[0].Id);
                        Assert.AreEqual(queueArn, getResponse.QueueConfigurations[0].Queue);

                        // Purge queue to remove test message sent configuration was setup.
                        sqsClient.PurgeQueue(createResponse.QueueUrl);
                        Thread.Sleep(TimeSpan.FromSeconds(1));

                        var putObjectRequest = new PutObjectRequest
                        {
                            BucketName  = bucketName,
                            Key         = "test/data.txt",
                            ContentBody = "Important Data"
                        };

                        s3Client.PutObject(putObjectRequest);

                        string messageBody = null;
                        for (int i = 0; i < 5 && messageBody == null; i++)
                        {
                            var receiveResponse = sqsClient.ReceiveMessage(new ReceiveMessageRequest {
                                QueueUrl = createResponse.QueueUrl, WaitTimeSeconds = 20
                            });
                            if (receiveResponse.Messages.Count != 0)
                            {
                                messageBody = receiveResponse.Messages[0].Body;
                            }
                        }


                        var evnt = S3EventNotification.ParseJson(messageBody);

                        Assert.AreEqual(1, evnt.Records.Count);
                        Assert.AreEqual(putObjectRequest.BucketName, evnt.Records[0].S3.Bucket.Name);
                        Assert.AreEqual(putObjectRequest.Key, evnt.Records[0].S3.Object.Key);
                        Assert.AreEqual(putObjectRequest.ContentBody.Length, evnt.Records[0].S3.Object.Size);
                    }
                    finally
                    {
                        sqsClient.DeleteQueue(createResponse.QueueUrl);
                        AmazonS3Util.DeleteS3BucketWithObjects(s3Client, bucketName);
                    }
                }
        }
Esempio n. 19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod != "POST")
            {
                return;
            }

            String area = "";

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"]))
            {
                area = (String)RouteData.Values["area"];
            }

            Int64 enterpriseId = 0;

            if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData))
            {
                enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id;
            }

            Boolean newItem = false;

            if ((RouteData.Values["new"] != null) && (RouteData.Values["new"] == "1"))
            {
                newItem = true;
            }

            String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();

            LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
            LMenu menu2 = new LMenu("Filtros", ApplicationVirtualPath + "admin/filter/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
            LMenu menu3 = new LMenu("Filtros", ApplicationVirtualPath + "admin/filter/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));

            WebJsonResponse contentRet = null;

            String html  = "";
            String eHtml = "";
            String js    = null;

            String errorTemplate = "<span class=\"empty-results\">{0}</span>";

            //Verifica se está sendo selecionada uma role
            Int64 filterId = 0;

            try
            {
                filterId = Int64.Parse((String)RouteData.Values["id"]);

                if (filterId < 0)
                {
                    filterId = 0;
                }
            }
            catch { }

            String          error     = "";
            FilterGetResult retFilter = null;
            String          filter    = "";
            HashData        hashData  = new HashData(this);

            String rData = null;
            //SqlConnection conn = null;
            String jData = "";

            Int32   page     = 1;
            Int32   pageSize = 20;
            Boolean hasNext  = true;

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["filter"]))
            {
                filter = (String)RouteData.Values["filter"];
            }

            if ((filterId > 0) && (area.ToLower() != "search"))
            {
                try
                {
                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "filter.get",
                        parameters = new
                        {
                            filterid = filterId
                        },
                        id = 1
                    });
                    jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    retFilter = JSON.Deserialize <FilterGetResult>(jData);
                    if (retFilter == null)
                    {
                        error = MessageResource.GetMessage("filter_not_found");
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retFilter.error != null)
                    {
                        error     = retFilter.error.data;
                        retFilter = null;
                    }
                    else if (retFilter.result == null || retFilter.result.info == null)
                    {
                        error     = MessageResource.GetMessage("filter_not_found");
                        retFilter = null;
                    }
                    else
                    {
                        menu3.Name = retFilter.result.info.name;
                    }
                }
                catch (Exception ex)
                {
                    error = MessageResource.GetMessage("api_error");
                    Tools.Tool.notifyException(ex, this);
                    retFilter = null;
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }
            }

            String infoTemplate = "<tr><td class=\"col1\">{0}</td><td class=\"col2\"><span class=\"no-edit\">{1}</span></td></tr>";

            String groupTemplate          = "<div id=\"{0}\"><div class=\"group\" group-id=\"{0}\"><div class=\"wrapper\"><div class=\"cmd-bar\"><div class=\"ico icon-close floatright\"></div></div>{1}<div class=\"cmd-bar1\"><div class=\"ico icon-plus floatright\"></div></div></div><div class=\"clear-block\"></div></div><div class=\"selector-wrapper\">{2}</div></div>";
            String groupSelectorTemplate  = "<div class=\"group-selector\"><select type=\"checkbox\" name=\"group_{0}_selector\"><option value=\"or\" {1}>or</option><option value=\"and\" {2}>and</option></select><div class=\"item {1}\" value=\"or\">OU</div><div class=\"item {2}\" value=\"and\">E</div><div class=\"clear-block\"></div></div>";
            String filterSelectorTemplate = "<div class=\"filter-selector\"><select type=\"checkbox\" name=\"filter_{0}_selector\"><option value=\"or\" {1}>or</option><option value=\"and\" {2}>and</option></select> <div class=\"item {1}\" value=\"or\">OU</div><div class=\"item {2}\" value=\"and\">E</div><div class=\"clear-block\"></div></div>";


            switch (area)
            {
            case "":
            case "search":
            case "content":
                if (newItem)
                {
                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "field.list",
                        parameters = new
                        {
                            page_size = Int32.MaxValue
                        },
                        id = 1
                    });
                    jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);

                    List <FieldData> fieldList = new List <FieldData>();
                    FieldListResult  flR       = JSON.Deserialize <FieldListResult>(jData);
                    if ((flR != null) && (flR.error == null) && (flR.result != null))
                    {
                        fieldList = flR.result;
                    }

                    String filterTemplate = GetFilterTemplate(fieldList, 0, "", "");

                    html  = "<h3>Adição do filtro</h3>";
                    html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/filter/action/add_filter/\">";
                    html += "<div class=\"no-tabs fields\"><table><tbody>";
                    html += String.Format(infoTemplate, "Nome", "<input id=\"filter_name\" name=\"filter_name\" placeholder=\"Digite o nome do filtro\" type=\"text\"\">");
                    html += "</tbody></table><div class=\"clear-block\"></div></div>";

                    html += "<h3>Parametros de filtragem</h3><div class=\"no-tabs pb10\">";
                    html += "<div id=\"filter_conditions\"><div><div class=\"a-btn blue secondary\" onclick=\"iamfnc.addGroup();\">Inserir grupo</div></div>";
                    html += "<div class=\"filter-groups\">";


                    String filters = String.Format(filterTemplate, "F0", "0", "");
                    html += String.Format(groupTemplate, "0", filters, "");

                    html += "</div>";

                    html += "</div><div class=\"clear-block\"></div></div>";
                    html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/filter/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                    contentRet    = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                    contentRet.js = GetFilterJS(groupTemplate, groupSelectorTemplate, filterTemplate, filterSelectorTemplate);
                }
                else
                {
                    if (retFilter == null)
                    {
                        Int32.TryParse(Request.Form["page"], out page);

                        if (page < 1)
                        {
                            page = 1;
                        }

                        String proxyTemplate = "<div id=\"proxy-list-{0}\" data-id=\"{0}\" data-name=\"{1}\" data-total=\"{2}\" class=\"app-list-item\">";
                        proxyTemplate += "<table>";
                        proxyTemplate += "   <tbody>";
                        proxyTemplate += "       <tr>";
                        proxyTemplate += "           <td class=\"col1\">";
                        proxyTemplate += "               <span id=\"total_{0}\" class=\"total \">{2}</span>";
                        proxyTemplate += "               <a href=\"" + ApplicationVirtualPath + "admin/filter/{0}/use/\">";
                        proxyTemplate += "                   <div class=\"app-btn a-btn\"><span class=\"a-btn-inner\">Ver utilizações</span></div>";
                        proxyTemplate += "               </a>";
                        proxyTemplate += "           </td>";
                        proxyTemplate += "           <td class=\"col2\">";
                        proxyTemplate += "               <div class=\"title\"><span class=\"name field-editor\" id=\"filter_name_{0}\" data-id=\"{0}\" data-function=\"iamadmin.editTextField('#filter_name_{0}',null,filterNameEdit);\">{1}</span><span class=\"date\">{3}</span><div class=\"clear-block\"></div></div>";
                        proxyTemplate += "               <div class=\"description\">";
                        proxyTemplate += "                   <div class=\"first\">{4}</div>";
                        proxyTemplate += "               </div>";
                        proxyTemplate += "               <div class=\"links\">";
                        proxyTemplate += "                   <div class=\"last\">{5}</div>";
                        proxyTemplate += "               </div>";
                        proxyTemplate += "           </td>";
                        proxyTemplate += "       </tr>";
                        proxyTemplate += "   </tbody>";
                        proxyTemplate += "</table></div>";

                        js += "filterNameEdit = function(thisId, changedText) { iamadmin.changeName(thisId,changedText); };";

                        html += "<div id=\"box-container\" class=\"box-container\">";

                        String query = "";
                        try
                        {
                            rData = "";

                            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["query"]))
                            {
                                query = (String)RouteData.Values["query"];
                            }

                            if (String.IsNullOrWhiteSpace(query) && !String.IsNullOrWhiteSpace(hashData.GetValue("query")))
                            {
                                query = hashData.GetValue("query");
                            }

                            if (String.IsNullOrWhiteSpace(query))
                            {
                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "filter.list",
                                    parameters = new
                                    {
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                });
                            }
                            else
                            {
                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "filter.search",
                                    parameters = new
                                    {
                                        text      = query,
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                });
                            }

                            jData = "";
                            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);

                            if (String.IsNullOrWhiteSpace(jData))
                            {
                                throw new Exception("");
                            }

                            FilterListResult ret2 = JSON.Deserialize <FilterListResult>(jData);
                            if (ret2 == null)
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("filter_not_found"));
                                hasNext = false;
                            }
                            else if (ret2.error != null)
                            {
#if DEBUG
                                eHtml += String.Format(errorTemplate, ret2.error.data + ret2.error.debug);
#else
                                eHtml += String.Format(errorTemplate, ret2.error.data);
#endif
                                hasNext = false;
                            }
                            else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("filter_not_found"));
                                hasNext = false;
                            }
                            else
                            {
                                foreach (FilterData f in ret2.result)
                                {
                                    String text = "<span>" + f.conditions_description + "</span>";

                                    String links = "";
                                    links += "<a href=\"" + ApplicationVirtualPath + "admin/filter/" + f.filter_id + "/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-change\">Editar</div></a>";
                                    links += (f.ignore_qty > 0 || f.lock_qty > 0 || f.role_qty > 0 ? "" : "<a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/filter/" + f.filter_id + "/action/delete/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente o filtro '" + f.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Apagar</div></a>");

                                    html += String.Format(proxyTemplate, f.filter_id, f.name, f.ignore_qty + f.lock_qty + f.role_qty, (f.create_date > 0 ? "Criado em " + MessageResource.FormatDate(new DateTime(1970, 1, 1).AddSeconds(f.create_date), true) : ""), text, links);
                                }

                                if (ret2.result.Count < pageSize)
                                {
                                    hasNext = false;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        }

                        if (page == 1)
                        {
                            html += "</div>";

                            html += "<span class=\"empty-results content-loading proxy-list-loader hide\"></span>";

                            contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                        }
                        else
                        {
                            contentRet = new WebJsonResponse("#content-wrapper #box-container", (eHtml != "" ? eHtml : html), true);
                        }

                        contentRet.js = js + "$( document ).unbind('end_of_scroll');";

                        if (hasNext)
                        {
                            contentRet.js += "$( document ).bind( 'end_of_scroll.loader_role', function() { $( document ).unbind('end_of_scroll.loader_role'); $('.proxy-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'" + (!String.IsNullOrWhiteSpace(query) ? query : "") + "' }, function(){ $('.proxy-list-loader').addClass('hide'); } ); });";
                        }
                    }
                    else    //Esta sendo selecionado o filtro
                    {
                        if (error != "")
                        {
                            contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                        }
                        else
                        {
                            switch (filter)
                            {
                            case "":

                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "field.list",
                                    parameters = new
                                    {
                                        page_size = Int32.MaxValue
                                    },
                                    id = 1
                                });
                                jData = "";
                                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                    jData = WebPageAPI.ExecuteLocal(database, this, rData);

                                List <FieldData> fieldList = new List <FieldData>();
                                FieldListResult  flR       = JSON.Deserialize <FieldListResult>(jData);
                                if ((flR != null) && (flR.error == null) && (flR.result != null))
                                {
                                    fieldList = flR.result;
                                }


                                String filterTemplate = GetFilterTemplate(fieldList, 0, "", "");

                                html  = "<h3>Edição do filtro</h3>";
                                html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/filter/" + retFilter.result.info.filter_id + "/action/change/\">";
                                html += "<div class=\"no-tabs fields\"><table><tbody>";
                                html += String.Format(infoTemplate, "Nome", "<input id=\"filter_name\" name=\"filter_name\" placeholder=\"Digite o nome do filtro\" type=\"text\"\" value=\"" + retFilter.result.info.name + "\">");
                                html += "</tbody></table><div class=\"clear-block\"></div></div>";

                                html += "<h3>Parametros de filtragem</h3><div class=\"no-tabs pb10\">";
                                html += "<div id=\"filter_conditions\"><div><div class=\"a-btn blue secondary\" onclick=\"iamfnc.addGroup();\">Inserir grupo</div></div>";
                                html += "<div class=\"filter-groups\">";

                                FilterRule fr = new FilterRule(retFilter.result.info.name);
                                foreach (IAM.GlobalDefs.WebApi.FilterCondition cond in retFilter.result.info.conditions)
                                {
                                    fr.AddCondition(cond.group_id.ToString(), cond.group_selector, cond.field_id, cond.field_name, cond.data_type, cond.text, cond.condition, cond.selector);
                                }

                                for (Int32 g = 0; g < fr.FilterGroups.Count; g++)
                                {
                                    String filters = "";

                                    for (Int32 fIndex = 0; fIndex < fr.FilterGroups[g].FilterRules.Count; fIndex++)
                                    {
                                        String fId = fr.FilterGroups[g].GroupId + "-" + fIndex;

                                        String ft = GetFilterTemplate(fieldList, fr.FilterGroups[g].FilterRules[fIndex].FieldId, fr.FilterGroups[g].FilterRules[fIndex].DataString, fr.FilterGroups[g].FilterRules[fIndex].ConditionType.ToString());

                                        filters += String.Format(ft, fId, fr.FilterGroups[g].GroupId, (fIndex < fr.FilterGroups[g].FilterRules.Count - 1 ? (fr.FilterGroups[g].FilterRules[fIndex].Selector == FilterSelector.AND ? String.Format(filterSelectorTemplate, fId, "", "selected") : String.Format(filterSelectorTemplate, fId, "selected", "")) : ""));
                                    }

                                    html += String.Format(groupTemplate, fr.FilterGroups[g].GroupId, filters, (g < fr.FilterGroups.Count - 1 ? (fr.FilterGroups[g].Selector == FilterSelector.AND ? String.Format(groupSelectorTemplate, fr.FilterGroups[g].GroupId, "", "selected") : String.Format(groupSelectorTemplate, fr.FilterGroups[g].GroupId, "selected", "")) : ""));
                                }

                                html += "</div>";

                                html += "</div><div class=\"clear-block\"></div></div>";
                                html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/filter/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                                contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));

                                contentRet.js = GetFilterJS(groupTemplate, groupSelectorTemplate, filterTemplate, filterSelectorTemplate);

                                break;

                            case "use":
                                if (retFilter != null)
                                {
                                    Int32.TryParse(Request.Form["page"], out page);

                                    if (page < 1)
                                    {
                                        page = 1;
                                    }

                                    if (page == 1)
                                    {
                                        html  = "<h3>Utilização deste perfil</h3>";
                                        html += "<table id=\"users-table\" class=\"sorter\"><thead>";
                                        html += "    <tr>";
                                        html += "        <th class=\"w50 mHide {sorter: false}\"><div class=\"select-all\"></div></th>";
                                        html += "        <th class=\"pointer header headerSortDown\" data-column=\"name\">Recurso x Plugin <div class=\"icomoon\"></div></th>";
                                        html += "        <th class=\"pointer tHide mHide header\" data-column=\"login\">Bloqueio <div class=\"icomoon\"></div></th>";
                                        html += "        <th class=\"pointer tHide mHide header\" data-column=\"login\">Vínculo com perfil <div class=\"icomoon\"></div></th>";
                                        html += "        <th class=\"pointer tHide mHide header\" data-column=\"login\">Desconsiderar registros <div class=\"icomoon\"></div></th>";
                                        html += "        <th class=\"pointer w200 tHide mHide header\" data-column=\"last_login\">Ações <div class=\"icomoon\"></div></th>";
                                        html += "    </tr>";
                                        html += "</thead>";

                                        html += "<tbody>";
                                    }

                                    String trTemplate = "    <tr class=\"user\" data-userid=\"{0}\">";
                                    trTemplate += "            <td class=\"select mHide\"><div class=\"checkbox\"></div></td>";
                                    trTemplate += "            <td class=\"ident10\">{2}</td>";
                                    trTemplate += "            <td class=\"tHide mHide\">{3}</td>";
                                    trTemplate += "            <td class=\"tHide mHide\">{4}</td>";
                                    trTemplate += "            <td class=\"tHide mHide\">{5}</td>";
                                    trTemplate += "            <td class=\"tHide mHide\"><button class=\"a-btn\" onclick=\"window.location = '" + ApplicationVirtualPath + "admin/resource_plugin/{1}/';\">Abrir</button></td>";
                                    trTemplate += "    </tr>";

                                    try
                                    {
                                        rData = SafeTrend.Json.JSON.Serialize2(new
                                        {
                                            jsonrpc    = "1.0",
                                            method     = "filter.use",
                                            parameters = new
                                            {
                                                page_size = pageSize,
                                                page      = page,
                                                filterid  = retFilter.result.info.filter_id
                                            },
                                            id = 1
                                        });

                                        jData = "";
                                        using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                            jData = WebPageAPI.ExecuteLocal(database, this, rData);

                                        if (String.IsNullOrWhiteSpace(jData))
                                        {
                                            throw new Exception("");
                                        }

                                        FilterUseResult ret2 = JSON.Deserialize <FilterUseResult>(jData);
                                        if (ret2 == null)
                                        {
                                            eHtml += String.Format(errorTemplate, MessageResource.GetMessage("filter_not_found"));
                                            //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                                            hasNext = false;
                                        }
                                        else if (ret2.error != null)
                                        {
                                            eHtml += String.Format(errorTemplate, ret2.error.data);
                                            //ret = new WebJsonResponse("", ret2.error.data, 3000, true);
                                            hasNext = false;
                                        }
                                        else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
                                        {
                                            eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("filter_not_found"));
                                            hasNext = false;
                                        }
                                        else
                                        {
                                            foreach (FilterUseData f in ret2.result)
                                            {
                                                html += String.Format(trTemplate, f.filter_id, f.resource_plugin_id, f.resource_plugin_name, f.lock_qty, f.role_qty, f.ignore_qty);
                                            }

                                            if (ret2.result.Count < pageSize)
                                            {
                                                hasNext = false;
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                                        //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                                    }

                                    if (page == 1)
                                    {
                                        html += "</tbody></table>";

                                        html += "<span class=\"empty-results content-loading user-list-loader hide\"></span>";

                                        contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                                    }
                                    else
                                    {
                                        contentRet = new WebJsonResponse("#content-wrapper tbody", (eHtml != "" ? eHtml : html), true);
                                    }

                                    contentRet.js = "$( document ).unbind('end_of_scroll.loader_usr');";

                                    if (hasNext)
                                    {
                                        contentRet.js += "$( document ).bind( 'end_of_scroll.loader_usr', function() { $( document ).unbind('end_of_scroll.loader_usr'); $('.user-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'' }, function(){ $('.user-list-loader').addClass('hide'); } ); });";
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                break;



            case "sidebar":
                if (menu1 != null)
                {
                    html += "<div class=\"sep\"><div class=\"section-nav-header\">";
                    html += "    <div class=\"crumbs\">";
                    html += "        <div class=\"subject subject-color\">";
                    html += "            <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>";
                    html += "        </div>";
                    if (menu2 != null)
                    {
                        html += "        <div class=\"topic topic-color\">";
                        html += "            <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>";
                        html += "        </div>";
                    }
                    html += "    </div>";
                    if (menu3 != null)
                    {
                        html += "    <div class=\"crumbs tutorial-title\">";
                        html += "        <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>";
                        html += "    </div>";
                    }
                    html += "</div></div>";
                }

                if (!newItem)
                {
                    html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/filter/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Novo filtro</button></div>";
                }

                contentRet = new WebJsonResponse("#main aside", html);
                break;

            case "mobilebar":
                break;


            case "buttonbox":
                break;
            }

            if (contentRet != null)
            {
                if (!String.IsNullOrWhiteSpace((String)Request["cid"]))
                {
                    contentRet.callId = (String)Request["cid"];
                }

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Esempio n. 20
0
 public void Add(FilterRule entity)
 {
     _list.Add(entity);
 }
Esempio n. 21
0
        private void Application_DocumentOpened(object sender, Autodesk.Revit.DB.Events.DocumentOpenedEventArgs e)
        {
            Application   app   = sender as Application;
            UIApplication uiApp = new UIApplication(app);
            Document      doc   = uiApp.ActiveUIDocument.Document;

            Utilits.Doc = doc;
            //app.DocumentChanged += new EventHandler<DocumentChangedEventArgs>(OnDocumentChanged);

            //Создание словаря
            MapConnectorsToCircuits dicConnCirc = new MapConnectorsToCircuits();
            //Develop.dicConnectCirc = dicConnCirc;

            //Перебор всех коннекторов для заполнения коннекторов
            //ElementId idConnect = ElementId.InvalidElementId;
            //string idCircuits = "";

            List <ElementId> circuitsId = new List <ElementId>();

            FilteredElementCollector filtConnectors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_TelephoneDevices).WhereElementIsNotElementType();

            foreach (var el in filtConnectors)
            {
                string strIdCirc = el.LookupParameter("ID_Circuits").AsString();
                //Проверка если в коннекторе нет цепей
                if (strIdCirc != null)
                {
                    string[] spl = strIdCirc.Split('?');
                    for (int i = 0; i < spl.Length; i++)
                    {
                        string strid = spl[i];
                        if (Int32.TryParse(strid, out int intId))
                        {
                            ElementId idCirc = new ElementId(Int32.Parse(strid));
                            dicConnCirc.Add(el.Id, idCirc);
                            circuitsId.Add(idCirc);
                        }
                    }
                }
            }

            Develop.dicConnectCirc = dicConnCirc;
            CircUpdater updater = new CircUpdater(uiApp.ActiveAddInId);

            Develop.updater = updater;
            //Регистрация апдатера
            if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId()))
            {
                UpdaterRegistry.RegisterUpdater(updater);
            }

            if (circuitsId.Count != 0)
            {
                //Добавление триггера на электрические цепи

                Element   elem      = doc.GetElement(circuitsId.First());
                Parameter parNumber = elem.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER);
                //Parameter parIdConn = elem.GetParameters("IdConnectors").First();
                UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, circuitsId, Element.GetChangeTypeParameter(parNumber));
                //UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, circuitsId, Element.GetChangeTypeParameter(parIdConn));

                UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, circuitsId, Element.GetChangeTypeElementDeletion());


                updater.dic = dicConnCirc;
            }
            if (filtConnectors.Count() != 0)
            {
                //добавление триггера на коннекторы
                //ElementCategoryFilter filt = new ElementCategoryFilter(BuiltInCategory.OST_TelephoneDevices);
                IList <FilterRule> ruls = new List <FilterRule>();
                FilterRule         rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInParameter.ELEM_FAMILY_PARAM), "Эмуляция потребителя без нагрузки", false);
                ruls.Add(rule);
                rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInCategory.OST_TelephoneDevices), (int)BuiltInCategory.OST_TelephoneDevices);
                ruls.Add(rule);
                ElementParameterFilter filter = new ElementParameterFilter(ruls);
                //FilteredElementCollector collector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_TelephoneDevices).WherePasses(filter);

                //var fs = new FilteredElementCollector(doc).WhereElementIsNotElementType().Where(x => x.Name == "Bunch");
                UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, filter, Element.GetChangeTypeElementDeletion());
            }
        }
Esempio n. 22
0
 public void Delete(FilterRule entity)
 {
     _list.Remove(entity);
 }
Esempio n. 23
0
        /// <summary>
        /// Método privado para processamento do método 'user.resetpassword'
        /// </summary>
        /// <param name="sqlConnection">Conexão com o banco de dados MS-SQL</param>
        /// <param name="parameters">Dicionário (String, Object) contendo todos os parâmetros necessários</param>
        private Dictionary <String, Object> get(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            Dictionary <String, Object> result = new Dictionary <String, Object>();

            if (!parameters.ContainsKey("filterid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter filterid is not defined.", "", null);
                return(null);
            }


            String filter = parameters["filterid"].ToString();

            if (String.IsNullOrWhiteSpace(filter))
            {
                Error(ErrorType.InvalidRequest, "Parameter filterid is not defined.", "", null);
                return(null);
            }

            Int64 filterid = 0;

            try
            {
                filterid = Int64.Parse(filter);
            }
            catch
            {
                Error(ErrorType.InvalidRequest, "Parameter filterid is not a long integer.", "", null);
                return(null);
            }


            DbParameterCollection par = new DbParameterCollection();

            par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId;
            par.Add("@filter_id", typeof(Int64)).Value     = filterid;


            DataTable dtFilter = database.ExecuteDataTable("select f.*, ignore_qty = (select COUNT(distinct i1.filter_id) from resource_plugin_ignore_filter i1 with(nolock) where i1.filter_id = f.id), lock_qty = (select COUNT(distinct l1.filter_id) from resource_plugin_lock_filter l1 with(nolock) where l1.filter_id = f.id), role_qty = (select COUNT(distinct r1.filter_id) from resource_plugin_role_filter r1 with(nolock) where r1.filter_id = f.id)  from filters f with(nolock) where f.enterprise_id = @enterprise_id and f.id = @filter_id", CommandType.Text, par, null);

            if (dtFilter == null)
            {
                Error(ErrorType.InternalError, "", "", null);
                return(null);
            }

            if (dtFilter.Rows.Count == 0)
            {
                Error(ErrorType.InvalidRequest, "Filter not found.", "", null);
                return(null);
            }


            DataRow dr1 = dtFilter.Rows[0];

            Dictionary <string, object> newItem = new Dictionary <string, object>();

            newItem.Add("enterprise_id", dr1["enterprise_id"]);
            newItem.Add("filter_id", dr1["id"]);
            newItem.Add("name", dr1["name"]);
            newItem.Add("ignore_qty", dr1["ignore_qty"]);
            newItem.Add("lock_qty", dr1["lock_qty"]);
            newItem.Add("role_qty", dr1["role_qty"]);
            newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));


            //Lista as condições
            List <Dictionary <String, Object> > conditions = new List <Dictionary <string, object> >();

            FilterRule f   = new FilterRule(dr1["name"].ToString());
            DataTable  dt2 = database.ExecuteDataTable("select f.*, f1.name field_name, f1.data_type from filters_conditions f with(nolock) inner join field f1 with(nolock) on f1.id = f.field_id where f.filter_id = " + dr1["id"] + " order by f.group_id, f1.name");

            if ((dt2 != null) || (dt2.Rows.Count > 0))
            {
                foreach (DataRow dr2 in dt2.Rows)
                {
                    Dictionary <string, object> c1 = new Dictionary <string, object>();
                    c1.Add("group_id", dr2["group_id"].ToString());
                    c1.Add("group_selector", dr2["group_selector"].ToString());
                    c1.Add("field_id", (Int64)dr2["field_id"]);
                    c1.Add("field_name", dr2["field_name"].ToString());
                    c1.Add("data_type", dr2["data_type"].ToString());
                    c1.Add("text", dr2["text"].ToString());
                    c1.Add("condition", dr2["condition"].ToString());
                    c1.Add("selector", dr2["selector"].ToString());

                    conditions.Add(c1);

                    f.AddCondition(dr2["group_id"].ToString(), dr2["group_selector"].ToString(), (Int64)dr2["field_id"], dr2["field_name"].ToString(), dr2["data_type"].ToString(), dr2["text"].ToString(), dr2["condition"].ToString(), dr2["selector"].ToString());
                }
            }

            newItem.Add("conditions_description", f.ToString());
            newItem.Add("conditions", conditions);

            result.Add("info", newItem);


            return(result);
        }
Esempio n. 24
0
        /// <summary>
        /// Convert FilterRule to our custom FilterRuleBuilder which will be displayed in form controls
        /// </summary>
        /// <param name="param">Parameter to which the FilterRule is applied.</param>
        /// <param name="rule">FilterRule to be converted.</param>
        /// <returns>Custom FilterRuleBuilder data converted from FilterRule</returns>
        public static FilterRuleBuilder CreateFilterRuleBuilder(BuiltInParameter param, FilterRule rule)
        {
            // Maybe FilterRule is inverse rule, we need to find its inner rule(FilterValueRule)
            // Note that the rule may be inversed more than once.
            bool       inverted  = false;
            FilterRule innerRule = ReflectToInnerRule(rule, out inverted);

            if (innerRule is FilterStringRule)
            {
                FilterStringRule          strRule   = innerRule as FilterStringRule;
                FilterStringRuleEvaluator evaluator = strRule.GetEvaluator();
                return(new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), strRule.RuleString, strRule.RuleString.ToLower() == strRule.RuleString ? false : true));
            }
            else if (innerRule is FilterDoubleRule)
            {
                FilterDoubleRule           dbRule    = innerRule as FilterDoubleRule;
                FilterNumericRuleEvaluator evaluator = dbRule.GetEvaluator();
                return(new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), dbRule.RuleValue, dbRule.Epsilon));
            }
            else if (innerRule is FilterIntegerRule)
            {
                FilterIntegerRule          intRule   = innerRule as FilterIntegerRule;
                FilterNumericRuleEvaluator evaluator = intRule.GetEvaluator();
                return(new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), intRule.RuleValue));
            }
            else if (innerRule is FilterElementIdRule)
            {
                FilterElementIdRule        idRule    = innerRule as FilterElementIdRule;
                FilterNumericRuleEvaluator evaluator = idRule.GetEvaluator();
                return(new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), idRule.RuleValue));
            }
            //
            // for other rule, not supported yet
            throw new System.NotImplementedException("The filter rule is not recognizable and supported yet!");
        }
Esempio n. 25
0
        public void ToFilterSetExpr_Always_FormatsRulesInOrder(string expectedResult, FilterRuleType[] ruleTypes, bool[] states)
        {
            FilterRule<object>[] filterRules = new FilterRule<object>[ruleTypes.Length];
            for (int i = 0; i < ruleTypes.Length; i++)
                filterRules[i] = new FilterRule<object>(ruleTypes[i],
                    states[i] ? (Filter<object>)new AnyFilter<object>() : new NoneFilter<object>());

            FilterSet<object> filterSet = new FilterSet<object>(filterRules);
            Assert.AreEqual(expectedResult, filterSet.ToFilterSetExpr());
        }
Esempio n. 26
0
        private void InitAccessRightsListView()
        {
            //init ListView control
            listView_AccessRights.Clear();              //clear control
            //create column header for ListView
            listView_AccessRights.Columns.Add("Type", 50, System.Windows.Forms.HorizontalAlignment.Left);
            listView_AccessRights.Columns.Add("Name", 160, System.Windows.Forms.HorizontalAlignment.Left);
            listView_AccessRights.Columns.Add("Readable", 70, System.Windows.Forms.HorizontalAlignment.Left);
            listView_AccessRights.Columns.Add("Writable", 70, System.Windows.Forms.HorizontalAlignment.Left);
            listView_AccessRights.Columns.Add("Deletable", 70, System.Windows.Forms.HorizontalAlignment.Left);
            listView_AccessRights.Columns.Add("Renamable", 70, System.Windows.Forms.HorizontalAlignment.Left);

            if (listView_LockFolders.SelectedItems.Count == 1)
            {
                System.Windows.Forms.ListViewItem item = listView_LockFolders.SelectedItems[0];
                FilterRule filterRule = (FilterRule)item.Tag;

                string[] processRights = filterRule.ProcessRights.Split(new char[] { ';' });
                if (processRights.Length > 0)
                {
                    foreach (string processRight in processRights)
                    {
                        if (processRight.Trim().Length > 0)
                        {
                            string processName = processRight.Substring(0, processRight.IndexOf('!'));
                            uint   accessFlags = uint.Parse(processRight.Substring(processRight.IndexOf('!') + 1));

                            string[] listEntry = new string[listView_AccessRights.Columns.Count];
                            int      index     = 0;
                            listEntry[index++] = "process";
                            listEntry[index++] = processName;
                            listEntry[index++] = ((accessFlags & (uint)FilterAPI.AccessFlag.ALLOW_READ_ACCESS) > 0).ToString();
                            listEntry[index++] = ((accessFlags & (uint)FilterAPI.AccessFlag.ALLOW_WRITE_ACCESS) > 0).ToString();
                            listEntry[index++] = ((accessFlags & (uint)FilterAPI.AccessFlag.ALLOW_FILE_DELETE) > 0).ToString();
                            listEntry[index++] = ((accessFlags & (uint)FilterAPI.AccessFlag.ALLOW_FILE_RENAME) > 0).ToString();

                            ListViewItem listItem = new ListViewItem(listEntry, 0);
                            item.Tag = filterRule;
                            listView_AccessRights.Items.Add(listItem);
                        }
                    }
                }

                string[] userRights = filterRule.UserRights.Split(new char[] { ';' });
                if (userRights.Length > 0)
                {
                    foreach (string userRight in userRights)
                    {
                        if (userRight.Trim().Length > 0)
                        {
                            string userName    = userRight.Substring(0, userRight.IndexOf('!'));
                            uint   accessFlags = uint.Parse(userRight.Substring(userRight.IndexOf('!') + 1));

                            string[] listEntry = new string[listView_AccessRights.Columns.Count];
                            int      index     = 0;
                            listEntry[index++] = "user";
                            listEntry[index++] = userName;
                            listEntry[index++] = ((accessFlags & (uint)FilterAPI.AccessFlag.ALLOW_READ_ACCESS) > 0).ToString();
                            listEntry[index++] = ((accessFlags & (uint)FilterAPI.AccessFlag.ALLOW_WRITE_ACCESS) > 0).ToString();
                            listEntry[index++] = ((accessFlags & (uint)FilterAPI.AccessFlag.ALLOW_FILE_DELETE) > 0).ToString();
                            listEntry[index++] = ((accessFlags & (uint)FilterAPI.AccessFlag.ALLOW_FILE_RENAME) > 0).ToString();

                            ListViewItem listItem = new ListViewItem(listEntry, 0);
                            item.Tag = filterRule;
                            listView_AccessRights.Items.Add(listItem);
                        }
                    }
                }
            }
        }
Esempio n. 27
0
 /// <summary>
 /// Reflect filter rule to its inner rule, the final inner rule is FilterValueRule for this sample
 /// </summary>
 /// <param name="srcRule">Source filter to be checked.</param>
 /// <param name="inverted">Indicates if source rule is inverse rule mapping to its inner rule.
 /// Note that the rule may be inversed more than once, if inverse time is odd(1, 3, 5...), the inverted will be true.
 /// If inverse time is even(0, 2, 4...), the inverted will be false. </param>
 /// <returns>Inner rule of source rule, the inner rule is FilterValueRule type for this sample.</returns>
 public static FilterRule ReflectToInnerRule(FilterRule srcRule, out bool inverted)
 {
     if (srcRule is FilterInverseRule)
     {
         inverted = true;
         FilterRule innerRule = (srcRule as FilterInverseRule).GetInnerRule();
         bool invertedAgain = false;
         FilterRule returnRule = ReflectToInnerRule(innerRule, out invertedAgain);
         if (invertedAgain)
             inverted = false;
         return returnRule;
     }
     else
     {
         inverted = false;
         return srcRule;
     }
 }
Esempio n. 28
0
        public Form_ProcessRights(FilterRule filterRule)
        {
            InitializeComponent();
            currentFilterRule = filterRule;

            StartPosition = FormStartPosition.CenterParent;

            string[] processRightList = filterRule.ProcessRights.ToLower().Split(new char[] { ';' });
            if (processRightList.Length > 0)
            {
                foreach (string processRightStr in processRightList)
                {
                    if (processRightStr.Trim().Length > 0)
                    {
                        string processName = processRightStr.Substring(0, processRightStr.IndexOf('!'));
                        uint   accessFlag  = uint.Parse(processRightStr.Substring(processRightStr.IndexOf('!') + 1));

                        if (!processRights.ContainsKey(processName))
                        {
                            ProcessRight processRight = new ProcessRight();
                            processRight.ProcessName = processName;
                            processRight.ProcessId   = 0;
                            processRight.AccessFlag  = accessFlag;

                            processRights.Add(processName, processRight);
                        }

                        textBox_ProcessName.Text = processName;
                        textBox_AccessFlag.Text  = accessFlag.ToString();
                    }
                }
            }

            string[] processIdList = filterRule.ProcessIdRights.Split(new char[] { ';' });
            if (processIdList.Length > 0)
            {
                foreach (string processIdRightStr in processIdList)
                {
                    if (processIdRightStr.Trim().Length > 0)
                    {
                        string processId  = processIdRightStr.Substring(0, processIdRightStr.IndexOf('!'));
                        uint   accessFlag = uint.Parse(processIdRightStr.Substring(processIdRightStr.IndexOf('!') + 1));

                        if (!processRights.ContainsKey(processId))
                        {
                            ProcessRight processRight = new ProcessRight();
                            processRight.ProcessName = "";
                            processRight.ProcessId   = uint.Parse(processId);
                            processRight.AccessFlag  = accessFlag;

                            processRights.Add(processId, processRight);
                        }

                        textBox_ProcessId.Text  = processId;
                        textBox_AccessFlag.Text = accessFlag.ToString();
                    }
                }
            }

            InitListView();
            SetCheckBoxValue();
        }
Esempio n. 29
0
        /// <summary>
        /// Execute the command
        /// </summary>
        /// <param name="Arguments">Command line arguments</param>
        /// <returns>Exit code</returns>
        public override int Execute(CommandLineArguments Arguments)
        {
            Arguments.ApplyTo(this);

            // Create the build configuration object, and read the settings
            BuildConfiguration BuildConfiguration = new BuildConfiguration();

            XmlConfig.ApplyTo(BuildConfiguration);
            Arguments.ApplyTo(BuildConfiguration);

            // Parse the filter argument
            FileFilter FileFilter = null;

            if (FilterRules.Count > 0)
            {
                FileFilter = new FileFilter(FileFilterType.Exclude);
                foreach (string FilterRule in FilterRules)
                {
                    FileFilter.AddRules(FilterRule.Split(';'));
                }
            }

            // Parse all the target descriptors
            List <TargetDescriptor> TargetDescriptors = TargetDescriptor.ParseCommandLine(Arguments, BuildConfiguration.bUsePrecompiled, BuildConfiguration.bSkipRulesCompile);

            // Generate the compile DB for each target
            using (ISourceFileWorkingSet WorkingSet = new EmptySourceFileWorkingSet())
            {
                // Find the compile commands for each file in the target
                Dictionary <FileReference, string> FileToCommand = new Dictionary <FileReference, string>();
                foreach (TargetDescriptor TargetDescriptor in TargetDescriptors)
                {
                    // Disable PCHs and unity builds for the target
                    TargetDescriptor.AdditionalArguments = TargetDescriptor.AdditionalArguments.Append(new string[] { "-NoPCH", "-DisableUnity" });

                    // Create a makefile for the target
                    UEBuildTarget Target = UEBuildTarget.Create(TargetDescriptor, BuildConfiguration.bSkipRulesCompile, BuildConfiguration.bUsePrecompiled);

                    // Find the location of the compiler
                    VCEnvironment Environment = VCEnvironment.Create(WindowsCompiler.Clang, Target.Platform, Target.Rules.WindowsPlatform.Architecture, null, Target.Rules.WindowsPlatform.WindowsSdkVersion);
                    FileReference ClangPath   = FileReference.Combine(Environment.CompilerDir, "bin", "clang++.exe");

                    // Create all the binaries and modules
                    CppCompileEnvironment GlobalCompileEnvironment = Target.CreateCompileEnvironmentForProjectFiles();
                    foreach (UEBuildBinary Binary in Target.Binaries)
                    {
                        CppCompileEnvironment BinaryCompileEnvironment = Binary.CreateBinaryCompileEnvironment(GlobalCompileEnvironment);
                        foreach (UEBuildModuleCPP Module in Binary.Modules.OfType <UEBuildModuleCPP>())
                        {
                            if (!Module.Rules.bUsePrecompiled)
                            {
                                UEBuildModuleCPP.InputFileCollection InputFileCollection = Module.FindInputFiles(Target.Platform, new Dictionary <DirectoryItem, FileItem[]>());

                                List <FileItem> InputFiles = new List <FileItem>();
                                InputFiles.AddRange(InputFileCollection.CPPFiles);
                                InputFiles.AddRange(InputFileCollection.CCFiles);

                                CppCompileEnvironment ModuleCompileEnvironment = Module.CreateModuleCompileEnvironment(Target.Rules, BinaryCompileEnvironment);

                                StringBuilder CommandBuilder = new StringBuilder();
                                CommandBuilder.AppendFormat("\"{0}\"", ClangPath.FullName);
                                foreach (FileItem ForceIncludeFile in ModuleCompileEnvironment.ForceIncludeFiles)
                                {
                                    CommandBuilder.AppendFormat(" -include \"{0}\"", ForceIncludeFile.FullName);
                                }
                                foreach (string Definition in ModuleCompileEnvironment.Definitions)
                                {
                                    CommandBuilder.AppendFormat(" -D\"{0}\"", Definition);
                                }
                                foreach (DirectoryReference IncludePath in ModuleCompileEnvironment.UserIncludePaths)
                                {
                                    CommandBuilder.AppendFormat(" -I\"{0}\"", IncludePath);
                                }
                                foreach (DirectoryReference IncludePath in ModuleCompileEnvironment.SystemIncludePaths)
                                {
                                    CommandBuilder.AppendFormat(" -I\"{0}\"", IncludePath);
                                }

                                foreach (FileItem InputFile in InputFiles)
                                {
                                    if (FileFilter == null || FileFilter.Matches(InputFile.Location.MakeRelativeTo(UnrealBuildTool.RootDirectory)))
                                    {
                                        FileToCommand[InputFile.Location] = String.Format("{0} \"{1}\"", CommandBuilder, InputFile.FullName);
                                    }
                                }
                            }
                        }
                    }
                }

                // Write the compile database
                FileReference DatabaseFile = FileReference.Combine(UnrealBuildTool.RootDirectory, "compile_commands.json");
                using (JsonWriter Writer = new JsonWriter(DatabaseFile))
                {
                    Writer.WriteArrayStart();
                    foreach (KeyValuePair <FileReference, string> FileCommandPair in FileToCommand.OrderBy(x => x.Key.FullName))
                    {
                        Writer.WriteObjectStart();
                        Writer.WriteValue("file", FileCommandPair.Key.FullName);
                        Writer.WriteValue("command", FileCommandPair.Value);
                        Writer.WriteValue("directory", UnrealBuildTool.EngineSourceDirectory.ToString());
                        Writer.WriteObjectEnd();
                    }
                    Writer.WriteArrayEnd();
                }
            }

            return(0);
        }
Esempio n. 30
0
 public sqlFilter(string _group, FilterRule rule)
 {
     this.groupOp = _group;
     this.rules   = new List <FilterRule>();
     rules.Add(rule);
 }