Пример #1
0
 // GET api/values
 public IEnumerable<Car> Get()
 {
     IRepository<Car> carRepository = new MongoDbRepository<Car>();
     var arr = carRepository.GetAll().ToArray();
     return arr;
     //return new string[] { "value1", "value2" };
 }
Пример #2
0
        public void Add_Log_Item()
        {
            try
            {
                MongoDbRepository<Log> logRepository = new MongoDbRepository<Log>();
                logRepository.DeleteAll();

                User user = new User();
                user.Id = 1;
                user.UserGuid = Guid.NewGuid();
                user.UserName = "******";
                Log item = new Log
                {
                    CreatedByTime = DateTime.UtcNow,
                    FullMessage = "This is a test message",
                    //Id = guid,
                    IpAddress = WebExtensions.CurrentMachineIPv4(),
                    LogLevel = LogLevel.Info,
                    ShortMessage = "Test",
                    User = user,
                    UserId = user.Id
                };

                logRepository.Insert(item);

                MongoDbRepository<Log> logRepository2 = new MongoDbRepository<Log>();
                Assert.AreEqual(logRepository2.Table.Count(), 1);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #3
0
        static void Main(string[]args)
        {
            var car = new Car() {
                Manufacturer = "Mercedes-Benz",
                Model = "New A Class",
                Colour = "Gray"
            };

            var carRepository = new MongoDbRepository<Car>();

            Console.WriteLine("Inserting car");
            var insertResult = carRepository.Insert(car);

            Console.WriteLine("Updating car");
            car.Colour = "Blue";
            var updateResult = carRepository.Update(car);

            Console.WriteLine("Search cars");
            var searchResult = carRepository.SearchFor(c => c.Colour == "Blue");

            Console.WriteLine("Get all cars");
            var getAllResult = carRepository.GetAll();

            Console.WriteLine("Getting car by id");
            var getByIdResult = carRepository.GetById(car.Id);

            Console.WriteLine("Deleting car");
            var deleteResult = carRepository.Delete(car);

            Console.Write("Press any key to continue...");
            Console.ReadKey();
        }
Пример #4
0
        static async void Run()
        {
            var connectionString = "mongodb://localhost";
            var dbName = "books";
            var db = GetDatabase(connectionString, dbName);

            IRepository<Book> repo = new MongoDbRepository<Book>(db);

            var input = ReadInput();

            var patrickRothfuss = new Author(input[2], input[3]);
            await repo.Add(new Book(input[0], input[1], patrickRothfuss));

            (await repo.All())
                    .ToList()
                    .ForEach(Console.WriteLine);


            //Deleting
            var first = (await repo.All())
                    .FirstOrDefault();

            Console.WriteLine("Deleting {0}", first.Title);
            await repo.Delete(first);

            Console.WriteLine("{0} deleted", first.Title);
            Console.WriteLine("---------------");
            (await repo.All())
                    .ToList()
                    .ForEach(Console.WriteLine);
        }
Пример #5
0
        // This method copies the Customer objects with the orders attached to the Mongo db database
        private static void SetUpMongoDbData()
        {
            var mongoDb = GetMongoDatabase();
            mongoDb.Drop();
            mongoDb = GetMongoDatabase();

            using (var efQueryRepository = new EntityFrameworkQueryRepository(new NRepository_NorthwindContext()))
            {
                // no proxy objects please
                var dbContext = (DbContext)efQueryRepository.ObjectContext;
                dbContext.Configuration.ProxyCreationEnabled = false;

                // load customers with orders attached
                var customers = efQueryRepository.GetEntities<Customer>(
                    new EagerLoadingQueryStrategy<Customer>(
                        p => p.Orders)).ToList();

                // MongoDbRepository immediately calls the db when adding, modifying or deleting data. Use this implementation
                // to both set and get the concerns. (MongoDbUnitOfWorkRepository will only return the concerns after all the items have been saved )
                using (IRepository mongoRepository = new MongoDbRepository(mongoDb))
                {
                    // Copy Ef data to mongo db
                    customers.ForEach(customer =>
                    {
                        //var result = mongoRepository.AddWithConcern(customer)
                        mongoRepository.Add(customer);
                    });
                }
            }
        }
        public void Load_non_existing_training()
        {
            IRepository sut = new MongoDbRepository(CONNECTIONSTRING);

            Exception ex = null;
            sut.LoadTrainingByMatchcode("xyz-nonexisting", null, _ => ex = _);

            Assert.IsNotNull(ex);
            Console.WriteLine("Exception thrown as expected: {0}", ex.Message);
        }
        public void Create_training()
        {
            IRepository sut = new MongoDbRepository(CONNECTIONSTRING);

            Training result = null;
            sut.CreateTraining("sometraining", "sometrainer", _ => result = _, null);

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Id);
            Assert.AreEqual("sometraining", result.Matchcode);
            Assert.AreEqual("sometrainer", result.TrainerMatchcode);
        }
        //        [Test]
        public void CheckAddAndDeleteFoMongoCommandRepository()
        {
            var mongoDatabase = CreateEmptyMongoDatabase();
            var repository = new MongoDbRepository(mongoDatabase);

            var account = new SimpleAccount("xyz");
            repository.GetEntities<SimpleAccount>(p => p.Name == account.Name).Any().ShouldEqual(false);
            repository.Add(account);
            repository.GetEntities<SimpleAccount>(p => p.Name == account.Name).Any().ShouldEqual(true);

            repository.Delete(account);
            repository.GetEntities<SimpleAccount>(p => p.Name == account.Name).Any().ShouldEqual(false);
        }
        public void Load_training_by_id()
        {
            IRepository sut = new MongoDbRepository(CONNECTIONSTRING);

            Training t = null;
            sut.CreateTraining("sometrainingLoad", "sometrainerLoad", _ => t = _, null);

            Training result = null;
            sut.LoadTrainingByMatchcode(t.Id, _ => result = _, null);

            Equalidator.AreEqual(t.Id, result.Id);
            Assert.AreEqual("sometrainerLoad", result.TrainerMatchcode);
        }
        public void TestFixtureSetUp()
        {
            var definitionProviders = TestSupport.SetupDefinitionProviders(new DefinitionMap(), typeof(NormalPage), typeof(NormalItem));
            var proxies = new N2.Persistence.Proxying.InterceptingProxyFactory();
            proxies.Initialize(definitionProviders.SelectMany(dp => dp.GetDefinitions()));

            itemRepository = new MongoContentItemRepository(
                databaseProvider = new MongoDatabaseProvider(TestSupport.CreateDependencyInjector(), proxies, new N2.Configuration.ConfigurationManagerWrapper("n2mongo"),
                definitionProviders,
                new AdaptiveContext()));

            persister = new ContentPersister(TestSupport.SetupContentSource(itemRepository), itemRepository);
            IRepository<ContentVersion> versionRepository = new MongoDbRepository<ContentVersion>(databaseProvider);
            repository = TestSupport.CreateVersionRepository(
                ref persister,
                ref activator,
                ref versionRepository,
                typeof(NormalPage), typeof(NormalItem));
            drafts = new DraftRepository(repository, new FakeCacheWrapper());
        }
        public void CanPushDataToActualMongoDb()
        {
            var characterRepository          = new MongoDbRepository <ICharacter>(MongoDatabase);
            var movementRepository           = new MongoDbRepository <IMovement>(MongoDatabase);
            var moveRepository               = new MongoDbRepository <IMove>(MongoDatabase);
            var characterAttributeRepository = new MongoDbRepository <ICharacterAttributeRow>(MongoDatabase);
            var uniqueDataRepository         = new MongoDbRepository <IUniqueData>(MongoDatabase);

            //real api services using mocked repos
            var mockQueryMappingService   = new Mock <IQueryMappingService>().Object;
            var dtoProvider               = new DefaultDtoProvider();
            var movementService           = new DefaultMovementService(movementRepository, mockQueryMappingService);
            var moveService               = new DefaultMoveService(moveRepository, mockQueryMappingService);
            var characterAttributeService = new DefaultCharacterAttributeService(characterAttributeRepository, new Mock <ICharacterAttributeNameProvider>().Object);
            var uniqueDataService         = new DefaultUniqueDataService(uniqueDataRepository, mockQueryMappingService);
            var characterService          = new DefaultCharacterService(characterRepository, dtoProvider,
                                                                        movementService, characterAttributeService, moveService, uniqueDataService, string.Empty);

            //real scraping from web to get data
            var captainFalcon = Characters.CaptainFalcon;

            _characterDataScraper.PopulateCharacterFromWeb(captainFalcon);

            int previousCount = characterRepository.GetAll().Count();

            //insert data into mock repos using api services
            var seeder = new DefaultSeeder(_characterDataScraper);

            seeder.SeedCharacterData(captainFalcon, characterService, movementService,
                                     moveService, characterAttributeService, uniqueDataService);

            //assert data can be retrieved
            Assert.That(characterRepository.GetAll().Count(), Is.EqualTo(previousCount + 1));
            Assert.That(moveRepository.GetAll().Count(), Is.GreaterThan(0));
            Assert.That(movementRepository.GetAll().Count(), Is.GreaterThan(0));
            Assert.That(characterAttributeRepository.GetAll().Count(), Is.GreaterThan(0));
            //Assert.That(uniqueDataRepository.GetAll().Count(), Is.GreaterThan(0)); //no unique data for this character
        }
        /// <summary>
        /// 保存MarkDown
        /// </summary>
        /// <param name="strArticleId"></param>
        /// <param name="strContent"></param>
        /// <param name="OwnerId"></param>
        public static void SaveMarkDownVersion(string strArticleId, string strContent, string OwnerId, RevisionType step)
        {
            IMongoQuery ArticleIdQuery     = Query.EQ(nameof(ArticleID), strArticleId);
            IMongoQuery RevisionQuery      = Query.EQ(nameof(Revision), step);
            IMongoQuery MarkDownExistQuery = Query.EQ(nameof(ContentType), MarkDown);
            var         FirstFind          = MongoDbRepository.GetFirstRec <ArticleContent>(Query.And(ArticleIdQuery, RevisionQuery, MarkDownExistQuery));

            if (FirstFind != null)
            {
                FirstFind.Content     = strContent;
                FirstFind.ContentType = MarkDown;
                MongoDbRepository.UpdateRec(FirstFind);
            }
            else
            {
                ArticleContent NewFirst = new ArticleContent();
                NewFirst.ArticleID   = strArticleId;
                NewFirst.Revision    = step;
                NewFirst.Content     = strContent;
                NewFirst.ContentType = MarkDown;
                InsertArticleContent(NewFirst, OwnerId);
            }
        }
Пример #13
0
        //
        // GET: /Home/
        public ActionResult Index()
        {
            var acct = new Account()
            {
                Email = "*****@*****.**",
                Username = "******",
                Password = "******",
                Name = "Saulo",
                Lastname = "Valdivia",
                Phone = "69549199",
                Ci = "6472568",
                Gender = "M",
                Country = "Bolivia",
                City = "Cochabamba"
            };

            var acctRepository = new MongoDbRepository<Account>();

            Console.WriteLine("Inserting Account");
            var insertResult = acctRepository.GetAll();

            return View();
        }
        public void Update()
        {
            string beforeUpdate = null;
            string afterUpdate  = null;

            User usr = new User()
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            beforeUpdate = usr.Email;
            MongoDbRepository <User> userRepository = new MongoDbRepository <User>();
            User result = userRepository.Insert(usr);

            result.Email = "*****@*****.**";

            userRepository.Update(result);

            beforeUpdate = result.Email;

            Assert.AreNotEqual(beforeUpdate, afterUpdate);
        }
Пример #15
0
        /// <summary>
        /// 模拟关注
        /// </summary>
        /// <param name="MinPerAccount"></param>
        /// <param name="MaxPerAccount"></param>
        public static void SimulateFocus(int MinPerAccount = 20, int MaxPerAccount = 20)
        {
            MongoDbRepository.DrapCollection(Focus.CollectionName);
            MongoDbRepository.SetIndex(Focus.CollectionName, nameof(Focus.OwnerId));
            var users   = MongoDbRepository.GetRecList <GithubAccount>();
            int usercnt = users.Count;

            foreach (var u in users)
            {
                Random r = new Random();
                int    x = r.Next(MinPerAccount, MaxPerAccount + 1);
                //if (x == 0) x = r.Next(50);
                System.Diagnostics.Debug.WriteLine(u.Sn + ":" + x);
                for (int i = 0; i < x; i++)
                {
                    var uid = r.Next(1, usercnt + 1);
                    if (uid.ToString(EntityBase.SnFormat) != u.Sn)
                    {
                        Focus.FocusAccount(u.Sn, uid.ToString(EntityBase.SnFormat));
                    }
                }
            }
        }
Пример #16
0
        //
        // GET: /Home/

        public ActionResult Index()
        {
            var acct = new Account()
            {
                Email    = "*****@*****.**",
                Username = "******",
                Password = "******",
                Name     = "Saulo",
                Lastname = "Valdivia",
                Phone    = "69549199",
                Ci       = "6472568",
                Gender   = "M",
                Country  = "Bolivia",
                City     = "Cochabamba"
            };

            var acctRepository = new MongoDbRepository <Account>();

            Console.WriteLine("Inserting Account");
            var insertResult = acctRepository.GetAll();

            return(View());
        }
Пример #17
0
        public static IRepository BuildMongoDbRepository(string url, bool reload = true)
        {
            var mongoUrl = new MongoUrl(url);
            var db       = new MongoClient(mongoUrl).GetServer();

            if (reload)
            {
                if (db.DatabaseExists(mongoUrl.DatabaseName))
                {
                    db.DropDatabase(mongoUrl.DatabaseName);
                }
            }

            if (!BsonClassMap.IsClassMapRegistered(typeof(IncEntityBase)))
            {
                BsonClassMap.RegisterClassMap <IncEntityBase>(map => map.UnmapProperty(r => r.Id));
            }
            var session = new MongoDatabaseDisposable(db.GetDatabase(mongoUrl.DatabaseName));
            var buildMongoDbRepository = new MongoDbRepository(/*Pleasure.MockStrictAsObject<IMongoDbSessionFactory>(mock => mock.Setup(r => r.GetCurrent()).Returns(session))*/);

            buildMongoDbRepository.SetProvider(session);
            return(buildMongoDbRepository);
        }
        /// <summary>
        /// 保存HTML
        /// </summary>
        /// <param name="strArticleId"></param>
        /// <param name="strContent"></param>
        /// <param name="OwnerId"></param>
        public static void SaveHTMLVersion(string strArticleId, string strContent, string OwnerId)
        {
            //HTML只保存当前版本,为了制作PDF用
            IMongoQuery ArticleIdQuery = Query.EQ(nameof(ArticleID), strArticleId);
            IMongoQuery HTMLExistQuery = Query.EQ(nameof(ContentType), HTML);
            var         FirstFind      = MongoDbRepository.GetFirstRec <ArticleContent>(Query.And(ArticleIdQuery, HTMLExistQuery));

            if (FirstFind != null)
            {
                FirstFind.Content     = strContent;
                FirstFind.ContentType = HTML;
                MongoDbRepository.UpdateRec(FirstFind);
            }
            else
            {
                ArticleContent NewFirst = new ArticleContent();
                NewFirst.ArticleID   = strArticleId;
                NewFirst.Revision    = RevisionType.Current;
                NewFirst.Content     = strContent;
                NewFirst.ContentType = HTML;
                InsertArticleContent(NewFirst, OwnerId);
            }
        }
Пример #19
0
        public async void GetRecentlyAdded_NewEntites_True()
        {
            var mongoDbRepository = new MongoDbRepository <Tweet>(_connectionString, _databaseName, _collectionName);

            var tweets = new List <Tweet>()
            {
                new Tweet
                {
                    Content = "This is a tweet"
                },
                new Tweet
                {
                    Content = "This is another tweet"
                }
            };

            await _database.GetCollection <Tweet>(_collectionName).InsertManyAsync(tweets);

            var all = await _database.GetCollection <Tweet>(_collectionName).Find(FilterDefinition <Tweet> .Empty).ToListAsync();

            var result = await mongoDbRepository.Get();

            Assert.Equal <RootEntity>(all, result, new RootEntityComparer());
        }
        //        [Test]
        public void Paging()
        {
            var mongoDatabase = CreateEmptyMongoDatabase();
            var repository    = new MongoDbRepository(mongoDatabase);

            repository.Add(new MySimpleAccount("xyz", DateTime.Today.AddDays(-1), 1)
            {
                Weigth = 1
            });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today.AddDays(-1), 2)
            {
                Weigth = 2
            });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today.AddDays(-1), 3)
            {
                Weigth = 3
            });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today, 4)
            {
                Weigth = 4
            });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today, 5)
            {
                Weigth = 5
            });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today, 6)
            {
                Weigth = 6
            });

            var rowCountFunc = default(Func <int>);
            var docs         = repository.GetEntities <MySimpleAccount>(new PagingQueryStrategy(2, 2, out rowCountFunc)).ToList();

            rowCountFunc().ShouldEqual(6);
            docs.Count().ShouldEqual(2);
        }
