public void Setup()
 {
     _server = LegacyTestConfiguration.Server;
     _primary = _server.Instances.First(x => x.IsPrimary);
     _database = LegacyTestConfiguration.Database;
     _collection = LegacyTestConfiguration.Collection;
 }
 public void Setup()
 {
     _server = Configuration.TestServer;
     _server.Connect();
     _database = Configuration.TestDatabase;
     _collection = Configuration.TestCollection;
 }
Beispiel #3
0
 public HugRepository(string connectionString, string databaseName, IUserProfileRepository userProfileRepository)
 {
     _userProfileRepository = userProfileRepository;
     _server = MongoServer.Create(connectionString);
     _database = _server.GetDatabase(databaseName);
     _mongoCollection = _database.GetCollection<PenedatingMongoUser>("users");
 }
Beispiel #4
0
 /// <summary>
 /// 初始化
 /// </summary>
 /// <param name="mDataViewInfo">Filter也是DataViewInfo的一个属性,所以这里加上参数</param>
 public frmQuery(MongoDBHelper.DataViewInfo mDataViewInfo)
 {
     InitializeComponent();
     CurrentDataViewInfo = mDataViewInfo;
     SystemManager.SelectObjectTag = mDataViewInfo.strDBTag;
     _mongoCol = SystemManager.GetCurrentCollection();
 }
 public void TestFixtureSetup()
 {
     _server = Configuration.TestServer;
     _database = Configuration.TestDatabase;
     _collection = Configuration.TestCollection;
     _collection.Drop();
 }
        private Level2FlightRecord HandleOneStep(int currentSecond, int step, FlightParameter para,
            LevelTopFlightRecord topRecord, Flight flight, MongoCollection<Level1FlightRecord> collection)
        {
            IMongoQuery query = Query.And(Query.EQ("ParameterID", new BsonString(para.ParameterID)),
                Query.GTE("FlightSecond", new BsonInt32(currentSecond)),
                Query.LT("FlightSecond", new BsonInt32(currentSecond + step)));

            MongoCursor<Level1FlightRecord> flightRecord = collection.Find(query);

            Level2FlightRecord level2 = new Level2FlightRecord()
            {
                StartSecond = currentSecond,
                EndSecond = Math.Min(flight.EndSecond, currentSecond + step),
                // Level1FlightRecords = flightRecord.ToArray(),
                ParameterID = para.ParameterID,
            };

            //var sum = from one in level2.Level1FlightRecords
            //          select one.ValueCount;
            //level2.Count = sum.Sum();

            //var avg = from one in level2.Level1FlightRecords
            //          select one.AvgValue;
            //level2.AvgValue = avg.Sum() * level2.Count;

            //var min = from one in level2.Level1FlightRecords
            //          select one.MinValue;
            //level2.MinValue = min.Min();

            //var max = from one in level2.Level1FlightRecords
            //          select one.MaxValue;
            //level2.MaxValue = max.Max();

            return level2;
        }
