public CommandEnvelopeRouteOnRequestCostcentreRepository(string connectionString)
            : base(connectionString)
        {
            _commandEnvelopeRouteOnRequestCostcentreCollection = CurrentMongoDB.GetCollection<CommandEnvelopeRouteOnRequestCostcentre>(_commandEnvelopeRouteOnRequestCostcentreCollectionName);
            _commandEnvelopeRouteOnRequestCostcentreCollection.EnsureIndex(IndexKeys<CommandEnvelopeRouteOnRequestCostcentre>.Ascending(n => n.Id), IndexOptions.SetUnique(true));
            _commandEnvelopeRouteOnRequestCostcentreCollection.EnsureIndex(IndexKeys<CommandEnvelopeRouteOnRequestCostcentre>.Ascending(n => n.EnvelopeId));
            _commandEnvelopeRouteOnRequestCostcentreCollection.EnsureIndex(IndexKeys<CommandEnvelopeRouteOnRequestCostcentre>.Ascending(n => n.CostCentreId));
            _commandEnvelopeRouteOnRequestCostcentreCollection.EnsureIndex(IndexKeys<CommandEnvelopeRouteOnRequestCostcentre>.Ascending(n => n.EnvelopeRoutePriority));
            _commandEnvelopeRouteOnRequestCostcentreCollection.EnsureIndex(IndexKeys<CommandEnvelopeRouteOnRequestCostcentre>.Ascending(n => n.EnvelopeArrivalAtServerTick));
            _commandEnvelopeRouteOnRequestCostcentreCollection.EnsureIndex(IndexKeys<CommandEnvelopeRouteOnRequestCostcentre>.Ascending(n => n.DocumentType));

            _commandEnvelopeRoutingStatusCollection = CurrentMongoDB.GetCollection<CommandEnvelopeRoutingStatus>(_commandEnvelopeRoutingStatusCollectionName);
            _commandEnvelopeRoutingStatusCollection.EnsureIndex(IndexKeys<CommandEnvelopeRoutingStatus>.Ascending(n => n.Id), IndexOptions.SetUnique(true));
            _commandEnvelopeRoutingStatusCollection.EnsureIndex(IndexKeys<CommandEnvelopeRoutingStatus>.Ascending(n => n.DestinationCostCentreApplicationId));
            _commandEnvelopeRoutingStatusCollection.EnsureIndex(IndexKeys<CommandEnvelopeRoutingStatus>.Ascending(n => n.EnvelopeDeliveredAtServerTick));

            _commandEnvelopeProcessingAuditCollection = CurrentMongoDB.GetCollection<CommandEnvelopeProcessingAudit>(_commandEnvelopeProcessingAuditCollectionName);
            _commandEnvelopeProcessingAuditCollection.EnsureIndex(IndexKeys<CommandEnvelopeProcessingAudit>.Ascending(n => n.Id), IndexOptions.SetUnique(true));
            _commandEnvelopeProcessingAuditCollection.EnsureIndex(IndexKeys<CommandEnvelopeProcessingAudit>.Ascending(n => n.GeneratedByCostCentreApplicationId));
            _commandEnvelopeProcessingAuditCollection.EnsureIndex(IndexKeys<CommandEnvelopeProcessingAudit>.Ascending(n => n.RecipientCostCentreId));
            _commandEnvelopeProcessingAuditCollection.EnsureIndex(IndexKeys<CommandEnvelopeProcessingAudit>.Ascending(n => n.DocumentId));
            _commandEnvelopeProcessingAuditCollection.EnsureIndex(IndexKeys<CommandEnvelopeProcessingAudit>.Ascending(n => n.Status));
            _commandEnvelopeProcessingAuditCollection.EnsureIndex(IndexKeys<CommandProcessingAudit>.Ascending(n => n.ParentDocumentId));
            _commandEnvelopeProcessingAuditCollection.EnsureIndex(IndexKeys<CommandProcessingAudit>.Ascending(n => n.DateInserted));

            _CommandEnvelopeRoutingTrackerCollection = CurrentMongoDB.GetCollection<CommandEnvelopeRoutingTracker>(_commandEnvelopeRoutingTrackerCollectionName);

            _CommandEnvelopeRoutingTrackerCollection.CreateIndex(IndexKeys<CommandEnvelopeRoutingTracker>.Ascending(n => n.Id), IndexOptions.SetUnique(true));
            _CommandEnvelopeRoutingTrackerCollection.CreateIndex(IndexKeys<CommandEnvelopeRoutingTracker>.Ascending(n => n.EnvelopeArrivalAtServerTick));
            _CommandEnvelopeRoutingTrackerCollection.CreateIndex(IndexKeys<CommandEnvelopeRoutingTracker>.Ascending(n => n.EnvelopeId));
        }
        protected override void InitializeCollection(MongoCollection <DayStackStats> collection)
        {
            base.InitializeCollection(collection);

            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.ProjectId));
            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.ErrorStackId));
        }