Пример #21
0
        public void Trying_to_update_non_existent_training_fails()
        {
            IRepository sut = new MongoDbRepository(CONNECTIONSTRING);

            Training t = null;
            sut.CreateTraining("sometrainingUpdate2", "sometrainerUpdate2", _ => t = _, null);
            _col.RemoveAll();

            t.TrainerMatchcode = "this change wont make it";

            Exception ex = null;
            sut.UpdateTraining(t, null, _ => ex = _);

            Assert.IsInstanceOf<InvalidOperationException>(ex);
            Console.WriteLine("Exception thrown as expected: {0}", ex.Message);

        }
Пример #22
0
        public void Load_trainings()
        {
            IRepository sut = new MongoDbRepository(CONNECTIONSTRING);

            var trainings = sut.LoadTrainings("sometrainer");
            Assert.AreEqual(0, trainings.Length);

            sut.CreateTraining("abc", "sometrainer", _ => { }, ex => { throw ex; });
            sut.CreateTraining("xyz", "sometrainer", _ => { }, ex => { throw ex; });

            var matchcodes = sut.LoadTrainings("sometrainer").Select(t => t.Matchcode).ToArray();
            Assert.That(matchcodes, Is.EquivalentTo(new[] { "abc", "xyz" }));
        }
Пример #23
0
 /// <summary>
 /// 修改消息
 /// </summary>
 /// <param name="OldSiteMessage"></param>
 public static void UpdateSiteMessage(SiteMessage OldSiteMessage)
 {
     MongoDbRepository.UpdateRec(OldSiteMessage);
 }