Beispiel #7
0
 /// <summary>
 ///     Adds a user to this database.
 /// </summary>
 /// <param name="user">The user.</param>
 public static void AddUserEx(MongoCollection Col, User user)
 {
     var document = Col.FindOneAs<BsonDocument>(Query.EQ("user", user.Username));
     if (document == null)
     {
         document = new BsonDocument("user", user.Username);
     }
     document["roles"] = user.roles;
     if (document.Contains("readOnly"))
     {
         document.Remove("readOnly");
     }
     //必须要Hash一下Password
     document["pwd"] = MongoUser.HashPassword(user.Username, user.Password);
     //OtherRole 必须放在Admin.system.users里面
     if (Col.Database.Name == MongoDbHelper.DATABASE_NAME_ADMIN)
     {
         document["otherDBRoles"] = user.otherDBRoles;
     }
     if (string.IsNullOrEmpty(user.Password))
     {
         document["userSource"] = user.userSource;
     }
     Col.Save(document);
 }
 public void Setup()
 {
     _server = Configuration.TestServer;
     _primary = Configuration.TestServer.Primary;
     _database = Configuration.TestDatabase;
     _collection = Configuration.TestCollection;
 }
        /// <summary>
        /// LevelTop只能有一个
        /// </summary>
        /// <param name="flight"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        public LevelTopFlightRecord FromLevel1RecordCollectionToLevelTopRecords(
            Flight flight, MongoCollection<Level1FlightRecord> collection)
        {
            FlightParameter[] parameters = this.GetParameters();
            Dictionary<string, LevelTopFlightRecord> topRecordMaps = new Dictionary<string, LevelTopFlightRecord>();
            Dictionary<LevelTopFlightRecord, List<Level2FlightRecord>> level2RecordMap
                = new Dictionary<LevelTopFlightRecord, List<Level2FlightRecord>>();
            List<LevelTopFlightRecord> topRecords = new List<LevelTopFlightRecord>();

            foreach (FlightParameter para in parameters)
            {
                LevelTopFlightRecord topRecord = new LevelTopFlightRecord()
                {
                    StartSecond = flight.StartSecond,
                    EndSecond = flight.EndSecond,
                    ParameterID = para.ParameterID,
                };

                topRecordMaps.Add(para.ParameterID, topRecord);
                level2RecordMap.Add(topRecord, new List<Level2FlightRecord>());

                for (int currentSecond = flight.StartSecond; currentSecond > flight.EndSecond; currentSecond += SecondGap)
                {
                    int step = SecondGap;
                    Level2FlightRecord level2 = this.HandleOneStep(currentSecond, step, para,
                         topRecord, flight, collection);

                    level2RecordMap[topRecord].Add(level2);
                }
            }

            return null;//DEBUG
            //return topRecords.ToArray();
        }
 protected bool Upsert(MongoCollection<object> collection, object obj, Guid id)
 {
     if (collection.FindOneById(id) != null)
         return collection.Update(Query.EQ("_id", id), Update.Replace(obj), WriteConcern.Acknowledged).Ok;
     else
         return Add(collection, obj);
 }
        private static void ChooseAction(MongoCollection<Word> words)
        {
            string action = Console.ReadLine();

            switch (action)
            {
                case "1":
                    ReadWord(words);
                    break;
                case "2":
                    ListWords(words);
                    break;
                case "3":
                    FindWords(words);
                    break;
                case "4":
                    DisplayStartupMenu();
                    break;
                case "exit":
                    Console.WriteLine("Goodbuy!");
                    return;
                default:
                    Console.WriteLine("Invalid action, please choose again.");
                    break;
            }

            ChooseAction(words);
        }
 private static void AddToDictionary(MongoCollection english)
 {
     Console.WriteLine("Enter word.");
     string word = Console.ReadLine();
     Console.WriteLine("Enter translation.");
     string translation = Console.ReadLine();
     if (!string.IsNullOrWhiteSpace(word) && !string.IsNullOrWhiteSpace(translation))
     {
         var query = Query.And(Query.EQ("Name", word));
         var filtered = english.FindAs<Word>(query);
         var count = filtered.Count();
         if (count == 0)
         {
             english.Insert(new Word(word, translation));
             Console.WriteLine("The word {0} is added.", word);
         }
         else
         {
             Console.WriteLine("The word {0} is already added.", word);
         }
     }
     else
     {
         Console.WriteLine("You enter null or empty string for word or translation. Please try again.");
     }
 }
 private static void ChangeTranslation(MongoCollection english)
 {
     Console.WriteLine("Enter word.");
     string word = Console.ReadLine();
     Console.WriteLine("Enter translation.");
     string translation = Console.ReadLine();
     if (!string.IsNullOrWhiteSpace(word) && !string.IsNullOrWhiteSpace(translation))
     {
         var query = Query.And(Query.EQ("Name", word));
         var filtered = english.FindAs<Word>(query);
         var count = filtered.Count();
         if (count > 0)
         {
             foreach (var item in filtered)
             {
                 var update = Update.Set("Translation", translation);
                 var queryId = Query.EQ("_id", item.Id);
                 english.Update(queryId, update);
                 Console.WriteLine("Translation of the word {0} is changed.", word);
             }
         }
         else
         {
             Console.WriteLine("There is no word {0}.", word);
         }
     }
     else
     {
         Console.WriteLine("You enter null or empty string for word or translation. Please try again.");
     }
 }
 public void TestSetUp()
 {
     if (_testDb.CollectionExists(TestCollectionName))
         _testDb.DropCollection(TestCollectionName);
     _collection = _testDb.GetCollection<BsonDocument>(TestCollectionName);
     _collection.EnsureIndex(IndexKeys.Ascending("key"), IndexOptions.SetUnique(true));
 }
 public void Setup()
 {
     server = MongoServer.Create("mongodb://localhost/?safe=true");
     server.Connect();
     database = server["onlinetests"];
     collection = database["testcollection"];
 }
Beispiel #16
0
        public dynamic find(MongoCollection collection,object[] args)
        {
            Type type = args[0].GetType();

            if(type.Name.Contains("<>__AnonType")){

                PropertyInfo[] properties = type.GetProperties();
                Dictionary<string,object> dictionary = new Dictionary<string, object>();
                foreach(var property in properties)
                    dictionary[property.Name] = property.GetValue(args[0],null);

                var query = new QueryDocument(dictionary);
                var result = collection.FindAs<BsonDocument>(query);
                List<Entity> documents = new List<Entity>();

                if(result.Size() > 0)
                {
                    foreach(var entity in result)
                        documents.Add(new Entity(entity));
                }

                return documents;
            }
            throw new NotImplementedException("Only annonymous types are accepted for Queries.");
        }
        public IEnumerable<BsonDocument> Run(MongoCollection<Rental> rentals)
        {
            var priceRange = new BsonDocument(
                "$subtract",
                new BsonArray
                {
                    "$Price",
                    new BsonDocument(
                        "$mod",
                        new BsonArray{"$Price",500}
                        )
                });
            var grouping =new BsonDocument(
                "$group",
                new BsonDocument
                {
                    {"_id",priceRange},
                    {"count",new BsonDocument("$sum",1)}
                });
            var sort=new BsonDocument(
                "$sort",
                new BsonDocument("_id",1)
                );

            var args=new AggregateArgs
            {
                Pipeline=new []{grouping,sort}
            };

            return rentals.Aggregate(args);
        }
 public PersonRepository()
 {
     string connectionString = "mongodb://localhost";
     _server = MongoServer.Create(connectionString);
     _peopleDb = _server.GetDatabase("Mono");
     _people = _peopleDb.GetCollection<Person>("Person");
 }
 internal static void CreateConnection()
 {
     Runner = MongoDbRunner.Start();
     var server = MongoServer.Create(Runner.ConnectionString);
     var database = server.GetDatabase("IntegrationTest");
     Collection = database.GetCollection<Post>("TestCollection");
 }
        private IEnumerable<ArticleWebDto> GetAroundYouArticles(
            MongoCollection<ArticleDto> articles,
            string lngString,
            string latString,
            CultureInfo culture)
        {
            var innerMaxDistance = 3.0d;
            var outerMaxDistance = 5.0d;

            var innerMaxDistanceString = (innerMaxDistance / EarthRadius).ToString(culture.NumberFormat);
            var outerMaxDistanceString = (outerMaxDistance / EarthRadius).ToString(culture.NumberFormat);

            var jsonQuery = "{$and:[ " +
                "{'location':{$geoWithin:{$centerSphere:[[" + lngString + "," + latString + "]," + outerMaxDistanceString + "]}}}," +
                "{'location':{$not:{$geoWithin:{$centerSphere:[[" + lngString + "," + latString + "]," + innerMaxDistanceString + "]}}} }," +
            "]}";

            var doc = BsonSerializer.Deserialize<BsonDocument>(jsonQuery);
            var query = new QueryDocument(doc);
            var results = articles.Find(query).SetSortOrder(new SortByBuilder().Descending("publishedAt")).SetLimit(50);

            var dtos = results.ToList().Select(ConvertArticleDtoToArticleWebDto());

            return dtos;
        }
