private static bool TryMatchFieldWithCondition(string fieldName, QueryFilter resultFilter, SearchConditions conditions)
        {
            List<SearchCondition> conditionList;
            if (!conditions.TryGetValue(fieldName, out conditionList))
            {
                return false;
            }

            switch (conditionList.Count)
            {
                case 2: // checking for the between operator
                {
                    var lessThanOrEqualCondition = conditionList.SingleOrDefault(c => c.Operator == ScanOperator.LessThanOrEqual);
                    var greaterThanOrEqualCondition = conditionList.SingleOrDefault(c => c.Operator == ScanOperator.GreaterThanOrEqual);

                    if ((lessThanOrEqualCondition == null) || (greaterThanOrEqualCondition == null))
                    {
                        throw new InvalidOperationException("Multiple conditions for the same field are only supported for the BETWEEN case");
                    }

                    if
                    (
                        (lessThanOrEqualCondition.Values.Length != 1)
                        ||
                        (greaterThanOrEqualCondition.Values.Length != 1)
                    )
                    {
                        return false;
                    }

                    resultFilter.AddCondition(fieldName, QueryOperator.Between, greaterThanOrEqualCondition.Values[0], lessThanOrEqualCondition.Values[0]);
                }
                break;
                case 1:
                {
                    SearchCondition condition = conditionList[0];

                    // here we need to convert operators, as AWS SDK's default conversion is buggy
                    QueryOperator queryOperator;
                    if 
                    (
                        (!TryConvertScanOperatorToQueryOperator(condition.Operator, out queryOperator))
                        ||
                        (condition.Values.Length != 1)
                    )
                    {
                        return false;
                    }

                    resultFilter.AddCondition(fieldName, queryOperator, condition.Values[0]);
                }
                break;
                default:
                    throw new InvalidOperationException(string.Format("Too many conditions for field {0}", fieldName));
            }

            // removing the matched condition
            conditions.Remove(fieldName);

            return true;
        }
Esempio n. 2
0
        public void TestThatFilterWorksWithCombinedSearchUnselectedAndText()
        {
            bool             showUnreadOnly = false;
            bool             ignoreCase     = false;
            bool             combinedSearch = false;
            SearchConditions conditions     = new SearchConditions(null, TEXT_MESSAGE, DATE_TIME.AddDays(1), DATE_TIME.AddDays(1), showUnreadOnly, ignoreCase, combinedSearch);
            var usedCapacity = _smsStorage.GetTotalCapacity() - _smsStorage.GetRemainingCapacity();
            var messages     = _smsStorage.GetAllSMSMessages(conditions);

            Assert.AreNotEqual(0, messages.Count());
            Assert.AreEqual(usedCapacity, messages.Count());

            conditions.Text = TEXT_MESSAGE.ToLower();
            messages        = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreEqual(0, messages.Count());

            conditions.Text = TEXT_MESSAGE + (PHONE_NUMBER1_COUNT - 1);
            messages        = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreEqual(2, messages.Count());

            conditions.Text = TEXT_MESSAGE + PHONE_NUMBER1_COUNT;
            messages        = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreEqual(0, messages.Count());

            conditions.Text       = TEXT_MESSAGE.ToLower();
            conditions.IgnoreCase = true;
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreNotEqual(0, messages.Count());
            Assert.AreEqual(usedCapacity, messages.Count());
        }
Esempio n. 3
0
        public void TestThatFilterWorksWithCombinedSearchUnselectedAndPhoneNumber()
        {
            bool             showUnreadOnly = false;
            bool             ignoreCase     = false;
            bool             combinedSearch = false;
            SearchConditions conditions     = new SearchConditions(null, "", DATE_TIME.AddDays(1), DATE_TIME.AddDays(1), showUnreadOnly, ignoreCase, combinedSearch);
            var messages = _smsStorage.GetAllSMSMessages(conditions);

            Assert.AreEqual(0, messages.Count());

            conditions.PhoneNumber = PHONE_NUMBER2;
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreNotEqual(0, messages.Count());
            Assert.AreEqual(PHONE_NUMBER2_COUNT, messages.Count());

            var usedCapacity = _smsStorage.GetTotalCapacity() - _smsStorage.GetRemainingCapacity();

            conditions.Text = TEXT_MESSAGE;
            messages        = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreNotEqual(0, messages.Count());
            Assert.AreEqual(usedCapacity, messages.Count());

            conditions.StartDateTime = DATE_TIME;
            conditions.EndDateTime   = DATE_TIME;
            conditions.Text          = "";
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreNotEqual(0, messages.Count());
            Assert.AreEqual(usedCapacity, messages.Count());
        }
Esempio n. 4
0
        public void TestThatFilterWorksWithCombinedSearchUnselectedAndShowUnreadOnly()
        {
            bool             showUnreadOnly = false;
            bool             ignoreCase     = false;
            bool             combinedSearch = false;
            SearchConditions conditions     = new SearchConditions(null, "", DATE_TIME, DATE_TIME, showUnreadOnly, ignoreCase, combinedSearch);
            var usedCapacity = _smsStorage.GetTotalCapacity() - _smsStorage.GetRemainingCapacity();
            var messages     = _smsStorage.GetAllSMSMessages(conditions);

            Assert.AreEqual(usedCapacity, messages.Count());

            conditions.StartDateTime = DATE_TIME.AddDays(1);
            conditions.EndDateTime   = DATE_TIME.AddDays(1);

            conditions.ShowUnreadOnly = true;
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreNotEqual(0, messages.Count());
            Assert.AreEqual(usedCapacity, messages.Count());

            messages.ForEach(message => message.IsRead = true);
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreEqual(0, messages.Count());

            _smsStorage.SaveSMSMessage(new SMSMessage(Guid.NewGuid(), PHONE_NUMBER1, TEXT_MESSAGE, DateTime.Now, _smsProvider1));
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreEqual(1, messages.Count());

            conditions.PhoneNumber = PHONE_NUMBER2;
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreEqual(PHONE_NUMBER2_COUNT + 1, messages.Count());
        }
Esempio n. 5
0
        public void TestThatFilterWorksWithCombinedSearchAndTextAndIgnoreCaseAndDateBetween()
        {
            bool             showUnreadOnly = false;
            bool             ignoreCase     = false;
            bool             combinedSearch = true;
            SearchConditions conditions     = new SearchConditions(PHONE_NUMBER1, TEXT_MESSAGE.ToLower(), DATE_TIME, DATE_TIME, showUnreadOnly, ignoreCase, combinedSearch);
            var messages = _smsStorage.GetAllSMSMessages(conditions);

            Assert.AreEqual(0, messages.Count());

            conditions.Text          = TEXT_MESSAGE;
            conditions.IgnoreCase    = true;
            conditions.StartDateTime = DATE_TIME.AddDays(1);
            conditions.EndDateTime   = DATE_TIME.AddDays(1);
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreEqual(0, messages.Count());

            conditions.StartDateTime = DATE_TIME.AddDays(1);
            conditions.EndDateTime   = DATE_TIME.AddDays(-1);
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreEqual(0, messages.Count());


            conditions.StartDateTime = DATE_TIME.AddDays(-1);
            conditions.EndDateTime   = DATE_TIME.AddDays(1);
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreEqual(PHONE_NUMBER1_COUNT, messages.Count());
            messages.ForEach(message => Assert.AreEqual(PHONE_NUMBER1, message.From));
        }