Пример #24
0
        public void Update_training()
        {
            IRepository sut = new MongoDbRepository(CONNECTIONSTRING);

            Training t = null;
            sut.CreateTraining("sometrainingUpdate", "sometrainerUpdate", _ => t = _, null);

            t.TrainerMatchcode = "new trainer matchcode";
            sut.UpdateTraining(t, () => Console.WriteLine("Updated training: " + t.Matchcode), null);

            Training result = null;
            sut.LoadTrainingByMatchcode("sometrainingUpdate", _ => result = _, null);
            Assert.AreEqual("new trainer matchcode", result.TrainerMatchcode);
        }
        public void CheckSaveInterceptor2()
        {
            var repository = new MongoDbRepository(CreateEmptyMongoDatabase());
            //BsonDocument nested = new BsonDocument {
            //{ "name", "JJK" },
            //{ "address", new BsonDocument {
            //    { "street", "123 Main St." },
            //    { "city", "Centerville" },
            //    { "state", "PA" },
            //    { "zip", 12345}
            //}}};

            var crappy = new SimpleAccount("JK2");
            crappy.SimpleAccount2 = new SimpleAccount("XXX");
            repository.Add(crappy);

            // Create Single Update!!!!!!!!!!!!


            var result3 = repository.ModifyAll<SimpleAccount>(
                new ExpressionSpecificationQueryStrategy<SimpleAccount>(p => p.Name == "JK2"),
                    new MongoUpdateItem<SimpleAccount>(p => p.DOB, DateTime.Today.AddDays(77777)),
                    new MongoUpdateItem<SimpleAccount>(p => p.SimpleAccount2.Name, "XCC"),
                    new MongoUpdateItem<SimpleAccount>(p => p.SimpleAccount2.Weigth, 1236));

            //            Update.Set("DOB", DateTime.Today.AddDays(99999));
        }