예제 #3
0
        public override void Initialize(string name, NameValueCollection config)
        {
            ApplicationName                      = config["applicationName"] ?? HostingEnvironment.ApplicationVirtualPath;
            enablePasswordReset                  = Boolean.Parse(config["enablePasswordReset"] ?? "true");
            enablePasswordRetrieval              = Boolean.Parse(config["enablePasswordRetrieval"] ?? "false");
            maxInvalidPasswordAttempts           = Int32.Parse(config["maxInvalidPasswordAttempts"] ?? "5");
            minRequiredNonAlphanumericCharacters = Int32.Parse(config["minRequiredNonAlphanumericCharacters"] ?? "1");
            minRequiredPasswordLength            = Int32.Parse(config["minRequiredPasswordLength"] ?? "7");
            passwordAttemptWindow                = Int32.Parse(config["passwordAttemptWindow"] ?? "10");
            passwordFormat = (MembershipPasswordFormat)Enum.Parse(typeof(MembershipPasswordFormat), config["passwordFormat"] ?? "Hashed");
            passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"] ?? string.Empty;
            requiresQuestionAndAnswer         = Boolean.Parse(config["requiresQuestionAndAnswer"] ?? "false");
            requiresUniqueEmail = Boolean.Parse(config["requiresUniqueEmail"] ?? "true");

            if (PasswordFormat == MembershipPasswordFormat.Hashed && EnablePasswordRetrieval)
            {
                throw new ProviderException("Configured settings are invalid: Hashed passwords cannot be retrieved. Either set the password format to different type, or set enablePasswordRetrieval to false.");
            }

            mongoCollection = MongoServer.Create(config["connectionString"] ?? "mongodb://localhost")
                              .GetDatabase(config["database"] ?? "ASPNETDB")
                              .GetCollection(config["collection"] ?? "Users");

            mongoCollection.EnsureIndex("ApplicationName");
            mongoCollection.EnsureIndex("ApplicationName", "Email");
            mongoCollection.EnsureIndex("ApplicationName", "Username");

            base.Initialize(name, config);
        }
예제 #4
0
        public IEnumerable <LogItemDto> Logs(string query, TimeSpan dateRange)
        {
            logs.EnsureIndex("TimeStamp", "Type", "Message");
            logs.EnsureIndex("TimeStamp", "Message");
            logs.EnsureIndex("TimeStamp", "Object");

            var result = new List <LogItemDto>();

            var         queryMain       = new QueryDocument(BsonDocument.Parse(query));
            var         queryDateFilter = Query.GT("TimeStamp", new BsonDateTime(DateTime.Now.Date.Subtract(dateRange)));
            IMongoQuery q = Query.And(queryMain, queryDateFilter);

            foreach (BsonDocument i in logs
                     .FindAs <BsonDocument>(q)
                     .SetLimit(250)
                     .SetSortOrder(new SortByDocument(new
            {
                TimeStamp = -1
            }.ToBsonDocument())))
            {
                result.Add(new LogItemDto
                {
                    Id        = i["_id"].AsObjectId,
                    Message   = i["Message"].AsString,
                    Type      = i["Type"].AsString,
                    TimeStamp = i["TimeStamp"].AsDateTime,
                    Object    = GetObject(i),
                    ThreadId  = int.Parse(i["ThreadId"].AsString)
                });
            }

            return(result);
        }
        protected override void InitializeCollection(MongoCollection <ProjectHook> collection)
        {
            base.InitializeCollection(collection);

            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.ProjectId));
            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.Url));
        }
예제 #6
0
        protected override void InitializeCollection(MongoCollection <Organization> collection)
        {
            base.InitializeCollection(collection);

            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.Invites_Token));
            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.Invites_EmailAddress));
            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.StripeCustomerId), IndexOptions.SetUnique(true).SetSparse(true));
        }
예제 #7
0
        protected override void InitializeCollection(MongoCollection <ErrorStack> collection)
        {
            base.InitializeCollection(collection);

            collection.EnsureIndex(M.IndexKeys.Ascending(FieldNames.ProjectId, FieldNames.SignatureHash), M.IndexOptions.SetUnique(true));
            collection.EnsureIndex(M.IndexKeys.Descending(FieldNames.LastOccurrence));
            collection.EnsureIndex(M.IndexKeys.Descending(FieldNames.IsHidden, FieldNames.DateFixed));
        }
예제 #8
0
        protected override void InitializeCollection(MongoCollection <User> collection)
        {
            base.InitializeCollection(collection);

            collection.EnsureIndex(IndexKeys <User> .Ascending(u => u.OrganizationIds));
            collection.EnsureIndex(IndexKeys <User> .Ascending(u => u.EmailAddress), IndexOptions.SetUnique(true));
            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.OAuthAccounts_Provider, FieldNames.OAuthAccounts_ProviderUserId), IndexOptions.SetUnique(true).SetSparse(true));
            collection.EnsureIndex(IndexKeys <User> .Ascending(u => u.Roles));
        }
예제 #9
0
        public MongoDataProvider(string connectionString) : base(connectionString)
        {
            var databaseName = MongoUrl.Create(connectionString).DatabaseName;
            var server       = MongoServer.Create(connectionString);
            var database     = server.GetDatabase(databaseName);

            _items = database.GetCollection <ItemDto>("items");
            _items.EnsureIndex(IndexKeys.Ascending(new[] { "ParentId" }));
            _items.EnsureIndex(IndexKeys.Ascending(new[] { "TemplateId" }));
        }