Esempio n. 6
0
        public void TestThatFilterWorksWithCombinedSearchAndShowUnreadOnly()
        {
            bool             showUnreadOnly = true;
            bool             ignoreCase     = false;
            bool             combinedSearch = true;
            SearchConditions conditions     = new SearchConditions(PHONE_NUMBER1, "", DATE_TIME, DATE_TIME, showUnreadOnly, ignoreCase, combinedSearch);

            conditions.PhoneNumber = null;
            var messages = _smsStorage.GetAllSMSMessages(conditions);

            Assert.AreNotEqual(0, messages.Count());
            var usedCapacity = _smsStorage.GetTotalCapacity() - _smsStorage.GetRemainingCapacity();

            Assert.AreEqual(usedCapacity, messages.Count());

            messages.First(message => message.From.Equals(PHONE_NUMBER1)).IsRead = true;
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreNotEqual(0, messages.Count());
            Assert.AreEqual(usedCapacity - 1, messages.Count());

            conditions.PhoneNumber = PHONE_NUMBER1;
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreNotEqual(0, messages.Count());
            Assert.AreEqual(PHONE_NUMBER1_COUNT - 1, messages.Count());

            conditions.PhoneNumber = PHONE_NUMBER2;
            messages = _smsStorage.GetAllSMSMessages(conditions);
            Assert.AreNotEqual(0, messages.Count());
            Assert.AreEqual(PHONE_NUMBER2_COUNT, messages.Count());
        }
        public void GetNumberOfStreaks_WithoutTeamId_AllGames_BTSG()
        {
            //arange
            var conditions = new SearchConditions
            {
                TimeRange = new SearchTimeRange
                {
                    FromDate = new DateTime(2017, 1, 1),
                    ToDate   = new DateTime(2017, 1, 2)
                },
                TeamId         = null,
                BothTeamsScore = true
            };

            var streakCondition = new StreakConditions
            {
                NumberOfItems = 1,
                TotalType     = TotalType.Over
            };

            //act
            var results = searchEngine.GetNumberOfStreaks(conditions, streakCondition);

            //assert
            Assert.AreEqual(2, results);
        }
        public void GetMinimalStreak_WithoutTeamId_AllGames_TotalUnder()
        {
            //arange
            var conditions = new SearchConditions
            {
                TimeRange = new SearchTimeRange
                {
                    FromDate = new DateTime(2017, 1, 1),
                    ToDate   = new DateTime(2017, 1, 2)
                },
                TeamId         = null,
                BothTeamsScore = null,
                GameTotal      = new Total
                {
                    GoalsNumber = 4,
                    TotalType   = TotalType.Under
                }
            };

            //act
            var results = searchEngine.GetMinimalStreak(conditions);

            //assert
            Assert.True(results.Any(g => g.GameId == 5));
            Assert.True(results.Any(g => g.GameId == 6));
            Assert.AreEqual(results.Count, 2);
        }
        public void GetGames_WithoutTeamId_AllGames_BTSG()
        {
            //arange
            var conditions = new SearchConditions
            {
                TimeRange = new SearchTimeRange
                {
                    FromDate = new DateTime(2017, 1, 1),
                    ToDate   = new DateTime(2017, 1, 2)
                },
                TeamId         = null,
                BothTeamsScore = true
            };

            //act
            var results = searchEngine.GetGames(conditions);

            //assert
            Assert.True(results.Any(g => g.GameId == 1));
            Assert.True(results.Any(g => g.GameId == 3));
            Assert.True(results.Any(g => g.GameId == 4));
            Assert.True(results.Any(g => g.GameId == 6));
            Assert.True(results.Any(g => g.GameId == 7));
            Assert.True(results.Any(g => g.GameId == 8));
            Assert.AreEqual(results.Count, 6);
        }
        public void GetGames_ByTeamId_AllGames_TeamTotal()
        {
            //arange
            var conditions = new SearchConditions
            {
                TimeRange = new SearchTimeRange
                {
                    FromDate = new DateTime(2017, 1, 1),
                    ToDate   = new DateTime(2017, 1, 2)
                },
                TeamId         = Teams["Arsenal FC"],
                BothTeamsScore = null,
                TeamTotal      = new TeamTotal
                {
                    Team        = Team.Team1,
                    GoalsNumber = 1,
                    TotalType   = TotalType.Over
                },
                GamePlace = GamePlace.NotDefined
            };

            //act
            var results = searchEngine.GetGames(conditions);

            //assert
            Assert.True(results.Any(g => g.GameId == 1));
            Assert.True(results.Any(g => g.GameId == 6));
            Assert.True(results.Any(g => g.GameId == 7));
            Assert.AreEqual(results.Count, 3);
        }
Esempio n. 11
0
 internal IndexCreator(TableCache parent, string indexKeyInCache, SearchConditions searchConditions)
 {
     _parent = parent;
     _index = new TableIndex(searchConditions);
     _indexKey = searchConditions.Key;
     _indexKeyInCache = indexKeyInCache;
 }