Пример #26
0
 /// <summary>
 /// 删除消息
 /// </summary>
 /// <param name="DropSiteMessage"></param>
 public static void DropSiteMessage(SiteMessage DropSiteMessage)
 {
     MongoDbRepository.DeleteRec(DropSiteMessage);
 }
Пример #27
0
        /// <summary>
        /// 获得专题
        /// </summary>
        /// <param name="accountid"></param>
        /// <returns></returns>
        public static Topic GetTopicByAccountId(string accountid)
        {
            IMongoQuery TopicQuery = Query.EQ(nameof(OwnerId), accountid);

            return(MongoDbRepository.GetFirstRec <Topic>(TopicQuery));
        }
Пример #28
0
 /// <summary>
 ///     返回所有标签
 /// </summary>
 /// <returns>官方标签</returns>
 public static List <Tag> GetAllTags()
 {
     return(MongoDbRepository.GetRecList <Tag>());
 }
Пример #29
0
 /// <summary>
 /// 插入文章表示综合体
 /// </summary>
 /// <param name="NewArticleBody">文章表示综合体</param>
 public static ObjectId InsertArticleBody(ArticleBody NewArticleBody)
 {
     return(MongoDbRepository.InsertCacheRec(NewArticleBody));
 }
Пример #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ContactService"/> class.
 /// </summary>
 /// <param name="mongoDbRepository">The mongo database repository.</param>
 public ContactService(MongoDbRepository mongoDbRepository)
 {
     this.MongoDbRepository = mongoDbRepository;
 }