예제 #10
0
        protected override void InitializeCollection(MongoCollection <Error> collection)
        {
            base.InitializeCollection(collection);

            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.ProjectId));
            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.ErrorStackId));
            collection.EnsureIndex(IndexKeys.Descending(FieldNames.ProjectId, FieldNames.OccurrenceDate_UTC));
            collection.EnsureIndex(IndexKeys.Descending(FieldNames.RequestInfo_ClientIpAddress, FieldNames.OccurrenceDate_UTC));
            collection.EnsureIndex(IndexKeys.Descending(FieldNames.ErrorStackId, FieldNames.OccurrenceDate_UTC));
        }
예제 #11
0
        public static void CreateIndex(this Schema schema)
        {
            MongoCollection <BsonDocument> collection = schema.GetCollection();

            collection.EnsureIndex("FolderName", "UUID", "Published", "UtcCreationDate");
            collection.EnsureIndex("FolderName", "UserKey", "Published", "UtcCreationDate");
            collection.EnsureIndex("FolderName", "UUID", "Published", "Sequence");
            collection.EnsureIndex("FolderName", "UserKey", "Published", "Sequence");
            collection.EnsureIndex("FolderName", "ParentFolder", "ParentUUID", "Published");
        }
예제 #12
0
        public MongoDbBlackBox(string connectionstring, string eventstorename)
        {
            var mdbClient = new MongoClient(connectionstring);
            var mdbServer = mdbClient.GetServer();
            var mdb       = mdbServer.GetDatabase(eventstorename);

            _eventCol = mdb.GetCollection("Events");
            _eventCol.EnsureIndex(new IndexKeysBuilder().Ascending("sequencenumber"));
            _eventCol.EnsureIndex(new IndexKeysBuilder().Ascending("name"));
            _eventCol.EnsureIndex(new IndexKeysBuilder().Ascending("context"));
        }
예제 #13
0
        public MongoDataProvider(string connectionString)
            : base(connectionString)
        {
            var databaseName = MongoUrl.Create(connectionString).DatabaseName;
            var server = MongoServer.Create(connectionString);
            var database = server.GetDatabase(databaseName);

            _items = database.GetCollection<ItemDto>("items");
            _items.EnsureIndex(IndexKeys.Ascending(new[] {"ParentId"}));
            _items.EnsureIndex(IndexKeys.Ascending(new[] {"TemplateId"}));
        }
예제 #14
0
        public MongoDbBlackBox(string connectionstring, string eventstorename)
        {
            var mdbClient = new MongoClient(connectionstring);
            var mdbServer = mdbClient.GetServer();
            var mdb = mdbServer.GetDatabase(eventstorename);

            _eventCol = mdb.GetCollection("Events");
            _eventCol.EnsureIndex(new IndexKeysBuilder().Ascending("sequencenumber"));
            _eventCol.EnsureIndex(new IndexKeysBuilder().Ascending("name"));
            _eventCol.EnsureIndex(new IndexKeysBuilder().Ascending("context"));
        }
예제 #15
0
        public CommandRoutingOnRequestMongoRepository(string connectionStringM1)
            : base(connectionStringM1)
        {
            _CommandRouteOnRequestCollection = CurrentMongoDB.GetCollection<CommandRouteOnRequest>(_commandRouteOnRequestCollectionName);
            _CommandRouteOnRequestCostcentreCollection = CurrentMongoDB.GetCollection<CommandRouteOnRequestCostcentre>(_commandRouteOnRequestCostcentreCollectionName);
            _commandRoutingStatusCollection = CurrentMongoDB.GetCollection<CommandRoutingStatus>(_commandCommandRoutingStatusCollectionName);
            _counterHelper = new IdCounterHelper(connectionStringM1);

            _CommandRouteOnRequestCollection.EnsureIndex(IndexKeys<CommandRouteOnRequest>.Ascending(n => n.CommandId), IndexOptions.SetUnique(true));
            _CommandRouteOnRequestCollection.EnsureIndex(IndexKeys<CommandRouteOnRequest>.Ascending(n => n.DocumentId));
            _CommandRouteOnRequestCostcentreCollection.EnsureIndex(IndexKeys<CommandRouteOnRequestCostcentre>.Ascending(n => n.CommandRouteOnRequestId).Ascending(n => n.CostCentreId), IndexOptions.SetUnique(true));
            _commandRoutingStatusCollection.EnsureIndex(IndexKeys<CommandRoutingStatus>.Ascending(n => n.CommandRouteOnRequestId).Ascending(n => n.DestinationCostCentreApplicationId), IndexOptions.SetUnique(true));
            _commandRoutingStatusCollection.EnsureIndex(IndexKeys<CommandRoutingStatus>.Ascending(n => n.CommandId).Ascending(n => n.DestinationCostCentreApplicationId), IndexOptions.SetUnique(true));
        }