Esempio n. 12
0
        /// <summary>
        /// 查找当前登录用户的邮箱设置
        /// </summary>
        /// <param name="vault"></param>
        /// <returns></returns>
        private static ObjectSearchResults SearchMailConfig(Vault vault)
        {
            try
            {
                var oSearchConditions = new SearchConditions();
                var oSearchCondition1 = new SearchCondition();
                oSearchCondition1.ConditionType = MFConditionType.MFConditionTypeEqual;
                oSearchCondition1.Expression.DataPropertyValuePropertyDef =
                    (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass;
                oSearchCondition1.TypedValue.SetValue(MFDataType.MFDatatypeLookup,
                                                      GetObjectClassId(vault, "ClassMailSettings"));
                oSearchConditions.Add(-1, oSearchCondition1);

                var oSearchCondition2 = new SearchCondition();
                oSearchCondition2.ConditionType = MFConditionType.MFConditionTypeEqual;
                oSearchCondition2.Expression.DataPropertyValuePropertyDef =
                    (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefCreatedBy;
                oSearchCondition2.TypedValue.SetValue(MFDataType.MFDatatypeLookup,
                                                      vault.SessionInfo.UserID);
                oSearchConditions.Add(-1, oSearchCondition2);
                return(vault.ObjectSearchOperations.SearchForObjectsByConditions(oSearchConditions,
                                                                                 MFilesAPI.MFSearchFlags.MFSearchFlagNone,
                                                                                 false));
            }
            catch (Exception ex)
            {
                Common.Logger.Log.ErrorFormat("exception. search object from mfiles error: {0}", ex.Message);
            }

            return(null);
        }
 internal EnyimProjectionIndexCreator(EnyimTableCache parent, string indexKey, string indexKeyInCache, SearchConditions searchConditions)
 {
     this._parent = parent;
     this._index = new TableProjectionIndex(searchConditions);
     this._indexKey = indexKey;
     this._indexKeyInCache = indexKeyInCache;
 }
Esempio n. 14
0
        private static IEnumerable <ObjInfo> SearchObjsByParent(Vault vault, int type, int parentType, int parentId, int level)
        {
            var propIdOwner = vault.ObjectTypeOperations.GetObjectType(parentType).OwnerPropertyDef;

            var sConditons = new SearchConditions();
            //所属对象
            var conditionOwner = new SearchCondition();

            conditionOwner.ConditionType = MFConditionType.MFConditionTypeEqual;
            conditionOwner.Expression.DataPropertyValuePropertyDef = propIdOwner;
            conditionOwner.TypedValue.SetValue(MFDataType.MFDatatypeLookup, parentId);
            sConditons.Add(-1, conditionOwner);
            var res = new List <ObjInfo>();

            try {
                var objs = SearchObjects(vault, type, sConditons);

                for (var i = 1; i <= objs.Count; i++)
                {
                    var obj = objs[i];
                    res.Add(ToObjInfo(obj, level, parentId));
                }
                return((from ObjInfo o in res orderby o.ID select o).ToList());
            }
            catch (Exception ex) {
                throw new Exception("通过父类型搜索失败:" + parentType + " # " + ex.Message);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// 返回通过类型,类别和删除搜索 searchConditions
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="classId"></param>
        /// <param name="deleted"></param>
        /// <returns></returns>
        private static SearchConditions AddBaseConditions(int typeId, int classId, bool deleted)
        {
            var oSearchConditions    = new SearchConditions();
            var oSearchContitionType = new SearchCondition();

            oSearchContitionType.ConditionType = MFConditionType.MFConditionTypeEqual;
            oSearchContitionType.Expression.DataStatusValueType = MFStatusType.MFStatusTypeObjectTypeID;
            oSearchContitionType.TypedValue.SetValue(MFDataType.MFDatatypeLookup, typeId);
            oSearchConditions.Add(-1, oSearchContitionType);

            var oSearchContitionClass = new SearchCondition();

            oSearchContitionClass.ConditionType = MFConditionType.MFConditionTypeEqual;
            oSearchContitionClass.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass;
            oSearchContitionClass.TypedValue.SetValue(MFDataType.MFDatatypeLookup, classId);
            oSearchConditions.Add(-1, oSearchContitionClass);

            var oSearchContidionDeleted = new SearchCondition();

            oSearchContidionDeleted.ConditionType = MFConditionType.MFConditionTypeEqual;
            oSearchContidionDeleted.Expression.DataStatusValueType = MFStatusType.MFStatusTypeDeleted;
            oSearchContidionDeleted.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, deleted);
            oSearchConditions.Add(-1, oSearchContidionDeleted);

            return(oSearchConditions);
        }
Esempio n. 16
0
        public static string GetQuery(this SearchConditions model)
        {
            string cmdtext;

            if (!string.IsNullOrEmpty(model.SearchValue))
            {
                LookupForValueQuery query = new LookupForValueQuery();
                cmdtext = query.GetQueryText(model.SearchValue, model.Search1 ?? "");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(model.Search2))
                {
                    cmdtext = string.Format(
                        @"DECLARE @search nvarchar(40)
set @search = '%{0}%'
SELECT COLUMN_NAME, TABLE_SCHEMA, TABLE_NAME  FROM INFORMATION_SCHEMA.COLUMNS WHERE (COLUMN_NAME LIKE @search or TABLE_NAME like @search) ORDER BY TABLE_NAME",
                        model.Search1);
                }
                else
                {
                    cmdtext = string.Format(
                        @"DECLARE @search1 nvarchar(40), @search2 nvarchar(40)
set @search1 = '%{0}%'
set @search2 = '%{1}%'
SELECT COLUMN_NAME, TABLE_SCHEMA, TABLE_NAME  FROM INFORMATION_SCHEMA.COLUMNS WHERE (COLUMN_NAME LIKE @search1 or TABLE_NAME like @search1) AND (COLUMN_NAME LIKE @search2) ORDER BY TABLE_NAME",
                        model.Search1, model.Search2);
                }
            }
            return(cmdtext);
        }
Esempio n. 17
0
        private static int?GetPartId(Vault vault, int partTypeId, int propIfcId, string ifcGuid)
        {
            var scs = new SearchConditions();
            {
                var sc = new SearchCondition();
                sc.ConditionType = MFConditionType.MFConditionTypeEqual;
                sc.Expression.DataStatusValueType = MFStatusType.MFStatusTypeObjectTypeID;
                sc.TypedValue.SetValueToLookup(new Lookup {
                    Item = partTypeId
                });
                scs.Add(-1, sc);
            }
            {
                var sc = new SearchCondition();
                sc.ConditionType = MFConditionType.MFConditionTypeEqual;
                sc.Expression.DataPropertyValuePropertyDef = propIfcId;
                sc.TypedValue.SetValue(MFDataType.MFDatatypeText, ifcGuid);
                scs.Add(-1, sc);
            }
            var ret = vault.ObjectSearchOperations.SearchForObjectsByConditionsEx(scs,
                                                                                  MFSearchFlags.MFSearchFlagNone, false, 0, 0).ObjectVersions;

            //SimpleLog("result num=" + ret.Count + ",id=" + id + ",objtype:" + ObjPart);
            foreach (ObjectVersion objectVersion in ret)
            {
                //var ao = vault.ObjectOperations.GetMFilesURLForObject(objectVersion.ObjVer.ObjID,
                //    objectVersion.ObjVer.Version, false);
                return(objectVersion.ObjVer.ID);
                //return Json("OK-" + ao, JsonRequestBehavior.AllowGet);
            }
            return(null);
        }
Esempio n. 18
0
        public void TableCache_IndexIsRecreated()
        {
            var conditions = new SearchConditions();

            // creating index

            using (var indexCreator = this.TableCache.StartCreatingIndex(conditions))
            {
                indexCreator.AddEntityToIndex(new EntityKey(Guid.NewGuid(), Guid.NewGuid()), this.ToDocumentConverter(BooksHelper.CreateBook(persistToDynamoDb: false)));
                indexCreator.AddEntityToIndex(new EntityKey(Guid.NewGuid(), Guid.NewGuid()), this.ToDocumentConverter(BooksHelper.CreateBook(persistToDynamoDb: false)));
                indexCreator.AddEntityToIndex(new EntityKey(Guid.NewGuid(), Guid.NewGuid()), this.ToDocumentConverter(BooksHelper.CreateBook(persistToDynamoDb: false)));
            }

            var indexBooks = new Dictionary <EntityKey, Book>();

            indexBooks[new EntityKey(Guid.NewGuid(), Guid.NewGuid())] = BooksHelper.CreateBook(persistToDynamoDb: false);
            indexBooks[new EntityKey(Guid.NewGuid(), Guid.NewGuid())] = BooksHelper.CreateBook(persistToDynamoDb: false);
            indexBooks[new EntityKey(Guid.NewGuid(), Guid.NewGuid())] = BooksHelper.CreateBook(persistToDynamoDb: false);

            // re-creating index
            using (var indexCreator = this.TableCache.StartCreatingIndex(conditions))
            {
                foreach (var book in indexBooks)
                {
                    indexCreator.AddEntityToIndex(book.Key, this.ToDocumentConverter(book.Value));
                }
            }

            // checking, that index contains only the last three books
            var originalBooks = indexBooks.Values.OrderByDescending(b => b.Name);
            var loadedBooks   = this.TableCache.GetEntities(conditions, null, "Name", true).Select(d => (Book)d.ToObject(typeof(Book)));

            this.DeepCompareBookCollections(originalBooks, loadedBooks);
        }
Esempio n. 19
0
        internal static ObjectVersions SearchObjects(Vault vault, int objType, int urlDef, string wrongUrl)
        {
            var scs = new SearchConditions();

            var typeSc = new SearchCondition {
                ConditionType = MFConditionType.MFConditionTypeEqual
            };

            typeSc.Expression.DataStatusValueType = MFStatusType.MFStatusTypeObjectTypeID;
            typeSc.TypedValue.SetValue(MFDataType.MFDatatypeLookup, objType);
            scs.Add(-1, typeSc);

            var urlSc = new SearchCondition {
                ConditionType = MFConditionType.MFConditionTypeContains
            };

            urlSc.Expression.DataPropertyValuePropertyDef = urlDef;
            urlSc.TypedValue.SetValue(MFDataType.MFDatatypeMultiLineText, wrongUrl);
            scs.Add(-1, urlSc);

            var delSc = new SearchCondition {
                ConditionType = MFConditionType.MFConditionTypeEqual
            };

            delSc.Expression.DataStatusValueType = MFStatusType.MFStatusTypeDeleted;
            delSc.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, false);
            scs.Add(-1, delSc);

            return
                (vault.ObjectSearchOperations.SearchForObjectsByConditionsEx(scs, MFSearchFlags.MFSearchFlagNone, false, 0)
                 .GetAsObjectVersions());
        }
Esempio n. 20
0
        /// <summary>
        /// 得到所有联系人
        /// </summary>
        /// <param name="vault"></param>
        /// <param name="onlyIdAndTitle"></param>
        /// <returns></returns>
        public static IEnumerable <Linkman> GetLinkman(Vault vault, bool onlyIdAndTitle = false)
        {
            var linkman     = GetObjectClass(vault, "ClassEmailAddressBook");
            var sConditions = new SearchConditions();

            AddSearchBaseCondition(sConditions, linkman);
            var sResults = vault.ObjectSearchOperations.SearchForObjectsByConditionsEx(sConditions,
                                                                                       MFSearchFlags.MFSearchFlagNone, false, 0, 0);
            var lstLinkmans = new Collection <Linkman>();

            foreach (ObjectVersion objVn in sResults)
            {
                //lnkman.Name = objVn.Title;
                var lnkman = new Linkman {
                    Id = objVn.ObjVer.ID
                };

                if (!onlyIdAndTitle)
                {
                    var properties = vault.ObjectPropertyOperations.GetProperties(objVn.ObjVer, false);
                    LinkmanInfo(vault, lnkman, properties);
                }

                lstLinkmans.Add(lnkman);
            }
            return(lstLinkmans);
        }
Esempio n. 21
0
        public int?GetCount(SearchConditions searchConditions)
        {
            string indexKey = this.GetIndexKey(searchConditions);

            try
            {
                if (!this._redis.HashFieldExistsWithRetries(this.GetIndexListKeyInCache(), indexKey))
                {
                    this.OnMiss.FireSafely();
                    return(null);
                }

                long hashLengthWithVersionField = this._redis.GetHashLengthWithRetries(indexKey);
                if (hashLengthWithVersionField == 0)
                {
                    // zero means that index doesn't exist in the cache, because each index has at least a Version field added
                    throw new RedisCacheException("Index wasn't found in cache");
                }

                long result = hashLengthWithVersionField - 1;

                this.OnHit.FireSafely();
                this.Log("Contents of index ({0}) successfully loaded from cache and number of items returned is {1}", searchConditions.Key, result);
                return((int)result);
            }
            catch (Exception ex)
            {
                this.Log("Failed to get index size ({0}). {1}", searchConditions.Key, ex);
                this.OnMiss.FireSafely();
                return(null);
            }
        }
Esempio n. 22
0
        private void Search_Callback()
        {
            if (DateTo.Date <= DateFrom.Date)
            {
                string yesText   = (string)Application.Current.FindResource("DLG_BUTTON_YES");
                string noText    = (string)Application.Current.FindResource("DLG_BUTTON_NO");
                string titleText = "Hint";
                string infoText  = "The DateFrom should be earlier than DateTo.";

                MessageBoxEx.ShowDialog(DialogType.Warning, titleText, infoText);
                return;
            }

            SearchConditions conditions = new SearchConditions();

            conditions.DateFrom   = DateFrom.Date;
            conditions.DateTo     = DateTo.Date;
            conditions.FoupId     = FoupId.Trim();
            conditions.LotId      = LotId.Trim();
            conditions.WaferId    = WaferId.Trim();
            conditions.RecipeName = RecipeName.Trim();
            conditions.RecipeType = SelectedRecipeType.ToString();
            conditions.ModuleId   = SelectedMod.ToString();

            inEventAggregator.GetEvent <SearchConditionsEvent>().Publish(conditions);
        }
Esempio n. 23
0
        /// <summary>
        /// Uses the helper library to execute a search by display/external id.
        /// </summary>
        static void UseLibrary()
        {
            // Declare variables for our vault connection.
            Vault vault;
            MFilesServerApplication application;

            // The default connection (localhost, tcp, current Windows user) will suffice.
            var connectionDetails = new ConnectionDetails();

            // Connect to the vault.
            connectionDetails.ConnectToVaultAdministrative(
                Program.sampleVaultGuid,
                out vault, out application);

            // Create the basic search conditions collection.
            var searchConditions = new SearchConditions();

            // Add a condition for the display Id.
            searchConditions.AddDisplayIdSearchCondition(Program.customerDisplayId);

            // Search.
            var results = vault.ObjectSearchOperations.SearchForObjectsByConditions(searchConditions,
                                                                                    MFSearchFlags.MFSearchFlagNone, SortResults: false);

            // Output the number of items matching (should be one in each object type, at a maximum).
            Console.WriteLine($"There were {results.Count} objects with the display Id of {Program.customerDisplayId}:");

            Console.WriteLine($"Complete.");

            // Ensure we're disconnected.
            application.Disconnect(vault);
        }
Esempio n. 24
0
        public bool IsPublished()
        {
            Initialize();


            var propDef = _aliases.PdDict[PD.OwnedModel];
            var modelId = _obj.ObjVer.ID;

            var scs = new SearchConditions();

            var delSC = new SearchCondition {
                ConditionType = MFConditionType.MFConditionTypeEqual
            };

            delSC.Expression.DataStatusValueType = MFStatusType.MFStatusTypeDeleted;
            delSC.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, false);
            scs.Add(-1, delSC);

            var modelSC = new SearchCondition {
                ConditionType = MFConditionType.MFConditionTypeEqual
            };

            modelSC.Expression.DataPropertyValuePropertyDef = propDef;
            modelSC.TypedValue.SetValue(MFDataType.MFDatatypeLookup, modelId);
            scs.Add(-1, modelSC);

            var res = _vault.ObjectSearchOperations.SearchForObjectsByConditions(scs, MFSearchFlags.MFSearchFlagNone,
                                                                                 false);

            return(res.Count > 0);
        }
        public static SearchConditions AddPropertyCondition <T>(this SearchConditions search, object value, MFConditionType cType = MFConditionType.MFConditionTypeEqual)
            where T : IMFPropertyDefinition
        {
            int        pd_id     = (int)typeof(T).GetField("id").GetRawConstantValue();
            MFDataType data_type = (MFDataType)typeof(T).GetField("data_type").GetRawConstantValue();

            if (value is IObjVerEx)
            {
                search.AddPropertyCondition(pd_id, cType, data_type, (value as IObjVerEx).objVerEx.ToLookup());
            }
            else if (value is IList)
            {
                Lookups lookups = new Lookups();
                foreach (IObjVerEx objVerEx in (value as IList))
                {
                    if (objVerEx == null)
                    {
                        break;
                    }
                    lookups.Add(-1, objVerEx.objVerEx.ToLookup());
                }
                search.AddPropertyCondition(pd_id, cType, data_type, lookups);
            }
            else
            {
                search.AddPropertyCondition(pd_id, cType, data_type, value);
            }
            return(search);
        }