Пример #31
0
        private static void TestToDoOperations()
        {
            var job1 = new ToDo()
            {
                Title = "iTracker on App Store",
                Description = "A GPS based telemetry logger that stores real-time location data at user defined intervals. Journey information can be displayed on an interactive map or through the built-in CSV and GPX viewer. Routes exported via email can be imported into third party software that support both Comma-separated and GPS eXchange file formats. Waypoints can be graphically or manually bookmarked, then imported and exported via the clipboard.",
                Uuid = "FA507E77-D86D-46FE-885F-A2E4E48266E4",
                AssignedDate = "16/10/13",
                EstimatedDate = "01/11/13",
                CompletedDate = "03/12/2013",
                Status = "Ready for Sale",
                Image = "",
                Signature = "iPhone"
            };

            var job1b = new ToDo()
            {
                Title = "iTracker on App Store",
                Description = "A GPS based telemetry logger that stores real-time location data at user defined intervals. Journey information can be displayed on an interactive map or through the built-in CSV and GPX viewer. Routes exported via email can be imported into third party software that support both Comma-separated and GPS eXchange file formats. Waypoints can be graphically or manually bookmarked, then imported and exported via the clipboard.",
                Uuid = "DFD00AD7-BD17-4528-B6AD-DBBC44AE7FC9",
                AssignedDate = "16/10/13",
                EstimatedDate = "01/11/13",
                CompletedDate = "03/12/2013",
                Status = "Ready for Sale",
                Image = "",
                Signature = "iOS Simulator"
            };

            var job2 = new ToDo()
            {
                Title = "iWebsearch on App Store",
                Description = "Designed to speed up the process required when submitting a single search term to multiple search engines. By simply tapping on the desired search engine the user can scroll through the list then repeat the process by navigating back and tapping an alternative search engine. Bookmarked results can be viewed then exported via email in a Comma-separated format.",
                Uuid = "FA507E77-D86D-46FE-885F-A2E4E48266E4",
                AssignedDate = "03/12/2013",
                EstimatedDate = "06/12/2013",
                CompletedDate = "12/12/2013",
                Status = "Ready for Sale",
                Image = "",
                Signature = "iPhone"
            };

            var job2b = new ToDo()
            {
                Title = "iWebsearch on App Store",
                Description = "Designed to speed up the process required when submitting a single search term to multiple search engines. By simply tapping on the desired search engine the user can scroll through the list then repeat the process by navigating back and tapping an alternative search engine. Bookmarked results can be viewed then exported via email in a Comma-separated format.",
                Uuid = "DFD00AD7-BD17-4528-B6AD-DBBC44AE7FC9",
                AssignedDate = "03/12/2013",
                EstimatedDate = "06/12/2013",
                CompletedDate = "-",
                Status = "In Review",
                Image = "",
                Signature = "iOS Simulator"
            };

            var jobRepository = new MongoDbRepository<ToDo>();

            Console.WriteLine("Inserting job1 for iPhone");
            var insertResult1 = jobRepository.Insert(job1);

            Console.WriteLine("Inserting job1b for iOS Simulator");
            var insertResult3 = jobRepository.Insert(job1b);

            Console.WriteLine("Inserting job2 for iPhone");
            var insertResult2 = jobRepository.Insert(job2);

            Console.WriteLine("Inserting job2b for iOS Simulator");
            var insertResult4 = jobRepository.Insert(job2b);

            Console.WriteLine("Updating job2B status");
            job2b.Status = "Ready for Sale";
            var updateResult = jobRepository.Update(job2b);

            Console.WriteLine("Updating job2B completed date");
            job2b.CompletedDate = "12/12/2013";
            var updateResult2 = jobRepository.Update(job2b);

            Console.WriteLine("Searching jobs for 'In Review' Status");
            var searchResult = jobRepository.SearchFor(c => c.Status == "Ready for Sale");

            Console.WriteLine("Get all jobs");
            var getAllResult = jobRepository.GetAll();

            Console.WriteLine("Getting job by id");
            var getByIdResult = jobRepository.GetById(job1.Id);

            //Console.WriteLine("Deleting job");
            //var deleteResult = jobRepository.Delete(job2b);
        }
        //        [Test]
        public void Paging()
        {
            var mongoDatabase = CreateEmptyMongoDatabase();
            var repository = new MongoDbRepository(mongoDatabase);

            repository.Add(new MySimpleAccount("xyz", DateTime.Today.AddDays(-1), 1) { Weigth = 1 });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today.AddDays(-1), 2) { Weigth = 2 });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today.AddDays(-1), 3) { Weigth = 3 });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today, 4) { Weigth = 4 });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today, 5) { Weigth = 5 });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today, 6) { Weigth = 6 });

            var rowCountFunc = default(Func<int>);
            var docs = repository.GetEntities<MySimpleAccount>(new PagingQueryStrategy(2, 2, out rowCountFunc)).ToList();

            rowCountFunc().ShouldEqual(6);
            docs.Count().ShouldEqual(2);
        }