예제 #16
0
        public void EnsureIndex(Dictionary <string, object> matchData)
        {
            // matchKeys, Interval, Left
            IndexKeysBuilder ikb = new IndexKeysBuilder();

            ikb = ikb.Ascending(matchData.Keys.ToArray());

            CheckConnection();
            Collection.EnsureIndex(ikb);
            //
            var indexE = IndexKeys <MongoRange> .Ascending(r => r.SecondsInterval).Ascending(r => r.Left);

            Collection.EnsureIndex(indexE);
        }
예제 #17
0
        protected void CreateUniqueIndex(string indexedField)
        {
            if (collection == null)
            {
                return;
            }

            if (collection.Count() != 0)
            {
                return;
            }

            collection.EnsureIndex(new IndexKeysBuilder().Ascending(indexedField), IndexOptions.SetUnique(true));
        }
        public void Setup()
        {
            _server = Configuration.TestServer;
            _database = Configuration.TestDatabase;
            _collection = Configuration.GetTestCollection<B>();

            _collection.Drop();
            _collection.EnsureIndex(new IndexKeysBuilder().Ascending("a", "b"), IndexOptions.SetName("i"));
            _collection.EnsureIndex(new IndexKeysBuilder().Ascending("a", "b"), IndexOptions.SetName("i"));

            _collection.Insert(new B { Id = ObjectId.GenerateNewId(), a = 1, b = 10, c = 100 });
            _collection.Insert(new B { Id = ObjectId.GenerateNewId(), a = 2, b = 20, c = 200 });
            _collection.Insert(new B { Id = ObjectId.GenerateNewId(), a = 3, b = 30, c = 300 });
            _collection.Insert(new B { Id = ObjectId.GenerateNewId(), a = 4, b = 40, c = 400 });
        }
 public MongoController()
 {
     objServer   = MongoServer.Create("Server=localhost:27017");
     objDatabse  = objServer.GetDatabase("UniqueTestDatabase");
     UserDetails = objDatabse.GetCollection <BsonDocument>("Users");
     UserDetails.EnsureIndex(new IndexKeysBuilder().Ascending("Name"), IndexOptions.SetUnique(true));
 }
예제 #20
0
        public static List <Comments> getCommentsTop(int Type, string AtId, int top)
        {
            List <Comments> lst = new List <Comments>();

            MongoCollection <Comments> objCollection = db.GetCollection <Comments>("c_Comments");

            objCollection.EnsureIndex("Type");

            var query = Query.And(
                Query.EQ("Type", Type),
                Query.EQ("AtId", ObjectId.Parse(AtId)));
            var cursor = objCollection.Find(query);

            cursor.Limit = top;
            var sortBy = SortBy.Descending("AddedDate");

            cursor.SetSortOrder(sortBy);
            foreach (var item in cursor)
            {
                lst.Add(item);
            }


            return(lst);
        }
예제 #21
0
        public static void CreateIndex(string connectionString, string databaseName, string collectionName, params string[] keyNames)
        {
            SafeModeResult result = new SafeModeResult();

            if (null == keyNames)
            {
                return;
            }

            MongoServer server = MongoServer.Create(connectionString);

            //获取数据库或者创建数据库(不存在的话)。
            MongoDatabase database = server.GetDatabase(databaseName);



            using (server.RequestStart(database))//开始连接数据库。
            {
                MongoCollection <BsonDocument> myCollection = database.GetCollection <BsonDocument>(collectionName);
                if (!myCollection.IndexExists(keyNames))
                {
                    myCollection.EnsureIndex(keyNames);
                }
            }
        }
예제 #22
0
        public static List <Ticker> getTickerByUserId(string UserId, int top)
        {
            List <Ticker> lst = new List <Ticker>();

            MongoCollection <Ticker> objCollection = db.GetCollection <Ticker>("c_Ticker");

            objCollection.EnsureIndex("Type");

            var      query  = Query.EQ("TickerOwnerUserId", ObjectId.Parse(UserId));
            DateTime dt     = DateTime.Now.AddHours(-48);
            var      query2 = Query.GTE("AddedDate", dt);


            var query3 = Query.And(query, query2);
            var cursor = objCollection.Find(query3);

            cursor.Limit = top;
            var sortBy = SortBy.Descending("AddedDate");

            cursor.SetSortOrder(sortBy);
            foreach (var item in cursor)
            {
                lst.Add(item);
            }


            return(lst);
        }
예제 #23
0
        public override void AddCacheKeyMap(CacheKeyMapDescriptor request)
        {
            MongoCollection <CacheKeyMapDescriptor> collection = DistributedCacheHelper.GetMongoDBCacheKeyMapCollection();

            if (collection != null)
            {
                try
                {
                    var query = Query.And(Query.EQ("CacheKey", request.CacheKey));
                    collection.Remove(query);
                }
                catch (Exception ex)
                { }
                WriteConcernResult res = collection.Save(request);
                if (request.Cachelimit != Cachelimit.Forever)
                {
                    TimeSpan timespan = request.ExpireDate.Subtract(DateTime.Now);

                    if (!collection.IndexExists(new IndexKeysBuilder().Ascending("ExpireDate")))
                    {
                        collection.EnsureIndex(new IndexKeysBuilder().Ascending("ExpireDate"), IndexOptions.SetTimeToLive(timespan));
                    }
                }
            }
        }