Esempio n. 26
0
        public static void ExportContents(Vault vault, string exportPath, ExportStructureItems exportStructureItems = null,
                                          SearchConditions searchConditions = null)
        {
            var guid = vault.GetGUID();
            var now  = DateTime.Now;
            var ecj  = new ExportContentJob
            {
                ExportContent                      = false,
                ExportStructureItems               = true,
                IgnoreChangesBefore                = new Timestamp(),
                TargetLocation                     = exportPath,
                UseIgnoreChangesBefore             = false,
                UseSearchConditions                = false,
                IncludeValueListItemsWithStructure = true,
                Flags = MFExportContentFlag.MFExportContentFlagNone,
                IgnoreVersionsBefore = new Timestamp(),
                TargetFile           = Path.Combine(exportPath, string.Format("{0}_{1}_{2}_{3}_{4}_{5}_{6}",
                                                                              guid, now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second), "Index.xml"),
                VaultGUID = guid
            };

            if (exportStructureItems != null && exportStructureItems.Count > 0)
            {
                ecj.StructureItems = exportStructureItems;
            }
            if (searchConditions != null && searchConditions.Count > 0)
            {
                ecj.SearchConditions = searchConditions;
            }

            vault.ManagementOperations.ExportContent(ecj);
        }
Esempio n. 27
0
            public RedisIndex(RedisTableCache parent, string indexKey, SearchConditions searchConditions)
            {
                this._parent           = parent;
                this.IndexKeyInCache   = indexKey;
                this._searchConditions = searchConditions;

                try
                {
                    // (re)registering it in the list of indexes (it should be visible for update operations)
                    this._parent._redis.SetHashWithRetries(this._parent.GetIndexListKeyInCache(), this.IndexKeyInCache, this._searchConditions.ToRedisValue());

                    // asynchronously checking the total number of indexes
                    Task.Run(() => this.TryKeepIndexListSlim(indexKey));

                    // creating an index and marking it as being rebuilt
                    this._parent._redis.CreateNewHashWithRetries(this.IndexKeyInCache, IndexVersionField.Name, IndexVersionField.IsBeingRebuiltValue);

                    this.RedisTransaction = this._parent._redis.BeginTransaction(IndexVersionField.IsBeingRebuiltCondition(this.IndexKeyInCache));
                    this._parent.Log("Index ({0}) was marked as being rebuilt", this._searchConditions.Key);
                }
                catch (Exception ex)
                {
                    this._parent.Log("Failed to start creating index: {0}", ex);

                    // if something goes wrong - dropping the index (but only from the list - we don't want to let parallel update transaction to fail)
                    this._parent._redis.RemoveHashFieldsWithRetries(this._parent.GetIndexListKeyInCache(), this.IndexKeyInCache);
                    throw;
                }
            }