Beispiel #21
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            ObjectId organizationId = document.GetValue(ProjectRepository.FieldNames.OrganizationId).AsObjectId;
            var users = Database.GetCollection(UserRepository.CollectionName)
                .Find(Query.In(UserRepository.FieldNames.OrganizationIds, new List<BsonValue> {
                    organizationId
                }))
                .SetFields(ProjectRepository.FieldNames.Id).ToList();

            if (!document.Contains(ProjectRepository.FieldNames.NotificationSettings))
                document.Add(ProjectRepository.FieldNames.NotificationSettings, new BsonDocument());

            BsonDocument settings = document.GetValue(ProjectRepository.FieldNames.NotificationSettings).AsBsonDocument;
            foreach (var user in users) {
                var userId = user.GetValue(ProjectRepository.FieldNames.Id).AsObjectId.ToString();
                if (!settings.Contains(userId))
                    settings.Add(userId, new BsonDocument());

                var userSettings = settings.GetValue(userId).AsBsonDocument;
                if (!userSettings.Contains("SendDailySummary"))
                    userSettings.Add("SendDailySummary", new BsonBoolean(true));
                else
                    userSettings.Set("SendDailySummary", new BsonBoolean(true));
            }

            collection.Save(document);
        }
 public void TestFixtureSetup()
 {
     _database = Configuration.TestDatabase;
     var collectionSettings = new MongoCollectionSettings() { GuidRepresentation = GuidRepresentation.Standard };
     _collection = _database.GetCollection<C>("csharp714", collectionSettings);
     _collection.Drop();
 }
 public static void EstablishConnection()
 {
     client = new MongoClient(connectionString);
     server = client.GetServer();
     database = server.GetDatabase(DbName);
     entries = database.GetCollection<JSonReport>(collectionName);
 }
 public void Setup()
 {
     _server = Configuration.TestServer;
     _primary = _server.Instances.First(x => ReadPreference.Primary.MatchesInstance(x));
     _database = Configuration.TestDatabase;
     _collection = Configuration.TestCollection;
 }
        public ProblemRepositoryTest()
        {
            // Perform factory set up (once for entire test run)
            IGenerationSessionFactory factory = AutoPocoContainer.Configure(x =>
            {
                x.Conventions(c => c.UseDefaultConventions());
                x.AddFromAssemblyContainingType<Member>();

                x.Include<Member>()
                    .Setup(m => m.Id).Use<ObjectIdDataSource>()
                    .Setup(m => m.OpenId).Random(5, 10)
                    .Setup(m => m.UserName).Random(5, 7);

                x.Include<Problem>()
                    .Setup(p => p.Id).Use<ObjectIdDataSource>()
                    .Setup(p => p.Text).Use<LoremIpsumSource>()
                    .Setup(p => p.Title).Random(7, 12);

                x.Include<Response>()
                    .Setup(r => r.Text).Use<LoremIpsumSource>();
            });

            // Generate one of these per test (factory will be a static variable most likely)
            _session = factory.CreateSession();

            _conn = new DbConnexion("Test_LittleProblem");
            _problemRepository = new ProblemRepository(_conn);
            _problemCollection = _conn.Collection<Problem>(CollectionNames.Problem);
        }
 public BaseRepository(string collection)
 {
     _collectionName = collection;
     var client = new MongoClient(ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString);
     var db = client.GetServer().GetDatabase(ConfigurationManager.ConnectionStrings["mongodb"].ProviderName);
     _collection = db.GetCollection(_collectionName);
 }
 /// <summary>
 /// Initializes a new instance of the MongoInsertOptions class.
 /// </summary>
 /// <param name="collection">The collection from which to get default settings for the options.</param>
 public MongoInsertOptions(
     MongoCollection collection
 ) {
     this.checkElementNames = true;
     this.flags = InsertFlags.None;
     this.safeMode = collection.Settings.SafeMode;
 }
        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));
        }
 public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document)
 {
     var projectIds = document.GetValue("ProjectIds").AsBsonArray.Select(p => p.AsInt32).ToList();
     document.Remove("ProjectIds");
     document.Add("ProjectIds", new BsonArray(projectIds.Select(x => x.ToString())));
     collection.Save(document);
 }
        public IEnumerable<IDictionary<string, object>> Find(MongoCollection<BsonDocument> collection, SimpleQuery query, out IEnumerable<SimpleQueryClauseBase> unhandledClauses)
        {
            var builder = MongoQueryBuilder.BuildFrom(query);

            unhandledClauses = builder.UnprocessedClauses;

            if (builder.IsTotalCountQuery)
            {
                long count;
                if (builder.Criteria == null)
                    count = collection.Count();
                else
                    count = collection.Count(_expressionFormatter.Format(builder.Criteria));

                //TODO: figure out how to make count a long
                builder.SetTotalCount((int)count);
            }

            if (!builder.SkipCount.HasValue && builder.TakeCount.HasValue && builder.TakeCount.Value == 1)
                return new[] { FindOne(collection, builder.Criteria) };

            var cursor = CreateCursor(collection, builder.Criteria);

            ApplyFields(cursor, builder.Columns);
            ApplySorting(cursor, builder.Order);
            ApplySkip(cursor, builder.SkipCount);
            ApplyTake(cursor, builder.TakeCount);

            var aliases = builder.Columns.OfType<ObjectReference>().ToDictionary(x => ExpressionFormatter.GetFullName(x), x => x.GetAlias());

            return cursor.Select(x => x.ToSimpleDictionary(aliases));
        }