예제 #24
0
        void EnsureIndexHasBeenCreated(IEnumerable <string> sagaDataPropertyPathsToIndex, MongoCollection <BsonDocument> collection)
        {
            if (!indexCreated)
            {
                lock (this)
                {
                    if (!indexCreated)
                    {
                        collection.ResetIndexCache();

                        //                        var indexes = collection.GetIndexes();

                        foreach (var propertyToIndex in sagaDataPropertyPathsToIndex.Except(new[] { "Id" }))
                        {
                            var indexDefinition = IndexKeys.Ascending(propertyToIndex);

                            //if (IndexAlreadyExists(indexes, propertyToIndex))
                            //{
                            //    AssertIndexIsCorrect(indexes, propertyToIndex);
                            //}

                            collection.EnsureIndex(indexDefinition,
                                                   IndexOptions.SetBackground(false).SetUnique(true));
                        }

                        //collection.ReIndex();

                        indexCreated = true;
                    }
                }
            }
        }
예제 #25
0
        public static T[] GetNear <T>(this MongoCollection <T> collection, string key, double x, double y, int limit)
        {
            collection.EnsureIndex(IndexKeys.GeoSpatial(key));
            var query = Query.Near(key, x, y);

            return(collection.Find(query).Take(limit).ToArray());
        }
예제 #26
0
        public static List <Wall> getWallByUserIdAndFriendID(string UserId, string FriendID, int top)
        {
            List <Wall> lst = new List <Wall>();

            MongoCollection <Wall> objCollection = db.GetCollection <Wall>("c_Wall");

            objCollection.EnsureIndex("Type");

            var query = Query.And(
                Query.EQ("WallOwnerUserId", ObjectId.Parse(FriendID)),
                Query.EQ("PostedByUserId", ObjectId.Parse(UserId))
                );

            var cursor = objCollection.Find(query);

            cursor.Limit = top;
            var sortBy = SortBy.Descending("AddedDate");

            cursor.SetSortOrder(sortBy);
            foreach (var item in cursor)
            {
                lst.Add(item);
            }


            return(lst);
        }
 public void TestSetUp()
 {
     if (_testDb.CollectionExists(TestCollectionName))
         _testDb.DropCollection(TestCollectionName);
     _collection = _testDb.GetCollection<BsonDocument>(TestCollectionName);
     _collection.EnsureIndex(IndexKeys.Ascending("key"), IndexOptions.SetUnique(true));
 }
예제 #28
0
        public void TestEnsureIndexAfterDropCollection()
        {
            if (_collection.Exists())
            {
                _collection.Drop();
            }

            Assert.IsFalse(_collection.IndexExists("x"));
            _collection.EnsureIndex("x");
            Assert.IsTrue(_collection.IndexExists("x"));

            _collection.Drop();
            Assert.IsFalse(_collection.IndexExists("x"));
            _collection.EnsureIndex("x");
            Assert.IsTrue(_collection.IndexExists("x"));
        }
예제 #29
0
        void EnsureIndexHasBeenCreated(IEnumerable <string> sagaDataPropertyPathsToIndex, MongoCollection <BsonDocument> collection)
        {
            if (!indexEnsuredRecently)
            {
                lock (indexEnsuredRecentlyLock)
                {
                    if (!indexEnsuredRecently)
                    {
                        log.Info("Re-declaring indexes with unique constraints for the following paths: {0}", string.Join(", ", sagaDataPropertyPathsToIndex));

                        //collection.ResetIndexCache();

                        //                        var indexes = collection.GetIndexes();

                        foreach (var propertyToIndex in sagaDataPropertyPathsToIndex.Except(new[] { "Id" }))
                        {
                            var indexDefinition = IndexKeys.Ascending(propertyToIndex);

                            //if (IndexAlreadyExists(indexes, propertyToIndex))
                            //{
                            //    AssertIndexIsCorrect(indexes, propertyToIndex);
                            //}

                            collection.EnsureIndex(indexDefinition,
                                                   IndexOptions.SetBackground(false).SetUnique(true));
                        }

                        //collection.ReIndex();

                        indexEnsuredRecently = true;
                    }
                }
            }
        }
예제 #30
0
        public static void CreateIndex(this Schema schema)
        {
            MongoCollection <BsonDocument> collection = schema.GetCollection();

            try
            {
                collection.EnsureIndex(ModelExtensions.GetCaseInsensitiveFieldName("FolderName"), ModelExtensions.GetCaseInsensitiveFieldName("UUID"), ModelExtensions.GetCaseInsensitiveFieldName("Published"));
                collection.EnsureIndex(ModelExtensions.GetCaseInsensitiveFieldName("FolderName"), ModelExtensions.GetCaseInsensitiveFieldName("UserKey"), ModelExtensions.GetCaseInsensitiveFieldName("Published"));
                collection.EnsureIndex(ModelExtensions.GetCaseInsensitiveFieldName("FolderName"), ModelExtensions.GetCaseInsensitiveFieldName("UUID"), ModelExtensions.GetCaseInsensitiveFieldName("Published"));
                collection.EnsureIndex(ModelExtensions.GetCaseInsensitiveFieldName("FolderName"), ModelExtensions.GetCaseInsensitiveFieldName("UserKey"), ModelExtensions.GetCaseInsensitiveFieldName("Published"));
                collection.EnsureIndex(ModelExtensions.GetCaseInsensitiveFieldName("FolderName"), ModelExtensions.GetCaseInsensitiveFieldName("ParentFolder"), ModelExtensions.GetCaseInsensitiveFieldName("ParentUUID"));
            }//ignore the index creating exception
            catch (Exception e)
            {
                Kooboo.HealthMonitoring.Log.LogException(e);
            }
        }