Пример #33
0
 /// <summary>
 /// 插入爬虫
 /// </summary>
 /// <param name="NewVisitor"></param>
 public static void InsertSpider(Visitor NewVisitor)
 {
     MongoDbRepository.InsertCacheRec("Spider", NewVisitor);
 }
Пример #34
0
 /// <summary>
 /// 修改配置
 /// </summary>
 /// <param name="OldSiteConfig"></param>
 public static void UpdateSiteConfig(SiteConfig OldSiteConfig)
 {
     MongoDbRepository.UpdateRec(OldSiteConfig);
 }
Пример #35
0
 /// <summary>
 /// 删除配置
 /// </summary>
 /// <param name="DropSiteConfig"></param>
 public static void DropSiteConfig(SiteConfig DropSiteConfig)
 {
     MongoDbRepository.DeleteRec(DropSiteConfig);
 }
Пример #36
0
 public MongoDbRepositoryTestingScenario(Option<Func<object>> identityGenerator, string idPropertyName = "Id")
 {
     SessionScope = A.Fake<ISessionScopeEx>();
     IdentityGenerator = identityGenerator;
     Repository = new MongoDbRepository<TestEntity>(SessionScope, idPropertyName, IdentityGenerator);
 }
Пример #37
0
 public MongoDbSagaPersistence(MongoDbRepository repo)
 {
     _repo = repo;
 }