Beispiel #31
0
 /// <summary>
 ///     是否为系统数据集[无法删除]
 /// </summary>
 /// <param name="mongoCol"></param>
 /// <returns></returns>
 public static bool IsSystemCollection(MongoCollection mongoCol)
 {
     //http://docs.mongodb.org/manual/reference/system-collections/
     return(IsSystemCollection(mongoCol.Database.Name, mongoCol.Name));
 }
Beispiel #32
0
 public void TestFixtureSetup()
 {
     _collection = LegacyTestConfiguration.GetCollection <C>();
 }
Beispiel #33
0
 public ShipmentsController()
 {
     _shipments = ShipmentDb.Open();
 }
        /// <summary>
        /// 获取集合的存储大小
        /// </summary>
        /// <param name="collectionName">该集合对应的名称</param>
        /// <returns>返回一个long型</returns>
        public long GetDataSize(string collectionName)
        {
            MongoCollection <BsonDocument> mc = this._db.GetCollection <BsonDocument>(collectionName);

            return(mc.GetTotalStorageSize());
        }
        public String Mapreduced(Dictionary <string, string> fields, List <string> movement = null, List <string> objs = null, List <string> locations = null, List <string> users = null, Int64 start = 0, Int64 end = 0)
        {
            var orderfield = "folio";


            try
            {
                List <string> cols = new List <string>();
                foreach (var x in fields)
                {
                    cols.Add(x.Key);
                }
                cols.Add("CreatedTimeStamp");
                string[] arrayfields    = cols.ToArray();
                string[] arraymov       = movement.ToArray();
                string[] arrayobjs      = objs.ToArray();
                string[] arraylocations = locations.ToArray();
                string[] arrayusers     = users.ToArray();

                BsonArray bsonarraymov   = new BsonArray();
                BsonArray bsonarrayobjs  = new BsonArray();
                BsonArray bsonarrayloc   = new BsonArray();
                BsonArray bsonarrayusers = new BsonArray();
                for (int i = 0; i < arraymov.Length; i++)
                {
                    bsonarraymov.Add(arraymov[i]);
                }
                for (int i = 0; i < arrayobjs.Length; i++)
                {
                    bsonarrayobjs.Add(arrayobjs[i]);
                }
                for (int i = 0; i < arraylocations.Length; i++)
                {
                    bsonarrayloc.Add(arraylocations[i]);
                }
                for (int i = 0; i < arrayusers.Length; i++)
                {
                    bsonarrayusers.Add(arrayusers[i]);
                }


                List <BsonDocument> documents = new List <BsonDocument>();

                var query = Query.And(Query.In("movement", bsonarraymov), Query.In("object", bsonarrayobjs), Query.In("location", bsonarrayloc), Query.In("Creator", bsonarrayusers), Query.GTE("CreatedTimeStamp", start), Query.LTE("CreatedTimeStamp", end));

                /*Realiza la conexion */
                MongoCollection Demand    = conection.getCollection("Demand");
                MongoCollection Movements = conection1.getCollection("MovementProfiles");
                MongoCollection Locations = conection2.getCollection("Locations");

                var Movementsfunction = @"function() {
                var key = this._id.valueOf();
                var value={movement:this.name};
                 emit(key,value);
                   }";
                var Locationsfunction = @"function() {
                var key = this._id.valueOf();
                var value={location:this.name};
                 emit(key,value);
                   }";
                var Demandfunction    = @"function() {
                    var key = this.movement;
                     var value = {id:this._id.valueOf(),folio:this.folio,object:this.object,total:this.total,status:this.status,movementFields:this.movementFields,CreatedDate:this.CreatedDate,CreatedTimeStamp:this.CreatedTimeStamp,Creator:this.Creator,system_status:this.system_status};
                     emit(key,value);
                
                   }";
                var Demandfunction2   = @"function() {
                    var key = this.location;
                     var value = {id:this._id.valueOf(),folio:this.folio,object:this.object,total:this.total,status:this.status,movementFields:this.movementFields,CreatedDate:this.CreatedDate,CreatedTimeStamp:this.CreatedTimeStamp,Creator:this.Creator,system_status:this.system_status};
                     emit(key,value);
                
                   }";

                var reducefunction = @"function (key, values) {
               var reduced = {id:'',folio:'',movement:'',location:'',object:'',total:'',status:'',movementFields:'',CreatedDate:'',CreatedTimeStamp:'',Creator:'',system_status:''};
                var index=0;
              values.forEach(function(value){
              
          
                 
                    if(value.movement != null && reduced.movement ==''){
                    
                    reduced.movement = value.movement;
                  
                    }
                    if(value.location != null && reduced.location == ''){
                    
                    reduced.location = value.location;
                  
                    }
                   
                    if(value.id != null){
                       reduced.id= value.id;
                       reduced.folio = value.folio;
                      
                        reduced.object = value.object;
                        reduced.total = value.total;
                        reduced.status = value.status;
                        reduced.movementFields = value.movementFields;
                        reduced.CreatedDate = value.CreatedDate;
                        reduced.CreatedTimeStamp = value.CreatedTimeStamp;
                        reduced.Creator = value.Creator;
                        reduced.system_status = value.system_status;

                     
                    }
           
            });
           
            return reduced;
          }";

                /*Establece las propiedades a seguir del mapreduce */
                MapReduceOptionsBuilder options = new MapReduceOptionsBuilder();
                options.SetOutput(MapReduceOutput.Inline);
                options.SetOutput(MapReduceOutput.Reduce("result", true));



                /* Realiza los mapreduce sobre el mismo resultado */
                MapReduceResult result = Movements.MapReduce(Movementsfunction, reducefunction, options);
                // result = Locations.MapReduce(Locationsfunction, reducefunction, options);

                result = Demand.MapReduce(Demandfunction, reducefunction, options);
                //    result = Demand.MapReduce(Demandfunction2, reducefunction, options);


                /* resultado en json */
                string results = result.GetResults().ToJson();
                return(results);
            }catch (Exception ex) {
                return(null);
            }
        }