Esempio n. 28
0
        public async ValueTask ExecuteAsync(IConsole console)
        {
            console.GetCancellationToken().Register(() => Log.Information("Cancellation requested"));
            var options = new UpdateOptions {
                Actions  = Actions?.UnJoin('|'),
                Channels = Channels?.UnJoin('|'),
                Parts    = Parts?.UnJoin('|').Select(p => p.ParseEnum <CollectPart>()).ToArray(),
                Tables   = Tables?.UnJoin('|'),
                Results  = Results?.UnJoin('|'),
                Indexes  = Indexes?.UnJoin('|'),
                FullLoad = FullLoad,
                DisableChannelDiscover = DisableChannelDiscover,
                SearchConditions       = SearchConditions?.UnJoin('|').Select(t => {
                    var(index, condition, _) = t.UnJoin(':');
                    return(index, condition);
                }).ToArray(),
                SearchIndexes      = SearchIndexes?.UnJoin('|'),
                UserScrapeInit     = UserScrapeInit,
                UserScrapeTrial    = UserScrapeTrial,
                UserScrapeAccounts = UserScrapeAccounts?.UnJoin('|')
            };

            await PipeCtx.Run((YtUpdater u) => u.Update(options, PipeArg.Inject <CancellationToken>()),
                              new PipeRunOptions { Location = Location, Exclusive = true }, Log, console.GetCancellationToken());
        }
    }
Esempio n. 29
0
        public void TableCache_EmptyIndexIsCreatedAndThenLoaded()
        {
            // some garnish
            this.TableCache.PutSingleLoadedEntity(new EntityKey(0, 0), this.ToDocumentConverter(BooksHelper.CreateBook(persistToDynamoDb: false)));

            // creating an empty index
            var conditions = new SearchConditions();

            using (this.TableCache.StartCreatingIndex(conditions))
            {
            }

            // some garnish
            this.TableCache.PutSingleLoadedEntity(new EntityKey(1, 1), this.ToDocumentConverter(BooksHelper.CreateBook(persistToDynamoDb: false)));


            this._cacheHitCount  = 0;
            this._cacheMissCount = 0;

            Assert.AreEqual(this.TableCache.GetEntities(conditions, null, null, false).Count(), 0);
            Assert.AreNotEqual(this._cacheHitCount, 0);
            Assert.AreEqual(this._cacheMissCount, 0);


            this._cacheHitCount  = 0;
            this._cacheMissCount = 0;

            Assert.AreEqual(this.TableCache.GetEntities(conditions, null, null, false).Count(), 0);
            Assert.AreNotEqual(this._cacheHitCount, 0);
            Assert.AreEqual(this._cacheMissCount, 0);
        }