Пример #38
0
        public void Load_training_by_id_via_string()
        {
            IRepository sut = new MongoDbRepository(CONNECTIONSTRING);

            Training t = null;
            sut.CreateTraining("sometrainingLoad", "sometrainerLoad", _ => t = _, null);

            Console.WriteLine("id: {0}", t.Id);

            Training result = null;
            sut.LoadTrainingById(t.Id, _ => result = _, null);

            Equalidator.AreEqual(t.Id, result.Id);
            Assert.AreEqual("sometrainerLoad", result.TrainerMatchcode);
        }
        public void MongoRepository_Supports_Basic_Crud_Operations()
        {
            const string connectionString = "mongodb://127.0.0.1";

            if (!MongoDbRepositoryManager.ServerIsRunning(connectionString))
            {
                AssertIgnores.MongoServerIsNotRunning();
            }

            var repo = new MongoDbRepository<Order, string>(connectionString);

            // Create
            var create = new Order { Name = "Big sale" };
            repo.Add(create);

            // Read
            var read = repo.Get(create.OrderId);
            read.Name.ShouldEqual(create.Name);

            // Update
            read.Name = "Really big sale";
            repo.Update(read);

            var all = repo.GetAll();

            var update = repo.Get(read.OrderId);
            update.OrderId.ShouldEqual(read.OrderId);
            update.Name.ShouldEqual(read.Name);

            // Delete
            repo.Delete(update);
            var delete = repo.Get(read.OrderId);
            delete.ShouldBeNull();
        }
Пример #40
0
        public static async System.Threading.Tasks.Task CheckMailAsync()//string toemail, string username, string password)
        {
            try
            {
                MailServer oServer = new MailServer("imap.gmail.com",
                                                    "*****@*****.**",
                                                    "pachikkara",
                                                    EAGetMail.ServerProtocol.Imap4);

                // Enable SSL connection.
                oServer.SSLConnection = true;

                // Set 993 SSL port
                oServer.Port = 993;

                MailClient oClient = new MailClient("TryIt");
                oClient.Connect(oServer);
                MongoDbRepository <MailInvoice> mi = new MongoDbRepository <MailInvoice>();// retrieve unread/new email only
                oClient.GetMailInfosParam.Reset();
                oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;
                //oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.;

                MailInfo[] infos = oClient.GetMailInfos();
                Console.WriteLine("Total {0} unread email(s)\r\n", infos.Length);
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                                      info.Index, info.Size, info.UIDL);

                    // Receive email from IMAP4 server
                    Mail oMail = oClient.GetMail(info);
                    if (oMail.Attachments.Length > 0)
                    {
                        foreach (var attachment in oMail.Attachments)
                        {
                            if (attachment.ContentType == "application/json")
                            {
                                var       stream = new MemoryStream(attachment.Content);
                                IFormFile file   = new FormFile(stream, 0, attachment.Content.Length, "name", "Invoice.json");

                                // var filePath = Path.GetTempFileName();
                                var filePath = Path.GetTempFileName();

                                using (var streamfile = System.IO.File.Create(filePath))
                                {
                                    await file.CopyToAsync(streamfile);
                                }
                                //File.WriteAllBytes(filePath, attachment.Content);

                                //using (var streamcreate = System.IO.File.Create(filePath))
                                //{

                                //}

                                //StreamReader streamReader = new StreamReader(new MemoryStream(attachment.Content));// Server.MapPath("~/FileUpload/" + Path.GetFileName(file.FileName)));
                                // string data = streamReader.ReadToEnd();
                                IpfsClient ipfs   = new IpfsClient("https://ipfs.infura.io:5001");
                                var        result = ipfs.FileSystem.AddFileAsync(filePath).Result;
                                var        url    = "https://ipfs.io/ipfs/" + result.Id.Hash.ToString() + "?filename=" + "Invoice.json";

                                using (StreamReader r = new StreamReader(new MemoryStream(attachment.Content)))
                                {
                                    var         json        = r.ReadToEnd();
                                    var         invoiceJSON = JsonConvert.DeserializeObject <InvoiceJSON>(json);
                                    MailInvoice mailInvoice = new MailInvoice();
                                    mailInvoice.ToEmail                 = oMail.From.Address;
                                    mailInvoice.invoiceJSON             = invoiceJSON;
                                    mailInvoice.CreatedOn               = DateTime.Now;
                                    mailInvoice.InvoiceStatus           = MailInvoiceStatus.Created;
                                    mailInvoice.IsSend                  = false;
                                    mailInvoice.HashUrl                 = url;
                                    mailInvoice.mailInvoiceCreationType = MailInvoiceCreationType.Received;
                                    mi.Insert(mailInvoice);
                                }
                            }
                        }
                    }

                    Console.WriteLine("From: {0}", oMail.From.ToString());
                    Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
                    if (!info.Read)
                    {
                        oClient.MarkAsRead(info, true);
                    }
                }

                // Quit and expunge emails marked as deleted from IMAP4 server.
                oClient.Quit();
                Console.WriteLine("Completed!");
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
        }