Beispiel #36
0
 public QueryGroupAncestry(string connectionString) : base(connectionString)
 {
     groupCollection = DB.GetCollection <Group>(MongoDbConstants.Collections.Groups);
 }
        /// <summary>
        /// Insert an item, retrying in case of connection errors..
        /// </summary>
        /// <typeparam name="T">The type of the item.</typeparam>
        /// <param name="col">The collection.</param>
        /// <param name="item">The item.</param>
        /// <param name="retryCount">The retry count in case of connection errors.</param>
        /// <param name="throwOnError">Throws an exception on error.</param>
        /// <param name="ignoreDuplicates">If the insert fails because of duplicated id, then returns as success.</param>
        /// <returns></returns>
        public static bool SafeInsert <T> (this MongoCollection col, T item, int retryCount = 2, bool throwOnError = false, bool ignoreDuplicates = false)
        {
            int done = 0;

            // try to update/insert and
            // retry n times in case of connection errors
            do
            {
                try
                {
                    if (col.Insert(item).Ok)
                    {
                        return(true);
                    }
                }
                catch (MongoDuplicateKeyException dup)
                {
                    // duplicate id exception (no use to retry)
                    if (ignoreDuplicates)
                    {
                        return(true);
                    }
                    if (throwOnError)
                    {
                        throw;
                    }
                    break;
                }
                catch (WriteConcernException wcEx)
                {
                    // duplicate id exception (no use to retry)
                    if (wcEx.CommandResult != null && wcEx.CommandResult.Code.HasValue &&
                        (wcEx.CommandResult.Code.Value == 11000 || wcEx.CommandResult.Code.Value == 11001))
                    {
                        if (throwOnError)
                        {
                            throw;
                        }
                        else
                        {
                            return(ignoreDuplicates);
                        }
                    }
                    // retry limit
                    if (throwOnError && done > (retryCount - 1))
                    {
                        throw;
                    }
                }
                // System.IO.IOException ex
                catch
                {
                    if (throwOnError && done > (retryCount - 1))
                    {
                        throw;
                    }
                }
            }while (++done < retryCount);
            // if we got here, the operation have failled
            return(false);
        }
Beispiel #38
0
 public RepositoryMongo(IUnitOfWork unitOfWork)
 {
     _context    = (unitOfWork as MongoDataContext);
     _collection = _context.GetDatabase().GetCollection <T>(typeof(T).Name.ToLower());
 }
Beispiel #39
0
        /// <summary>
        /// Returns an instance of IQueryable{{T}} for a MongoCollection.
        /// </summary>
        /// <typeparam name="T">The type of the returned documents.</typeparam>
        /// <param name="collection">The name of the collection.</param>
        /// <returns>An instance of IQueryable{{T}} for a MongoCollection.</returns>
        public static IQueryable <T> AsQueryable <T>(this MongoCollection collection)
        {
            var provider = new MongoQueryProvider(collection);

            return(new MongoQueryable <T>(provider));
        }
Beispiel #40
0
 public abstract void UpdateDocument(MongoCollection <BsonDocument> collection, BsonDocument document);
 public CSharp522Tests()
 {
     _collection = LegacyTestConfiguration.GetCollection <C>();
     _collection.Drop();
 }
        //Constructors

        public MongoRepository(MongoDatabase db)
        {
            this.collection = db.GetCollection <T>(typeof(T).Name);
        }
Beispiel #43
0
 public ProductRepository(MongoDatabase db)
 {
     _collection           = db.GetCollection <Product>("products");
     _activitiesCollection = db.GetCollection <ProductActivity>("activities");
 }
 public void TestFixtureSetup()
 {
     _server     = Configuration.TestServer;
     _database   = Configuration.TestDatabase;
     _collection = Configuration.GetTestCollection <C>();
 }