Esempio n. 30
0
        public void TableCache_IndexIsDiscardedIfEntityIsMissing()
        {
            EntityKey randomBookKey   = null;
            int       bookCount       = 5;
            int       randomBookIndex = new Random().Next(0, bookCount - 1);
            var       conditions      = new SearchConditions();

            using (var indexCreator = this.TableCache.StartCreatingIndex(conditions))
            {
                for (int i = 0; i < bookCount; i++)
                {
                    var bookKey = new EntityKey(Guid.NewGuid(), Guid.NewGuid());
                    indexCreator.AddEntityToIndex(bookKey, this.ToDocumentConverter(BooksHelper.CreateBook(persistToDynamoDb: false)));

                    if (i == randomBookIndex)
                    {
                        randomBookKey = bookKey;
                    }
                }
            }

            // dropping an entity from cache
            this.DropEntityFromCache(randomBookKey);

            Assert.IsNull(this.TableCache.GetEntities(conditions, null, null, false));
            Assert.IsNull(this.TableCache.GetEntities(conditions, null, null, false));
        }
Esempio n. 31
0
        public void TableCache_IndexDoesNotResurrectAfterExpiring()
        {
            var conditions = new SearchConditions();

            conditions.AddCondition("Author", new SearchCondition(ScanOperator.NotEqual, Guid.NewGuid().ToString().ToDynamoDbEntry(typeof(string))));

            // there should be no index yet
            Assert.IsNull(this.TableCache.GetEntities(conditions, null, null, false));

            // creating an index
            using (var indexCreator = this.TableCache.StartCreatingIndex(conditions))
            {
                indexCreator.AddEntityToIndex(new EntityKey(Guid.NewGuid(), Guid.NewGuid()), this.ToDocumentConverter(BooksHelper.CreateBook(persistToDynamoDb: false)));
                indexCreator.AddEntityToIndex(new EntityKey(Guid.NewGuid(), Guid.NewGuid()), this.ToDocumentConverter(BooksHelper.CreateBook(persistToDynamoDb: false)));
            }

            this.DropIndexEntityFromCache(conditions.Key);

            // now updating the same index
            this.TableCache.UpdateCacheAndIndexes
            (
                new Dictionary <EntityKey, Document>
            {
                { new EntityKey(Guid.NewGuid(), Guid.NewGuid()), this.ToDocumentConverter(BooksHelper.CreateBook(persistToDynamoDb: false)) }
            },
                new Dictionary <EntityKey, Document>(),
                new EntityKey[] { }
            );

            // the index should still be dropped
            Assert.IsNull(this.TableCache.GetEntities(conditions, null, null, false));
            Assert.IsNull(this.TableCache.GetEntities(conditions, null, null, false));
        }
Esempio n. 32
0
        public void TableCache_LocalChangesAreNeverOverwrittenWhenCreatingAnIndex()
        {
            var bookKey1 = new EntityKey(1, 1);
            var book1    = BooksHelper.CreateBook(author: "Mark Twain", numPages: 1, persistToDynamoDb: false);
            var bookKey2 = new EntityKey(2, 2);
            var book2    = BooksHelper.CreateBook(author: "Mark Twain", numPages: 2, persistToDynamoDb: false);
            var book21   = BooksHelper.CreateBook(author: "Mark Twain", numPages: 21, persistToDynamoDb: false);
            var bookKey3 = new EntityKey(3, 3);
            var book3    = BooksHelper.CreateBook(author: "Mark Twain", numPages: 3, persistToDynamoDb: false);

            // creating and filling one index with a filter
            var index1 = new SearchConditions();

            index1.AddCondition("Author", new SearchCondition(ScanOperator.Equal, "Mark Twain".ToDynamoDbEntry(typeof(string))));
            using (var indexCreator = this.TableCache.StartCreatingIndex(index1))
            {
                indexCreator.AddEntityToIndex(bookKey1, this.ToDocumentConverter(book1));
                indexCreator.AddEntityToIndex(bookKey2, this.ToDocumentConverter(book2));
            }

            // now start creating another index
            var index2 = new SearchConditions();

            using (var indexCreator = this.TableCache.StartCreatingIndex(index2))
            {
                // loading some garnish
                indexCreator.AddEntityToIndex(new EntityKey(Guid.NewGuid(), Guid.NewGuid()), this.ToDocumentConverter(BooksHelper.CreateBook(author: "Mark Twain", persistToDynamoDb: false)));
                indexCreator.AddEntityToIndex(new EntityKey(Guid.NewGuid(), Guid.NewGuid()), this.ToDocumentConverter(BooksHelper.CreateBook(author: "Mark Twain", persistToDynamoDb: false)));

                // in parallel modifying existing index
                this.TableCache.UpdateCacheAndIndexes
                (
                    new Dictionary <EntityKey, Document>
                {
                    { bookKey3, this.ToDocumentConverter(book3) }
                },
                    new Dictionary <EntityKey, Document>
                {
                    { bookKey2, this.ToDocumentConverter(book21) }
                },
                    new [] { bookKey1 }
                );

                indexCreator.AddEntityToIndex(new EntityKey(Guid.NewGuid(), Guid.NewGuid()), this.ToDocumentConverter(BooksHelper.CreateBook(author: "Mark Twain", persistToDynamoDb: false)));

                // loading the same books to the second index - these should be discarded
                indexCreator.AddEntityToIndex(bookKey2, this.ToDocumentConverter(book2));
                indexCreator.AddEntityToIndex(bookKey1, this.ToDocumentConverter(book1));
            }

            // the second index shouldn't be created
            Assert.IsNull(this.TableCache.GetEntities(index2, null, null, false));

            // the first index should now contain book3 and book21
            var expectedBooks = new[] { book3, book21 };
            var loadedBooks   = this.TableCache.GetEntities(index1, null, "NumPages", false).Select(d => (Book)d.ToObject(typeof(Book)));

            this.DeepCompareBookCollections(expectedBooks, loadedBooks);
        }
Esempio n. 33
0
        public static ObjectSearchResults SearchObjectsByType(Vault vault, int objType, bool deleted = false)
        {
            var scs = new SearchConditions();

            AddBaseConditions(scs, objType, null, deleted);
            return(vault.ObjectSearchOperations.SearchForObjectsByConditions(
                       scs, MFSearchFlags.MFSearchFlagNone, false));
        }
Esempio n. 34
0
 public static IEnumerable<ObjectVersion> GetObjectsByCondition(IVault vault, SearchConditions cond)
 {
     var searchResults = vault.ObjectSearchOperations.SearchForObjectsByConditionsEx(
             SearchConditions: cond,
             SearchFlags: MFSearchFlags.MFSearchFlagReturnLatestVisibleVersion,
             SortResults: false,
             MaxResultCount: 0
             );
     return searchResults.Cast<ObjectVersion>().ToList();
 }