예제 #31
0
 public void TestDropDatabaseClearsIndexCache()
 {
     _server.IndexCache.Reset();
     _collection.EnsureIndex("x");
     Assert.IsTrue(_server.IndexCache.Contains(_collection, "x_1"));
     _database.Drop();
     Assert.IsFalse(_server.IndexCache.Contains(_collection, "x_1"));
 }
예제 #32
0
        public void TestEnsureIndexAfterDropCollection()
        {
            if (collection.Exists())
            {
                collection.Drop();
            }
            server.ResetIndexCache();

            Assert.IsFalse(collection.IndexExists("x"));
            collection.EnsureIndex("x");
            Assert.IsTrue(collection.IndexExists("x"));

            collection.Drop();
            Assert.IsFalse(collection.IndexExists("x"));
            collection.EnsureIndex("x");
            Assert.IsTrue(collection.IndexExists("x"));
        }
예제 #33
0
        static void CreateIndex(MongoCollection col, string field)
        {
            if (field == "_id") //create proper index first!
            {
                return;
            }

            col.EnsureIndex(IndexKeys.Ascending(field), IndexOptions.SetBackground(true));
        }
예제 #34
0
        /// <summary>
        /// Ensures that the proper indexes for GridFS exist.
        /// </summary>
        /// <param name="maxFiles">Only create new indexes if there are fewer than this number of GridFS files).</param>
        public void EnsureIndexes(
            int maxFiles
            )
        {
            // don't try to create indexes on secondaries
            var requestConnection = database.Server.RequestConnection;

            if (requestConnection != null)
            {
                // check whether the actual server instance we are using is a primary
                var serverInstance = requestConnection.ServerInstance;
                if (!serverInstance.IsPrimary)
                {
                    return;
                }
            }
            else
            {
                // check whether we are guaranteed to use a primary
                if (database.Settings.SlaveOk)
                {
                    return;
                }
            }

            // avoid round trip to count files if possible
            var indexCache = database.Server.IndexCache;

            if (
                indexCache.Contains(files, "filename_1_uploadDate_1") &&
                indexCache.Contains(chunks, "files_id_1_n_1")
                )
            {
                return;
            }

            // only create indexes if number of GridFS files is still small (to avoid performance surprises)
            var count = files.Count();

            if (count < maxFiles)
            {
                files.EnsureIndex("filename", "uploadDate");
                chunks.EnsureIndex(IndexKeys.Ascending("files_id", "n"), IndexOptions.SetUnique(true));
            }
            else
            {
                // at least check to see if the indexes exist so we can stop calling files.Count()
                if (files.IndexExistsByName("filename_1_uploadDate_1"))
                {
                    indexCache.Add(files, "filename_1_uploadDate_1");
                }
                if (chunks.IndexExistsByName("files_id_1_n_1"))
                {
                    indexCache.Add(chunks, "files_id_1_n_1");
                }
            }
        }
예제 #35
0
        private void EnsureIndexes()
        {
            _commits.EnsureIndex(
                IndexKeys.Ascending("CommitId"),
                IndexOptions.SetName("CommitIdIndex"));

            _commits.EnsureIndex(
                IndexKeys.Ascending("Processed"),
                IndexOptions.SetName("ProcessedIndex"));

            _commits.EnsureIndex(
                IndexKeys.Descending("EventSourceId", "FromVersion"),
                IndexOptions.SetName("OptimisticEventSourceConcurrencyIndex").SetUnique(true));

            _events.EnsureIndex(
                IndexKeys.Ascending("EventIdentifier"),
                IndexOptions.SetName("EventIdentifierIndex"));
        }
        public MongoDbApiOutputCache(MongoDatabase mongoDatabase, string cacheCollectionName)
        {
            MongoCollection = mongoDatabase.GetCollection(cacheCollectionName);

            MongoCollection.EnsureIndex(
                IndexKeys.Ascending("expireAt"),
                IndexOptions.SetTimeToLive(TimeSpan.FromMilliseconds(0))
                );
        }
예제 #37
0
        public void Create(MongoCollection collection,bool isBackground)
        {
            var index  = OnBuildIndex();
          
            log.Debug("Index {0}: {1}",name,index);
            log.Info("Ensuring index {0} exists on collection {1}",name,collection.Name);

            collection.EnsureIndex(index, new IndexOptionsBuilder().SetBackground(isBackground).SetName(name));
        }