Пример #41
0
 public MongoDbRepositoryTestingScenario(Option <Func <object> > identityGenerator, string idPropertyName = "Id")
 {
     SessionScope      = A.Fake <ISessionScopeEx>();
     IdentityGenerator = identityGenerator;
     Repository        = new MongoDbRepository <TestEntity>(SessionScope, idPropertyName, IdentityGenerator);
 }
Пример #42
0
        /// <summary>
        /// 是否存在专题
        /// </summary>
        /// <param name="accountid"></param>
        /// <returns></returns>
        public static bool IsExistTopic(string accountid)
        {
            IMongoQuery TopicQuery = Query.EQ(nameof(OwnerId), accountid);

            return(MongoDbRepository.GetRecordCount <Topic>(TopicQuery) > 0);
        }
Пример #43
0
 /// <summary>
 /// 按照序列号查找消息
 /// </summary>
 /// <param name="Sn"></param>
 /// <returns>消息</returns>
 public static SiteMessage GetSiteMessageBySn(string Sn)
 {
     return(MongoDbRepository.GetRecBySN <SiteMessage>(Sn));
 }
Пример #44
0
 /// <summary>
 /// 获得所有专题
 /// </summary>
 /// <returns></returns>
 public static List <Topic> getAllTopic()
 {
     return(MongoDbRepository.GetRecList <Topic>());
 }
Пример #45
0
 /// <summary>
 /// 插入消息
 /// </summary>
 /// <param name="Newsitemessage"></param>
 /// <returns>序列号</returns>
 public static string InsertSiteMessage(SiteMessage NewSiteMessage)
 {
     return(MongoDbRepository.InsertRec(NewSiteMessage));
 }
Пример #46
0
 /// <summary>
 /// 获得指定标签的公开文章
 /// </summary>
 /// <param name="MultiTagString"></param>
 /// <returns></returns>
 public static List <Article> GetArticleListByTag(string MultiTagString)
 {
     return(MongoDbRepository.GetRecList <Article>(Query.And(ArticleListManager.PublicArticleQuery, GetTagQuery(MultiTagString))));
 }
        //        [Test]
        public void ModifyAll()
        {
            var mongoDatabase = CreateEmptyMongoDatabase();
            var repository = new MongoDbRepository(mongoDatabase);

            repository.Add(new MySimpleAccount("xyz", DateTime.Today.AddDays(-1), 1) { Weigth = 1 });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today.AddDays(-1), 2) { Weigth = 2 });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today.AddDays(-1), 3) { Weigth = 3 });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today, 4) { Weigth = 4 });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today, 5) { Weigth = 5 });
            repository.Add(new MySimpleAccount("xyz", DateTime.Today, 6) { Weigth = 6 });

            var lessThanTodayQuery = new ExpressionSpecificationQueryStrategy<MySimpleAccount>(p => p.DOB < DateTime.Today);
            repository.GetEntities<MySimpleAccount>(lessThanTodayQuery).Count().ShouldEqual(3);

            var result3 = repository.ModifyAll<MySimpleAccount>(
                    lessThanTodayQuery,
                    new MongoUpdateItem<MySimpleAccount>(p => p.DOB, DateTime.Today),
                    new MongoUpdateItem<MySimpleAccount>(p => p.Weigth, 100));

            result3.DocumentsAffected.ShouldEqual(3);

            repository.GetEntities<MySimpleAccount>(lessThanTodayQuery).Count().ShouldEqual(0);
            repository.GetEntities<MySimpleAccount>(p => p.DOB == DateTime.Today).Count().ShouldEqual(6);
            repository.GetEntities<MySimpleAccount>(p => p.Weigth == 100).Count().ShouldEqual(3);
        }
Пример #48
0
 /// <summary>
 /// 插入访客
 /// </summary>
 /// <param name="NewVisitor">访客</param>
 public static void InsertVisitor(Visitor NewVisitor)
 {
     MongoDbRepository.InsertCacheRec(NewVisitor);
 }
 public MyAggregateRootRepository(string mongoUrl, string databaseName)
 {
     _mongoRepository = new MongoDbRepository <MyAggregateRoot>(mongoUrl, databaseName);
 }
Пример #50
0
 public ItemController(MongoDbRepository repo)
 {
     _IRepo = repo;
 }
Пример #51
0
 public PlayersController(MongoDbRepository repo)
 {
     _IRepo = repo;
 }