Esempio n. 35
0
        public override IIndexCreator StartCreatingIndex(SearchConditions searchConditions)
        {
            string indexKeyInCache = this.GetIndexKeyInCache(searchConditions.Key, this._hashKeyValue);
            if (indexKeyInCache.Length > MaxKeyLength)
            {
                this.Log("Index key ({0}) is too long", searchConditions.Key);
                return null;
            }

            return base.StartCreatingIndex<EnyimIndexCreator>(indexKeyInCache, searchConditions);
        }
Esempio n. 36
0
        public override IIndexCreator StartCreatingProjectionIndex(SearchConditions searchConditions, IList<string> projectedFields)
        {
            string indexKey = this.GetProjectionIndexKey(searchConditions, projectedFields);
            string indexKeyInCache = this.GetIndexKeyInCache(indexKey, this._hashKeyValue);
            if (indexKeyInCache.Length > MaxKeyLength)
            {
                this.Log("Index key ({0}) is too long", searchConditions.Key);
                return null;
            }

            return base.StartCreatingProjectionIndex<EnyimProjectionIndexCreator>(indexKey, indexKeyInCache, searchConditions);
        }
Esempio n. 37
0
        /// <summary>
        /// Gets from cache or compiles a predicate for the specified list of conditions and the specified entity type
        /// </summary>
        private static Func<Document, bool> GetPredicate(SearchConditions conditions, Type entityType)
        {
            // if no conditions specified - then just returning a predicate, that always returns true
            if (conditions.Count == 0)
            {
                return doc => true;                
            }

            var predicatesDic = PredicatesDictionary.GetOrAdd(entityType, new ConcurrentDictionary<string, Func<Document, bool>>());
            var result = predicatesDic.GetOrAdd(conditions.Key, _ => CreatePredicate(conditions, entityType));

            TryKeepPredicatesDictionarySlim(predicatesDic);

            return result;
        }
Esempio n. 38
0
        public IEnumerable<Document> GetEntities(SearchConditions searchConditions, IEnumerable<string> projectedFields, string orderByFieldName, bool orderByDesc)
        {
            // first trying to find a full index
            string indexKey = searchConditions.Key;
            var index = this.TryLoadHealthyIndex(indexKey);

            Document[] result = null;

            // if no full index exist
            if (index == null)
            {
                if (projectedFields != null)
                {
                    // then there still might be a projection index
                    indexKey = this.GetProjectionIndexKey(searchConditions, projectedFields);
                    result = this.TryLoadProjectionIndexEntities(indexKey);
                }
            }
            else
            {
                result = this.TryLoadIndexEntities(index, indexKey);
            }

            // if we failed to load both full and projection index
            if (result == null)
            {
                this.OnMiss.FireSafely();
                return null;
            }

            this.OnHit.FireSafely();
            this.Log("Index ({0}) with {1} items successfully loaded from cache", indexKey, result.Length);

            if (string.IsNullOrEmpty(orderByFieldName))
            {
                return result;
            }

            // creating a comparer to sort the results
            var comparer = PrimitiveComparer.GetComparer(this._tableEntityType, orderByFieldName);

            return orderByDesc
                ?
                result.OrderByDescending(doc => doc[orderByFieldName].AsPrimitive(), comparer)
                :
                result.OrderBy(doc => doc[orderByFieldName].AsPrimitive(), comparer)
            ;
        }
Esempio n. 39
0
 internal EnyimIndexCreator(EnyimTableCache parent, string indexKeyInCache, SearchConditions searchConditions)
     : base(parent, indexKeyInCache, searchConditions)
 {
 }
        /// <summary>
        /// TODO: This method needs to be moved from here as it makes calls to schema specific methods.
        /// </summary>
        /// <param name="callingUrl"></param>
        /// <param name="domainId"></param>
        /// <param name="conditions"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public SearchMapResult SearchMap(string callingUrl, Guid domainId, Guid rootMapUid, SearchConditions conditions, int pageNumber, int pageSize)
        {
            if (pageNumber == 0)
            {
                pageNumber = 1;
            }

            if (pageSize == 0)
            {
                pageSize = 5;
            }

            using (GlymaNSApp.NodeServiceClient nodeServiceClient = new GlymaNSApp.NodeServiceClient(callingUrl))
            {
                using (WebAppSPGlymaSession glymaSession = new WebAppSPGlymaSession(callingUrl, domainId, rootMapUid, SPGlymaRightFactory.Instance.MapReadRight))
                {
                    GlymaSessionConfiguration configuration = glymaSession.ExportGlymaSession();

                    return nodeServiceClient.SearchMap(configuration, domainId, rootMapUid, conditions, pageNumber, pageSize);
                }
            }
        }
 /// <summary>
 /// TODO: This method needs to be moved from here as it makes calls to schema specific methods.
 /// </summary>
 /// <param name="callingUrl"></param>
 /// <param name="domainId"></param>
 /// <param name="conditions"></param>
 /// <param name="pageNumber"></param>
 /// <param name="pageSize"></param>
 /// <returns></returns>
 public SearchMapResult SearchMap(string callingUrl, Guid domainId, Guid rootMapUid, SearchConditions conditions, int pageNumber = 1, int pageSize = 5)
 {
     using (GlymaNSApp.NodeServiceClient nodeServiceClient = new GlymaNSApp.NodeServiceClient(callingUrl))
     {
         return nodeServiceClient.SearchMap(callingUrl, domainId, rootMapUid, conditions, pageNumber, pageSize);
     }
 }
Esempio n. 42
0
 public IEnumerable<Document> GetEntities(SearchConditions searchConditions, IEnumerable<string> projectedFields, string orderByFieldName, bool orderByDesc)
 {
     return null;
 }
Esempio n. 43
0
 public int? GetCount(SearchConditions searchConditions)
 {
     return null;
 }
Esempio n. 44
0
 public IIndexCreator StartCreatingIndex(SearchConditions searchConditions)
 {
     return null;
 }
Esempio n. 45
0
 public IIndexCreator StartCreatingProjectionIndex(SearchConditions searchConditions, IList<string> projectedFields)
 {
     return null;
 }
Esempio n. 46
0
 /// <summary>
 /// Composes a key for a projection index
 /// </summary>
 private string GetProjectionIndexKey(SearchConditions searchConditions, IEnumerable<string> projectedFields)
 {
     return ProjectionIndexKeyPrefix + projectedFields.Aggregate((i, s) => i + "," + s) + "; " + searchConditions.Key;
 }
Esempio n. 47
0
 public IIndexCreator StartCreatingIndex(SearchConditions searchConditions)
 {
     throw new NotImplementedException();
 }
Esempio n. 48
0
        public int? GetCount(SearchConditions searchConditions)
        {
            var index = this.TryLoadHealthyIndex(searchConditions.Key);

            if (index == null)
            {
                this.OnMiss.FireSafely();
                return null;
            }

            this.OnHit.FireSafely();
            this.Log("Contents of index ({0}) successfully loaded from cache and number of items returned is {1}", searchConditions.Key, index.Count);

            return index.Count;
        }