예제 #38
0
        public DrugLord()
        {
            database = MongoDatabase.Create(ConfigurationManager.AppSettings["mongo"]);

            money = database.GetCollection("money");
            money.EnsureIndex(IndexKeys.Ascending("userToken", "secretCode"), IndexOptions.SetUnique(true));

            drugs = database.GetCollection("drugs");
            drugs.EnsureIndex(IndexKeys.Ascending("userToken", "secretCode"), IndexOptions.SetUnique(true));
        }
예제 #39
0
        public PatientRepository()
        {
            _server = new MongoServer(new MongoServerSettings { Server = new MongoServerAddress(_DBHOST), SafeMode = SafeMode.True });

            //patients
            _patients = _server.GetDatabase(_DBNAME).GetCollection<PatientModel>("patients");
            _patients.EnsureIndex(IndexKeys.Ascending("_id"), IndexOptions.SetUnique(true));
            _gridFS = _server.GetDatabase(_DBNAME).GridFS;

            new MongoDB.Web.Providers.MongoDBMembershipProvider();
        }
        public void SetUp()
        {
            var db = Configuration.TestDatabase;
            _collection = db.GetCollection<GeoClass>("geo");

            _collection.Drop();
            _collection.EnsureIndex(IndexKeys<GeoClass>.GeoSpatialSpherical(x => x.Location));
            _collection.EnsureIndex(IndexKeys<GeoClass>.GeoSpatialSpherical(x => x.Surrounding));

            var doc = new GeoClass
            {
                Id = 1,
                Location = GeoJson.Point(GeoJson.Geographic(40.5, 18.5)),
                Surrounding = GeoJson.Polygon(
                    GeoJson.Geographic(40, 18),
                    GeoJson.Geographic(40, 19),
                    GeoJson.Geographic(41, 19),
                    GeoJson.Geographic(40, 18))
            };

            _collection.Save(doc);
        }
 public CommandProcessingAuditRepository(string connectionString) : base(connectionString)
 {
   _commandProcessingAuditCollection = CurrentMongoDB.GetCollection<CommandProcessingAudit>(_commandProcessingAuditCollectionName);
   _commandProcessingAuditCollection.EnsureIndex(IndexKeys<CommandProcessingAudit>.Ascending(n => n.Id), IndexOptions.SetUnique(true));
   _commandProcessingAuditCollection.EnsureIndex(IndexKeys<CommandProcessingAudit>.Ascending(n => n.CostCentreApplicationId));
   _commandProcessingAuditCollection.EnsureIndex(IndexKeys<CommandProcessingAudit>.Ascending(n => n.Status));
   _commandProcessingAuditCollection.EnsureIndex(IndexKeys<CommandProcessingAudit>.Ascending(n => n.DocumentId));
   _commandProcessingAuditCollection.EnsureIndex(IndexKeys<CommandProcessingAudit>.Ascending(n => n.ParentDocumentId));
   _commandProcessingAuditCollection.EnsureIndex(IndexKeys<CommandProcessingAudit>.Ascending(n => n.DateInserted));
 }
 public Boolean GuardarProveedor(Proveedor P)
 {
     try
     {
         coleccion = bd.GetCollection<Proveedor>("Proveedor");
         coleccion.EnsureIndex(new IndexKeysBuilder().
             Ascending("Rut"), IndexOptions.SetUnique(true));
         this.mensaje.Append(coleccion.Insert(P).Response.ToString());
         return true;
     }
     catch (MongoSafeModeException MSME)
     {
         this.mensaje.Append("Rut Duplicado: " + P.Rut);
     }
     catch (Exception E)
     {
         this.mensaje.Append(E.Message);
     }
     return false;
 }
예제 #43
0
        public MessageSessionInfo EnsureSession(string appName, string sessionId, ObjectId from, ObjectId to, MongoCollection<MessageSessionInfo> collection)
        {
            var session = collection.Find(Query.EQ("session_id", sessionId)).SetFields("session_id", "user_1", "user_2", "user1_is_deleted", "user2_is_deleted").FirstOrDefault();

            if (session == null)
            {
                session = new MessageSessionInfo()
                {
                    SessionId = sessionId,
                    User1 = from,
                    User2 = to,
                    Messages = new MessageInfo[0],
                    LastUpdated = DateTime.Now,
                    UnreadMessagesUser1 = 0,
                    UnreadMessagesUser2 = 0
                };
                collection.EnsureIndex("session_id");
                collection.Insert(session);
            }
            return session;
        }
예제 #44
0
 /// <summary>
 /// Constructs the timeout storage, connecting to the Mongo database pointed to by the given connection string,
 /// storing the timeouts in the given collection
 /// </summary>
 public MongoDbTimeoutStorage(string connectionString, string collectionName)
 {
     database = MongoHelper.GetDatabase(connectionString);
     collection = database.GetCollection(collectionName);
     collection.EnsureIndex(IndexKeys.Ascending(TimeProperty), IndexOptions.SetBackground(true).SetUnique(false));
 }