Beispiel #45
0
 private PetDatabase(GameApplication app)
 {
     m_App          = app;
     m_PetDocuments = m_App.defaultDatabase.GetCollection <PetDocument>(GameServerSettings.Default.PetCollectionName);
 }
 private static bool OneTimeSetup()
 {
     __collection = LegacyTestConfiguration.GetCollection <GDA>();
     __collection.Drop();
     return(true);
 }
 /// <summary>
 /// Is Exist by Key
 /// </summary>
 /// <param name="mongoCol">Collection</param>
 /// <param name="KeyValue">KeyValue</param>
 /// <param name="Field">KeyField</param>
 /// <returns></returns>
 public static Boolean IsExistByKey(MongoCollection mongoCol, BsonValue KeyValue)
 {
     return(mongoCol.FindAs <BsonDocument>(Query.EQ(KEY_ID, KeyValue)).Count() > 0);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MongoCursor"/> class.
 /// </summary>
 /// <param name="collection">The collection.</param>
 /// <param name="query">The query.</param>
 /// <param name="readConcern">The read concern.</param>
 /// <param name="readPreference">The read preference.</param>
 /// <param name="serializer">The serializer.</param>
 protected MongoCursor(MongoCollection collection, IMongoQuery query, ReadConcern readConcern, ReadPreference readPreference, IBsonSerializer serializer)
     : this(collection, query, readPreference, serializer)
 {
     _readConcern = readConcern;
 }
Beispiel #49
0
 public MongoInsertOptions(MongoCollection collection) : this()
 {
     this.safeMode = collection.Settings.SafeMode;
 }
Beispiel #50
0
        public IHttpActionResult Get([FromUri] Request <Info> request)
        {
            if (request.Type == -1)
            {
                MongoCollection          data           = database.GetCollection("info");
                GroupByBuilder           groupbyBuilder = new GroupByBuilder(new string[] { "CategoryCode", "CategoryName" });
                Dictionary <string, int> dic_F          = new Dictionary <string, int>();
                dic_F["num"] = 0;
                var result_F = data.Group(null, groupbyBuilder, BsonDocument.Create(dic_F), BsonJavaScript.Create("function(doc,prev){prev.num++;}"), BsonJavaScript.Create("function(doc){doc.Count=doc.num;delete doc.num;}")).ToList();

                /*List<InfoAllList> list = new List<InfoAllList>();
                 * if (result_F.Count > 0)
                 * {
                 *  foreach (var item in result_F)
                 *  {
                 *      InfoAllList temp = new InfoAllList();
                 *      temp.CategoryCode = item["CategoryCode"].AsString;
                 *      temp.CategoryName = item["CategoryName"].AsString;
                 *      temp.Count = item["Count"].AsDouble.ToString().ToInt(0);
                 *      list.Add(temp);
                 *  }
                 * }*/
                Response <List <BsonDocument> > rsp = new Response <List <BsonDocument> >();
                rsp.Data = result_F;
                return(Ok(rsp));
            }
            if (request.ID == "SearchInfo")
            {
                Response <List <InfoModel> > rsp = new Response <List <InfoModel> >();
                if (string.IsNullOrEmpty(request.Keyword))
                {
                    return(Ok(rsp));
                }

                List <InfoModel> list = new List <InfoModel>();

                #region 1、在mongodb查询匹配的Info对象
                IMongoQuery query = null;
                if (request.UserName == "Title")
                {
                    query = Query <Info> .Matches(c => c.Title, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "Author")
                {
                    query = Query <Info> .Matches(c => c.Author, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "Source")
                {
                    query = Query <Info> .Matches(c => c.Source, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "Digest")
                {
                    query = Query <Info> .Matches(c => c.Digest, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "KeyWord")
                {
                    query = Query <Info> .Matches(c => c.KeyWord, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "CategoryCode")
                {
                    query = Query <Info> .Matches(c => c.CategoryCode, new BsonRegularExpression(new Regex(request.Keyword)));
                }

                if (query != null)
                {
                    var data = database.GetCollection("info").Find(query).ToList();
                    foreach (var item in data)
                    {
                        InfoModel temp = new InfoModel();
                        temp.InfoId = item.GetValue("_id").ToString();
                        temp.Title  = item.GetValue("Title").ToString();
                        Dictionary dic = getArticleClassNameFoo(item.GetValue("CategoryCode").ToString());
                        if (dic != null)
                        {
                            temp.ArticleClass = dic.value;
                        }
                        temp.ArticleCategory = item.GetValue("CategoryName").ToString();
                        temp.Author          = item.GetValue("Author").ToString();
                        string   extStr = item.GetValue("ArticleType").ToString();
                        string[] arr    = extStr.Split('、');
                        if (arr.Length > 0)
                        {
                            temp.FileType = arr[0];
                        }
                        else
                        {
                            temp.FileType = "1176708";
                        }

                        string fileUrl    = "";
                        string dbFileName = item.GetValue("FileName").AsString.Trim();
                        if (!string.IsNullOrEmpty(dbFileName))
                        {
                            fileUrl = "/Upload/" + dbFileName;
                        }

                        /*if (item.GetValue("FileName").ToString().Trim().EndsWith(".xls") || item.GetValue("FileName").ToString().Trim().EndsWith(".xlsx"))
                         * {
                         *  fileUrl += "XLS/";
                         * }
                         * fileUrl += item.GetValue("FileId").ToString().Trim() + "/" + item.GetValue("FileName").ToString().Trim();*/
                        temp.FilePath    = fileUrl;
                        temp.PublishTime = item.GetValue("PublishTime").AsDateTime;
                        temp.ArticleType = item.GetValue("ArticleType").AsString;
                        temp.ModifyTime  = item.GetValue("ModifyTime").AsDateTime;
                        temp.ModifyUser  = item.GetValue("ModifyUser").AsString;

                        list.Add(temp);
                    }
                }
                #endregion

                if (request.UserName == "Content")
                {
                    #region 2、查询solr服务器来搜索文件内容
                    string      q      = "text:" + request.Keyword;
                    string      url    = SolrUrl + "select?q=" + HttpUtility.UrlEncode(q) + "&rows=1000000&wt=json&_=" + StringExtension.getTimeStamp(DateTime.Now);
                    HttpClient  client = new HttpClient();
                    string      result = client.GetStringAsync(url).Result;
                    SolrContext sc     = result.JsonDeserialize <SolrContext>();
                    #endregion

                    #region 3、通过solr搜索结果来匹配数据库
                    foreach (var item in sc.response.docs)
                    {
                        FileInfo fi      = new FileInfo(item.uri);
                        string   dirName = fi.Directory.Name;
                        var      query2  = Query.EQ("FileId", dirName);
                        Info     info    = database.GetCollection("info").FindAs <Info>(query2).FirstOrDefault();
                        if (info == null)
                        {
                            continue;
                        }
                        if (info.FileName != fi.Name)
                        {
                            continue;
                        }

                        InfoModel temp = new InfoModel();
                        temp.InfoId = info._id.ToString();
                        temp.Title  = info.Title;
                        Dictionary dic = getArticleClassNameFoo(info.CategoryCode);
                        if (dic != null)
                        {
                            temp.ArticleClass = dic.value;
                        }
                        temp.ArticleCategory = info.CategoryName;
                        temp.Author          = info.Author;

                        string   extStr = info.ArticleType;
                        string[] arr    = extStr.Split('、');
                        if (arr.Length > 0)
                        {
                            temp.FileType = arr[0];
                        }
                        else
                        {
                            temp.FileType = "1176708";
                        }

                        string fileUrl = "/Upload/";
                        if (fi.Extension == ".xls" || fi.Extension == ".xlsx")
                        {
                            fileUrl += "XLS/";
                        }
                        fileUrl      += info.FileId + "/" + info.FileName;
                        temp.FilePath = fileUrl;

                        if (list.Contains(temp))
                        {
                            continue;
                        }
                        list.Add(temp);
                    }
                    #endregion
                }

                rsp.Data = list;
                if (request.UserName == "CategoryCode")
                {
                    List <InfoModel> result = list.Skip((request.CurrentPage - 1) * PageSize).Take(PageSize).ToList();
                    int count = list.Count / PageSize;
                    if (list.Count % PageSize > 0)
                    {
                        count += 1;
                    }
                    rsp.PagesCount = count;
                    rsp.Data       = result;
                }

                return(Ok(rsp));
            }
            else
            {
                Guid g = new Guid();
                if (Guid.TryParse(request.Keyword, out g))
                {
                    Dictionary    dic     = _dictionary.GetDictionaryById(g.ToString());
                    List <string> nodeIds = new List <string>();
                    nodeIds.Add(dic.nodeId);
                    Foo(nodeIds, dic);

                    Response <List <Info> > response = new Response <List <Info> >();
                    var         list   = database.GetCollection <Info>("info").FindAll().ToList();
                    List <Info> result = new List <Info>();
                    foreach (string item in nodeIds)
                    {
                        Info temp = list.Find(p => p.CategoryCode == item);
                        if (temp != null)
                        {
                            result.Add(temp);
                        }
                    }
                    response.Data = result;
                    return(Ok(response));
                }
                else
                {
                    Response <List <Info> > response = new Response <List <Info> >();
                    var list = database.GetCollection <Info>("info").FindAll().ToList();
                    if (!string.IsNullOrEmpty(request.Keyword))
                    {
                        list = list.FindAll(p => p.Title.Contains(request.Keyword) || p.Html.Contains(request.Keyword) || p.Author.Contains(request.Keyword));
                    }
                    response.Data = list;
                    return(Ok(response));
                }
            }
        }
Beispiel #51
0
        /// <summary>
        /// Load a list of images that were uploaded after the passed in date object
        /// </summary>
        /// <param name="lastKnownUploadDate"></param>
        /// <returns></returns>
        public static List <Image> LoadRecentlyUploaded(DateTime lastKnownUploadDate)
        {
            MongoCollection <Image> Collection = Execute.GetCollection <Image>(COLLECTION_NAME);

            return((List <Image>)(from e in Collection.AsQueryable <Image>() where e.ModifiedDateUTC >= lastKnownUploadDate orderby e.ModifiedDateUTC descending select e).ToList());
        }
Beispiel #52
0
 public MongoInsertOptions(MongoCollection collection) : this()
 {
     _writeConcern = collection.Settings.WriteConcern;
 }
Beispiel #53
0
 public MongoModel(String name, Dictionary <string, string> dbConf = null, Boolean authAgainstAdmin = false)
 {
     conection  = (MongoConection)Conection.getConection(dbConf);
     collection = conection.getCollection(name, authAgainstAdmin);
 }
Beispiel #54
0
 public LogRepository(MongoCollection <T> mongoCollection)
 {
     _mongoCollection = mongoCollection;
 }
 public void Setup()
 {
     _server     = Configuration.TestServer;
     _collection = Configuration.TestCollection;
 }
Beispiel #56
0
        /// <summary>
        /// Load all of the previously uploaded images
        /// </summary>
        /// <returns></returns>
        public static List <Image> LoadAll()
        {
            MongoCollection <Image> Collection = Execute.GetCollection <Image>(COLLECTION_NAME);

            return((List <Image>)(from e in Collection.AsQueryable <Image>() orderby e.ModifiedDateUTC descending select e).ToList());
        }
 public void TestFixtureSetUpAttribute()
 {
     _collection = Configuration.TestCollection;
 }
Beispiel #58
0
 public override void Initialize(string name, NameValueCollection config)
 {
     this.mongoCollection = MongoDatabase.Create(ConnectionHelper.GetDatabaseConnectionString(config)).GetCollection(config["collection"] ?? "OutputCache");
     this.mongoCollection.EnsureIndex("Key");
     base.Initialize(name, config);
 }
Beispiel #59
0
        private void RunTroToPayrollExport()
        {
            logger.LogDebug("Starting TRO to payroll export thread.");

            {
                var sw = new Stopwatch();

                DateTime lockDayOffset;
                DateTime exportDayOffset;
                long     payrollLockOffset   = 0; // = 32400000;  //9h
                long     payrollExportOffset = 0;;
                long     stopwatchInterval   = (long)config["automaticexportinterval"].GetValueOrDefault(1800000);

                bool lockAutomatically = (bool)config["lockautomatically"].GetValueOrDefault(false);
                if (lockAutomatically)
                {
                    //Default 3h -> ms
                    payrollLockOffset = (long)config["payrolllockoffset"].GetValueOrDefault(10800000);
                    sw.Start();
                }
                bool exportAutomatically = (bool)config["exportautomatically"].GetValueOrDefault(false);
                if (exportAutomatically)
                {
                    //Default 1d -> ms
                    payrollExportOffset = (long)config["payrollexportoffset"].GetValueOrDefault(86400000);
                    if (!sw.IsRunning)
                    {
                        sw.Start();
                    }
                }

                while (!stopping.WaitOne(5021))
                {
                    try
                    {
                        lock (payrollExportLock)
                        {
                            exportTask = PayrollExport.GetNextPayrollExportTask(database);
                            if (exportTask != null)
                            {
                                logger.LogInfo("Handling next payroll export task");
                                payrollExport = new PayrollExport(logger, IntegrationTroToPayrollFolder, database, config);
                                payrollExport.ExportDocuments(exportTask);
                            }
                            //Check for locking payroll
                            if (lockAutomatically || exportAutomatically)
                            {
                                if (sw.Elapsed.TotalMilliseconds > stopwatchInterval)
                                {
                                    if (lockAutomatically)
                                    {
                                        lockDayOffset = DateTime.Today + TimeSpan.FromMilliseconds(payrollLockOffset);
                                        if (lockDayOffset < DateTime.Now)
                                        {
                                            var andQueries = new List <IMongoQuery>();
                                            andQueries.Add(Query.LTE("enddate", lockDayOffset));
                                            andQueries.Add(Query.EQ("locked", false));
                                            andQueries.Add(Query.EQ("automaticallylocked", false));

                                            MongoCollection <BsonDocument> collection = database.GetCollection("payrollperiod");
                                            MongoCursor <BsonDocument>     cursor     = collection.Find(Query.And(andQueries));
                                            if (cursor.Count() > 0)
                                            {
                                                foreach (var item in cursor)
                                                {
                                                    if ((DateTime)item["enddate"] < lockDayOffset)
                                                    {
                                                        logger.LogInfo("Automatically locking payroll period", item[DBDocument.Id]);
                                                        item["automaticallylocked"] = true;
                                                        item["locked"] = true;
                                                        item["automaticallylocked_time"] = DateTime.UtcNow;
                                                        collection.Save(item, WriteConcern.Acknowledged);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (exportAutomatically)
                                    {
                                        var andQueries = new List <IMongoQuery>();
                                        exportDayOffset = DateTime.Today + TimeSpan.FromMilliseconds(payrollExportOffset);
                                        andQueries.Add(Query.LTE("enddate", exportDayOffset));
                                        andQueries.Add(Query.EQ("locked", true));
                                        andQueries.Add(Query.EQ("automaticallyexported", false));

                                        MongoCollection <BsonDocument> collection = database.GetCollection("payrollperiod");
                                        MongoCursor <BsonDocument>     cursor     = collection.Find(Query.And(andQueries));
                                        if (cursor.Count() > 0)
                                        {
                                            if (exportDayOffset < DateTime.Now)
                                            {
                                                foreach (var item in cursor)
                                                {
                                                    logger.LogInfo("Add automatical export task for payroll", item[DBDocument.Id]);
                                                    exportTask    = PayrollExport.GetNextPayrollExportTask(database, true, item);
                                                    payrollExport = new PayrollExport(logger, IntegrationTroToPayrollFolder, database, config);
                                                    payrollExport.ExportDocuments(exportTask);
                                                    item["automaticallyexported"] = true;
                                                    collection.Save(item, WriteConcern.Acknowledged);
                                                }
                                            }
                                        }
                                    }
                                    //Reset stopwatch for next interval
                                    sw.Reset();
                                    sw.Start();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError("Failed import entries to payroll.", ex);
                    }

                    stopping.WaitOne(payrollExportPollingInterval);
                }
            }

            logger.LogError("Tro to payroll export thread stopping.");
        }
Beispiel #60
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the MongoLinqQuery class.
 /// </summary>
 /// <param name="collection">The collection being queried.</param>
 /// <param name="documentType">The document type being queried.</param>
 protected TranslatedQuery(MongoCollection collection, Type documentType)
 {
     _collection   = collection;
     _documentType = documentType;
 }