Esempio n. 49
0
 public TableIndex(SearchConditions conditions)
 {
     this.Index = new HashSet<EntityKey>();
     this._conditions = conditions;
     this.IsBeingRebuilt = true;
 }
 /// <summary>
 /// Tries to fit all remaining SearchConditions to QueryFilter
 /// </summary>
 private static bool TryPutRemainingConditionsToQueryFilter(QueryFilter resultFilter, SearchConditions conditions)
 {
     return conditions
         .Keys.ToArray()
         .All(fieldName => TryMatchFieldWithCondition(fieldName, resultFilter, conditions));
 }
Esempio n. 51
0
        /// <summary>
        /// Creates a lambda expression, that checks a Document to satisfy the list of conditions.
        /// Then compiles it and returns a predicate.
        /// </summary>
        private static Func<Document, bool> CreatePredicate(SearchConditions conditions, Type entityType)
        {
            // parameter, that represents input Document
            var docParameter = Expression.Parameter(typeof(Document));

            Expression predicateExp = null;

            foreach (var condition in conditions.Flatten())
            {
                string fieldName = condition.Item1;

                var fieldPropertyInfo = entityType.GetProperty(fieldName);
                if (fieldPropertyInfo == null)
                {
                    throw new InvalidOperationException(string.Format("An entity type {0} doesn't contain a property with name {1}, which was specified in search condition", entityType.Name, fieldName));
                }

                var fieldType = fieldPropertyInfo.PropertyType;
                var fieldValues = condition.Item2.Values;

                // operation of getting a Document property value by it's name 
                Expression getFieldExp = Expression.Property(docParameter, "Item", Expression.Constant(fieldName));

                if (fieldType.BaseType == typeof (Enum))
                {
                    // need to convert enums to ints
                    getFieldExp = Expression.Convert(getFieldExp, typeof (int));
                }

                // operation of converting the property to fieldType
                var operand1 = Expression.Convert(getFieldExp, fieldType);

                Expression conditionExp;
                if (condition.Item2.Operator == ScanOperator.In)
                {
                    // special support for IN operator

                    var valueList = new ArrayList();
                    foreach (var fieldValue in fieldValues)
                    {
                        valueList.Add(fieldValue.ToObject(fieldType));
                    }

                    conditionExp = Expression.Call
                        (
                            Expression.Constant(valueList), 
                            "Contains", 
                            new Type[0], 
                            Expression.Convert(operand1, typeof(object))
                        );
                }
                else
                {
                    Expression valueExp = Expression.Constant(fieldValues[0]);

                    if (fieldType.BaseType == typeof(Enum))
                    {
                        // need to convert enums to ints
                        valueExp = Expression.Convert(valueExp, typeof(int));
                    }

                    // operation of converting the fieldValue to fieldType
                    var operand2 = Expression.Convert(valueExp, fieldType);

                    // now getting a predicate for current field
                    conditionExp = ScanOperatorToExpression(condition.Item2.Operator, operand1, operand2);
                }

                // attaching it to other predicates
                predicateExp = predicateExp == null ? conditionExp : Expression.AndAlso(predicateExp, conditionExp);
            }

            Debug.Assert(predicateExp != null);
            // compiling the lambda into a predicate
            return (Func<Document, bool>)Expression.Lambda( predicateExp, docParameter ).Compile();
        }
        /// <summary>
        /// Tries to make up a batch get operation from SearchConditions
        /// </summary>
        private static DocumentBatchGet GetBatchGetOperationForSearchConditions(Table tableDefinition, SearchConditions conditions, string keyFieldName, Primitive hashKeyValue)
        {
            // there should be only one IN operator for key field
            if
            (!(
                (conditions.Count == 1)
                &&
                (conditions.Keys.First() == keyFieldName)
            ))
            {
                return null;
            }

            var conditionList = conditions.Values.First();
            if
            (!(
                (conditionList.Count == 1)
                &&
                (conditionList.First().Operator == ScanOperator.In)
            ))
            {
                return null;
            }

            var result = tableDefinition.CreateBatchGet();
            foreach (var value in conditionList.First().Values)
            {
                if (hashKeyValue == null)
                {
                    result.AddKey((Primitive)value);
                }
                else
                {
                    result.AddKey(hashKeyValue, (Primitive)value);
                }
            }
            return result;
        }
 public TableProjectionIndex(SearchConditions conditions) : base(conditions)
 {
 }
Esempio n. 54
0
 public IEnumerable<Document> GetEntities(SearchConditions searchConditions, string orderByFieldName, bool orderByDesc)
 {
     throw new NotImplementedException();
 }
Esempio n. 55
0
        public IIndexCreator StartCreatingProjectionIndex(SearchConditions searchConditions, IList<string> projectedFields)
        {
            string indexKey = this.GetProjectionIndexKey(searchConditions, projectedFields);
            string indexKeyInCache = this.GetIndexKeyInCache(indexKey, this._hashKeyValue);
            if (indexKeyInCache.Length > MaxKeyLength)
            {
                this.Log("Index key ({0}) is too long", searchConditions.Key);
                return null;
            }

            var creator = new EnyimProjectionIndexCreator(this, indexKey, indexKeyInCache, searchConditions);

            if (!creator.StartCreatingIndex())
            {
                this.Log("Failed to start creating projection index ({0})", indexKey);
                return null;
            }

            return creator;
        }
Esempio n. 56
0
        /// <summary>
        /// TODO: This method needs to be moved from here as it makes calls to schema specific methods.
        /// </summary>
        /// <param name="callingUrl"></param>
        /// <param name="domainId"></param>
        /// <param name="conditions"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public SearchMapResult SearchMap(GlymaSessionConfiguration configuration, Guid domainId, Guid rootMapUid, SearchConditions conditions, int pageNumber, int pageSize)
        {
            if (pageNumber == 0)
            {
                pageNumber = 1;
            }

            if (pageSize == 0)
            {
                pageSize = 5;
            }

            using (IGlymaSession glymaSession = new SvcAppSPGlymaSession(configuration))
            {
                return Base.SearchMap(glymaSession, domainId, rootMapUid, conditions, pageNumber, pageSize);
            }
        }
Esempio n. 57
0
 public int? GetCount(SearchConditions searchConditions)
 {
     throw new NotImplementedException();
 }
Esempio n. 58
-1
        private ObjectSearchResults Find(SearchCondition searchCondition)
        {
            var vault = this.VaultService.Vault.Value;

              var searchConditions = new SearchConditions();
              searchConditions.Add(-1, searchCondition);

              var objectSearchResults = vault.ObjectSearchOperations.SearchForObjectsByConditionsEx(
            searchConditions,
            MFSearchFlags.MFSearchFlagLookInAllVersions | MFSearchFlags.MFSearchFlagDisableRelevancyRanking,
            false,
            MaxResultCount: 100000,
            SearchTimeoutInSeconds: Int32.MaxValue);

              return objectSearchResults;
        }