예제 #45
0
        /// <summary>
        /// Calculate the amount of documents
        /// </summary>
        /// <param name="name">Field name to group by</param>
        /// <returns>Document list represented by "Key" and "Value" inside aggregate result object</returns>
        public AggregateResult GroupByCount(string name, MongoCollection collection, BsonDocument sort, BsonDocument limit, BsonDocument skip, BsonDocument match, bool countGroups =false)
        {
            // prepare pipeline operations
            var group = new BsonDocument
            {
                {
                    "$group",
                    new BsonDocument
                    {
                        {
                            "_id", new BsonDocument
                            {
                                {
                                    "Key","$" + name
                                }
                            }
                        },
                        {
                            "Value", new BsonDocument
                            {
                                {
                                    "$sum", 1
                                }
                            }
                        }
                    }
                }
            };

            var project = new BsonDocument
            {
                {
                    "$project",
                    new BsonDocument
                    {
                        {"_id", 0}, // remove reference to _id
                        {"Key","$_id.Key"}, // set reference to "_id.Name" as "UserName"
                        {"Value", 1}, // dont  change "Count"
                    }
                }
            };

            List<BsonDocument> pipeline = new List<BsonDocument>{ };
            if (match != null)
                pipeline.Add(match);

            pipeline.Add(group);
            if (countGroups)
            {
                var total = new BsonDocument
                {
                    {
                        "$group",
                        new BsonDocument
                        {
                            {
                                "_id", 0
                            },
                            {
                                "Total", new BsonDocument
                                {
                                    {
                                        "$sum", 1
                                    }
                                }
                            }
                        }
                    }
                };

                pipeline.Add(total);
            }
            else
            {
                pipeline.Add(project);

                if (sort != null)
                {
                    pipeline.Add(sort);
                }
                pipeline.Add(skip);
                pipeline.Add(limit);
            }
            collection.EnsureIndex(IndexKeys.Ascending(name));
            return collection.Aggregate(pipeline);
        }
예제 #46
0
        static void CreateIndex(MongoCollection col, string field)
        {
            if (field == "_id") //create proper index first!
                return;

            col.EnsureIndex(IndexKeys.Ascending(field), IndexOptions.SetBackground(true));
        }
        static CourseManager()
        {
            collection = new MongoClient(ConfigurationManager.ConnectionStrings["MongoConnection"].ConnectionString)
                .GetServer().GetDatabase("EAMSystem").GetCollection<Course>("Courses");

            collection.EnsureIndex("CourseNo");
        }
        static TeacherManager()
        {
            collection = new MongoClient("mongodb://localhost").GetServer().GetDatabase("EAMSystem").GetCollection<Teacher>("Teachers");

            collection.EnsureIndex("TeaNo");
        }
        static StudentManager()
        {
            collection = new MongoClient("mongodb://localhost").GetServer().GetDatabase("EAMSystem").GetCollection<Student>("Students");

            collection.EnsureIndex("StuNo");
        }
예제 #50
0
 public void EnsureTTLIndex(MongoCollection<SessionObject> collection, double timeoutInMinutes) {
     var options = IndexOptions.SetTimeToLive(TimeSpan.FromMinutes(timeoutInMinutes));
     collection.EnsureIndex(new IndexKeysBuilder().Ascending("Expires"), options);
 }
        public override void Initialize(string name, NameValueCollection config)
        {
            ApplicationName = config["applicationName"] ?? HostingEnvironment.ApplicationVirtualPath;
            enablePasswordReset = Boolean.Parse(config["enablePasswordReset"] ?? "true");
            enablePasswordRetrieval = Boolean.Parse(config["enablePasswordRetrieval"] ?? "false");
            maxInvalidPasswordAttempts = Int32.Parse(config["maxInvalidPasswordAttempts"] ?? "5");
            minRequiredNonAlphanumericCharacters = Int32.Parse(config["minRequiredNonAlphanumericCharacters"] ?? "1");
            minRequiredPasswordLength = Int32.Parse(config["minRequiredPasswordLength"] ?? "7");
            passwordAttemptWindow = Int32.Parse(config["passwordAttemptWindow"] ?? "10");
            passwordFormat = (MembershipPasswordFormat)Enum.Parse(typeof(MembershipPasswordFormat), config["passwordFormat"] ?? "Hashed");
            passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"] ?? string.Empty;
            requiresQuestionAndAnswer = Boolean.Parse(config["requiresQuestionAndAnswer"] ?? "false");
            requiresUniqueEmail = Boolean.Parse(config["requiresUniqueEmail"] ?? "true");

            if (PasswordFormat == MembershipPasswordFormat.Hashed && EnablePasswordRetrieval)
            {
                throw new ProviderException("Configured settings are invalid: Hashed passwords cannot be retrieved. Either set the password format to different type, or set enablePasswordRetrieval to false.");
            }

            mongoCollection = MongoServer.Create(config["connectionString"] ?? "mongodb://localhost")
                                         .GetDatabase(config["database"] ?? "ASPNETDB")
                                         .GetCollection(config["collection"] ?? "Users");

            mongoCollection.EnsureIndex("ApplicationName");
            mongoCollection.EnsureIndex("ApplicationName", "Email");
            mongoCollection.EnsureIndex("ApplicationName", "Username");

            base.Initialize(name, config);
        }