コード例 #1
0
 public void ConfigureRequestProcTime(IAppBuilder app)
 {
     RequestProcTimeOption requestProcTimeOption = new RequestProcTimeOption();
     requestProcTimeOption.RequestProcTimeAction = (data) =>
     {
         var messageInfo = new MessageInfo();
         messageInfo.Message = "请求时间日志";
         messageInfo.Body = data;
         messageInfo.Action = (messageData) =>
         {
             var bodyData = messageData.Body as RequestProcData;
             if (bodyData == null) return;
             //var requestProcTimeLog = new RequestProcTimeLog
             //{
             //    BeginRequestDateTime = bodyData.BeginRequestDateTime,
             //    EndRequestDateTime = bodyData.EndRequestDateTime,
             //    RequestIp = bodyData.RequestIp,
             //    RequestResponseInterval = bodyData.RequestResponseInterval,
             //    RequestUrl = bodyData.RequestUrl
             //};
             var requestProcTimeLog = Mapper.MapNew<RequestProcData, RequestProcTimeLog>(bodyData);
             var mongoDbRepository = new MongoDBRepository<RequestProcTimeLog>();
             mongoDbRepository.Insert(requestProcTimeLog);
         };
         QueueManagement.getInstance().PushData(messageInfo);
     };
     app.UseRequestProcTime(requestProcTimeOption);
 }
コード例 #2
0
        static void Main(string[] args)
        {
            string remoteSrv = @"mongodb://115.156.252.5:27017";
            string localSrv  = @"mongodb://127.0.0.1:27017";
            //setup db context
            var connection = localSrv;
            //todo ioc is really needed here
            MongoDBRepository <House>               houseDb   = new MongoDBRepository <House>(connection, "OldHouseDb", "House");
            MongoDBRepository <BlogPostEntity>      CheckInDb = new MongoDBRepository <BlogPostEntity>(connection, "OldHouseDb", "CheckIn");
            MongoDBRepository <OldHouseUser>        UserDb    = new MongoDBRepository <OldHouseUser>(connection, "OldHouseDb", "OldHouseUser");
            MongoDBRepository <OldHouseUserProfile> ProfileDb = new MongoDBRepository <OldHouseUserProfile>(connection, "OldHouseDb", "OldHouseUserProfile");
            MongoDBRepository <Message>             feedDb    = new MongoDBRepository <Message>(connection, "OldHouseDb", "Feed");


            houseService = new HouseService(
                houseDb,
                new BlogPostService(CheckInDb, null),
                new EntityService <OldHouseUserProfile>(ProfileDb),
                null,   //the like rate is not used here
                new UserManager <OldHouseUser>(UserDb),
                new MessageService(feedDb));

            loadExcel(@"D:\OldHouse\code\OldHouse\TestDataSet\test2\data.xls", int.Parse(args[0]), int.Parse(args[1]));

            Console.ReadKey();
        }
コード例 #3
0
        public void GetCompanyByMarketCapTest()
        {
            var compRepo = new MongoDBRepository <Company>(nameof(Company));
            CompanyCollection companyCollection = new CompanyCollection();

            var statRepo = new MongoDBRepository <Stat>("IEXStat");
            var finRepo  = new MongoDBRepository <Financial>(nameof(Financial));

            long minCap = 1_000_000;
            long maxCap = 2_000_000_000;

            var filter = Builders <Stat> .Filter.Lte(x => x.Marketcap, maxCap) &
                         Builders <Stat> .Filter.Gte(x => x.Marketcap, minCap);

            var results = statRepo.DbCollection.FindAsync(filter).Result.ToList();

            Assert.NotNull(results);

            results.ForEach((x) =>
            {
                Console.WriteLine(x.Marketcap);
                Assert.True(x.Marketcap <= maxCap, $"Actual={x.Marketcap} <= Expected={maxCap}");
            });

            var companies = companyCollection.GetCompanyId(results.Select(x => x.Symbol).ToList());

            Assert.AreEqual(companies.Count, results.Count);
        }
コード例 #4
0
        /// <summary>
        /// Configure
        /// </summary>
        /// <param name="builder">Authentication builder</param>
        public void Configure(AuthenticationBuilder builder, IConfiguration configuration)
        {
            builder.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
            {
                var settings = new GoogleExternalAuthSettings();
                try
                {
                    var goSettings = new MongoDBRepository <Setting>(DataSettingsHelper.ConnectionString()).Table.Where(x => x.Name.StartsWith("googleexternalauthsettings"));
                    settings.ClientKeyIdentifier = goSettings.FirstOrDefault(x => x.Name == "googleexternalauthsettings.clientkeyidentifier")?.Value;
                    settings.ClientSecret        = goSettings.FirstOrDefault(x => x.Name == "googleexternalauthsettings.clientsecret")?.Value;
                }
                catch { };

                options.ClientId     = !string.IsNullOrWhiteSpace(settings.ClientKeyIdentifier) ? settings.ClientKeyIdentifier : "000";
                options.ClientSecret = !string.IsNullOrWhiteSpace(settings.ClientSecret) ? settings.ClientSecret : "000";
                options.SaveTokens   = true;

                //handles exception thrown by external auth provider
                options.Events = new OAuthEvents()
                {
                    OnRemoteFailure = ctx =>
                    {
                        ctx.HandleResponse();
                        var errorMessage = ctx.Failure.Message;
                        var state        = ctx.Request.Query["state"].FirstOrDefault();
                        errorMessage     = WebUtility.UrlEncode(errorMessage);
                        ctx.Response.Redirect($"/google-signin-failed?error_message={errorMessage}");

                        return(Task.FromResult(0));
                    }
                };
            });
        }
コード例 #5
0
 static void Main(string[] args)
 {
     BusinessLog user = new BusinessLog() { Data = "张三", CreateTime = DateTime.Now };
     IMongoDBRepository<BusinessLog> mongoDbRepository = new MongoDBRepository<BusinessLog>();
     mongoDbRepository.Insert(user);
     Console.Read();
 }
コード例 #6
0
        /// <summary>
        /// Configure
        /// </summary>
        /// <param name="builder">Authentication builder</param>
        public void Configure(AuthenticationBuilder builder, IConfiguration configuration)
        {
            builder.AddFacebook(FacebookDefaults.AuthenticationScheme, options =>
            {
                var settings = new FacebookExternalAuthSettings();
                try
                {
                    var fbSettings = new MongoDBRepository <Setting>(DataSettingsHelper.ConnectionString()).Table.Where(x => x.Name.StartsWith("facebookexternalauthsettings"));
                    settings.ClientKeyIdentifier = fbSettings.FirstOrDefault(x => x.Name == "facebookexternalauthsettings.clientkeyidentifier")?.Value;
                    settings.ClientSecret        = fbSettings.FirstOrDefault(x => x.Name == "facebookexternalauthsettings.clientsecret")?.Value;
                }
                catch { };

                //no empty values allowed. otherwise, an exception could be thrown on application startup
                options.AppId      = !string.IsNullOrWhiteSpace(settings.ClientKeyIdentifier) ? settings.ClientKeyIdentifier : "000";
                options.AppSecret  = !string.IsNullOrWhiteSpace(settings.ClientSecret) ? settings.ClientSecret : "000";
                options.SaveTokens = true;
                //handles exception thrown by external auth provider
                options.Events = new OAuthEvents()
                {
                    OnRemoteFailure = ctx =>
                    {
                        ctx.HandleResponse();
                        var errorCode    = ctx.Request.Query["error_code"].FirstOrDefault();
                        var errorMessage = ctx.Request.Query["error_message"].FirstOrDefault();
                        var state        = ctx.Request.Query["state"].FirstOrDefault();
                        errorCode        = WebUtility.UrlEncode(errorCode);
                        errorMessage     = WebUtility.UrlEncode(errorMessage);
                        ctx.Response.Redirect($"/fb-signin-failed?error_code={errorCode}&error_message={errorMessage}");

                        return(Task.FromResult(0));
                    }
                };
            });
        }
コード例 #7
0
        static void Main(string[] args)
        {
            MongoDBRepository.RegisterMongoDBContext(new TripperCenterDBContext());
            MongoDBRepository.RegisterMongoDBContext(new DeliveryCenterDBContext());
            MongoDBRepository.RegisterMongoDBContext(new StatusCenterDBContext());
            MongoDBRepository.RegisterMongoDBContext(new RelationCenterDBContext());
            MongoDBRepository.RegisterMongoIndex();

            var      ass  = WinAssemblyUtility.GetAssembly();
            HostInfo host = new HostInfo(ConfigurationManager.AppSettings["WcfHostAddress"]).LoadTypesFromAssemblies(ass);

            using (ServiceContainer container = new ServiceContainer())
            {
                container.Open(host);
                Console.WriteLine("press close to stop host");

                while (true)
                {
                    if ("close" == Console.ReadLine().ToLower())
                    {
                        container.Close(host);
                        break;
                    }
                }
                Console.WriteLine("press 'Enter' to quit");
                Console.ReadKey();
            }
        }
コード例 #8
0
        public async Task TestMultiInsert(int max)
        {
            var repository = new MongoDBRepository();
            var tasks = new List<Task<BaseEntity>>();
            for (int count = 0; count < max; count++)
            {
                tasks.Add(repository.Insert(new BaseEntity() { Name = String.Format("Alice{0}",count) }));
            }

            var names = new List<string>();
            // Run collection of Inserts concurrently
            foreach (var bucket in TaskProcessor.Interleaved(tasks))
            {
                var t = await bucket;
                try { var entity = await t;
                     names.Add(entity.Name);
                }
                catch (OperationCanceledException) { }
                catch (Exception exc) { 
                    Debug.WriteLine(exc); 
                }
            }

            Assert.Equal(max, names.Count);
        }
コード例 #9
0
        public void Setup()
        {
            MongoDBRepository.RegisterMongoDBContext(new TestDBContext());
            MongoDBRepository.RegisterMongoIndex();

            students = new List <Student>()
            {
                new Student {
                    Name = "hyf", Age = 33
                },
                new Student {
                    Name = "zhc", Age = 30
                }
            };
            teachers = new List <Teacher>()
            {
                new Teacher {
                    Name = "Lee", Age = 53
                },
                new Teacher {
                    Name = "Chen", Age = 50
                }
            };
            Grade grade = new Grade();

            teachers.ForEach(t => grade.Teachers.Add(t.ToDBRef()));
            grades = new List <Grade>()
            {
                grade
            };

            MongoEntity.Save(students);
            MongoEntity.Save(teachers);
            MongoEntity.Save(grades);
        }
コード例 #10
0
 public async Task TestGet()
 {
     var repository = new MongoDBRepository();
     var entities = await repository.Get<BaseEntity>();
     Assert.NotNull(entities);
     Assert.NotEmpty(entities);
 }
コード例 #11
0
        public void FindIncomeGrowthTest()
        {
            var compRepo = new MongoDBRepository <Company>(nameof(Company)).DbCollection;
            var histColl = new MongoDBRepository <Financial>(nameof(Financial)).DbCollection;
            var results  = histColl.Aggregate().Group(key => key.companyId,
                                                      value => new {
                CompanyId   = value.Select(x => x.companyId).First(),
                TotalIncome = value.Sum(x => x.netIncome).Value,
                FirstYear   = value.First().netIncome.Value,
                LastYear    = value.Last().netIncome.Value,
                YearCount   = value.Count()
            }).ToList().Distinct();

            foreach (var result in results)
            {
                double growthRate = ((double)(result.FirstYear - result.LastYear) / result.LastYear) * 100 / result.YearCount;
                var    filter     = Builders <Company> .Filter.Eq("_id", result.CompanyId);

                var comp = compRepo.Find(filter).ToListAsync().Result;

                if (growthRate > 10 && comp.Count > 0)
                {
                    Console.WriteLine($"{comp.First().symbol}, {result.TotalIncome}, {result.FirstYear}, {result.LastYear}, {growthRate}");
                }
            }
        }
コード例 #12
0
 /// Add and configure any of the middleware
 /// </summary>
 /// <param name="services">Collection of service descriptors</param>
 /// <param name="configuration">Configuration root of the application</param>
 public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
 {
     //database is already installed, so start scheduled tasks
     if (DataSettingsHelper.DatabaseIsInstalled())
     {
         try
         {
             var machineName = Environment.MachineName;
             var tasks       = new MongoDBRepository <ScheduleTask>(DataSettingsHelper.ConnectionString()).Table;
             foreach (var task in tasks)
             {
                 if (task.Enabled)
                 {
                     if (string.IsNullOrEmpty(task.LeasedByMachineName) || (machineName == task.LeasedByMachineName))
                     {
                         services.AddSingleton <IHostedService, BackgroundServiceTask>(sp =>
                         {
                             return(new BackgroundServiceTask(task, sp));
                         });
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             throw new Exception(ex.Message);
         }
     }
 }
コード例 #13
0
        public ProductIntegrationTests()
        {
            sut1 = new EventSourcingRepository <Product, ProductId>(
                new EventStoreEventStore(EventStoreConnection.Create(new Uri("tcp://localhost:1113"))),
                new TransientDomainEventPubSub()
                );

            var client = new MongoClient("mongodb://localhost:27017");

            mongoDB = client.GetDatabase("cqrs1");

            productItemRepository      = new MongoDBRepository <ProductDto>(mongoDB);
            productItemPriceRepository = new MongoDBRepository <ProductPriceDto>(mongoDB);

            cardEventHandler = new ProductProjection(productItemRepository, productItemPriceRepository);

            productItemCreatedHandlers = new List <IDomainEventHandler <ProductId, ProductItemCreated> >()
            {
                cardEventHandler
            };
            productItemChangedHandlers = new List <IDomainEventHandler <ProductId, ProductItemChanged> >()
            {
                cardEventHandler
            };
            productItemPriceChangedHandlers = new List <IDomainEventHandler <ProductId, ProductPriceChanged> >()
            {
                cardEventHandler
            };
        }
コード例 #14
0
        // GET api/apps?id=app_id
        public HttpResponseMessage Get(string id)
        {
            MobileAppResponse response = new MobileAppResponse();

            // List of Apps Found with that given ID
            List <AppModel> result = new List <AppModel> ();

            using (MongoDBRepository mongoHandler = new MongoDBRepository())
            {
                // Is the App Already on The Database ?
                if (!mongoHandler.IsAppOnTheDatabase(id))
                {
                    response.error         = false;
                    response.statusMessage = String.Format("App Id {0} could not be found On the Database.", id);
                    response.appsFound     = null;

                    // NotModified Response Code
                    return(Request.CreateResponse(HttpStatusCode.NotFound, response, GetFormatter()));
                }

                // Finding The Apps
                result.AddRange(mongoHandler.FindAppsByID(id));
            }

            // Filling Up Web Response
            response.error         = false;
            response.statusMessage = String.Empty;
            response.appsFound     = result;
            return(Request.CreateResponse(HttpStatusCode.OK, response, GetFormatter()));
        }
コード例 #15
0
        internal static void InsertBatch(IEnumerable <CIKInfo> cikInfos, List <IEXDataType> listIexDataTypes, ChartOption chartOption, int itemCount, Period period)
        {
            int total      = cikInfos.Count();
            int count      = 0;
            int batchCount = 50;
            CompanyCollection companyRepo = new CompanyCollection();

            do
            {
                var symbols = cikInfos.Select(x => x.Ticker).Skip(count).Take(batchCount).ToArray();
                count += symbols.Count();

                var dictSymbolComp = companyRepo.GetCompanyId(symbols.ToList());
                //get data
                IEXClientHandler response = new IEXClientHandler();
                var results = response.GetBatchReport(symbols, listIexDataTypes, ChartOption._1d, itemCount, period);


                //insert to db
                var comp  = new MongoDBRepository <Company>(nameof(Company));
                var stat  = new MongoDBRepository <Stat>("IEXStat");
                var fin   = new MongoDBRepository <Financial>(nameof(Financial));
                var quote = new MongoDBRepository <Quote>("Quote");


                foreach (string symbol in results.Keys)
                {
                    ObjectId compId = ObjectId.GenerateNewId(); //ObjectId.GenerateNewId().ToString();
                    results[symbol].Company._id = compId;
                    if (results[symbol].Company != null)
                    {
                        comp.MongoInsert(results[symbol].Company).Wait();
                    }

                    if (results[symbol].Stat != null)
                    {
                        results[symbol].Stat.companyId = compId;
                        stat.MongoInsert(results[symbol].Stat).Wait();
                    }

                    if (results[symbol].Financials.financials != null)
                    {
                        Parallel.For(0, results[symbol].Financials.financials.Count, (i) =>
                        {
                            results[symbol].Financials.financials[i].companyId = compId;
                        });

                        fin.MongoInsertMany(results[symbol].Financials.financials).Wait();
                    }

                    if (results[symbol].Quote != null)
                    {
                        results[symbol].Quote.companyId = compId;
                        quote.MongoInsert(results[symbol].Quote).Wait();
                    }
                }
            } while (count < total);
        }
コード例 #16
0
        public void GetIEXData()
        {
            var    comp   = new MongoDBRepository <Company>("Company");
            string symbol = "GE";
            var    filter = Builders <Company> .Filter.Eq(x => x.symbol, symbol);

            var result = comp.MongoGet(filter);

            Assert.NotNull(result);
        }
コード例 #17
0
        public void Clear()
        {
            MongoEntity.RemoveAll <Student>();
            MongoEntity.RemoveAll <Teacher>();
            MongoEntity.RemoveAll <Grade>();
            MongoEntity.RemoveAll <School>();
            MongoEntity.RemoveAllFiles <MyFile>();

            MongoDBRepository.UnregisterDBContext <TestDBContext>();
        }
コード例 #18
0
ファイル: Global.asax.cs プロジェクト: Red626/VolQ-Web
        protected void Application_Start()
        {
            //先读config
            Jtext103.StringConfig.ConfigString.Load(HttpRuntime.AppDomainAppPath + "Static\\StringConfig");

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //BundleConfig.RegisterBundles(BundleTable.Bundles);
            Configure(System.Web.Http.GlobalConfiguration.Configuration);
            string db           = ConfigurationSettings.AppSettings["DataBase"];
            string eventHandler = ConfigurationSettings.AppSettings["EventHandler"];
            string connection   = @"mongodb://115.156.252.5:27017";
            //new service and inject to entity
            MongoDBRepository <Entity>             entityRepository                         = new MongoDBRepository <Entity>(connection, db, "volunteer");
            MongoDBRepository <Message>            messageRepository                        = new MongoDBRepository <Message>(connection, db, "message");
            MongoDBRepository <Message>            feedRepository                           = new MongoDBRepository <Message>(connection, db, "feed");
            MongoDBRepository <TagEntity>          activityTagRepository                    = new MongoDBRepository <TagEntity>(connection, db, "activityTag");
            MongoDBRepository <TagEntity>          affiliationRepository                    = new MongoDBRepository <TagEntity>(connection, db, "affiliation");
            MongoDBRepository <TokenModel>         tokenRepository                          = new MongoDBRepository <TokenModel>(connection, db, "token");
            MongoDBRepository <AuthorizationModel> authorizationRepository                  = new MongoDBRepository <AuthorizationModel>(connection, "Volunteer", "authorization");
            MongoDBRepository <Event>                    eventRepository                    = new MongoDBRepository <Event>(connection, db, "event");
            MongoDBRepository <Subscriber>               subscriberRepository               = new MongoDBRepository <Subscriber>(connection, db, "subscriber");
            MongoDBRepository <BadgeDescription>         badgeDescriptionRepository         = new MongoDBRepository <BadgeDescription>(connection, db, "badgeDescription");
            MongoDBRepository <BadgeEntity>              badgeEntityRepository              = new MongoDBRepository <BadgeEntity>(connection, db, "badgeEntity");
            MongoDBRepository <FriendRelationshipEntity> friendRelationshipEntityRepository = new MongoDBRepository <FriendRelationshipEntity>(connection, db, "friendRelationship");
            MongoDBRepository <ActionValidationModel>    actionValidationRepository         = new MongoDBRepository <ActionValidationModel>(connection, db, "actionValidation");
            MongoDBRepository <CommentEntity>            commentRepository                  = new MongoDBRepository <CommentEntity>(connection, db, "comment");
            MongoDBRepository <BlogPostEntity>           summaryRepository                  = new MongoDBRepository <BlogPostEntity>(connection, db, "summary");

            //初始化service
            VolunteerService        myService               = new VolunteerService(entityRepository);
            TokenService            tokenService            = new TokenService(tokenRepository);
            MessageService          messageService          = new MessageService(messageRepository);
            MessageService          feedService             = new MessageService(feedRepository);
            TagService              activityTagService      = new TagService(activityTagRepository);
            TagService              affiliationService      = new TagService(affiliationRepository);
            ActionValidationService actionValidationService = new ActionValidationService(actionValidationRepository);
            BlogService             blogService             = new BlogService(commentRepository, summaryRepository);

            Entity.SetServiceContext(myService);
            EventService.InitService(eventRepository, subscriberRepository, 100, 1000, eventHandler);
            BadgeService.InitService(badgeDescriptionRepository, badgeEntityRepository);
            FriendService.InitService(friendRelationshipEntityRepository);
            ValidationService.InitService(tokenService, myService, authorizationRepository);
            myService.InitVolunteerService(messageService, feedService, activityTagService, affiliationService, actionValidationService, blogService);
            //新建badgeDescription
            BadgeService.RegisterBadgeDescriptions(getIBadge(EventService.EventHandlerList));

            ShortMessageService shortMessageService = new ShortMessageService("VerifyShortMessageSenderAccount.xml");
            MailService         mailService         = new MailService("NoReplyMailSenderAccount.xml");

            //setActivityCover(myService);
        }
コード例 #19
0
        public static void AddLogToCollection(string jsonDocument,string collectionName)
        {
            try
            {
                var document = BsonDocument.Parse(jsonDocument);

                document = CorrectDateField(document);

                var keyValue = document.First().Value.ToString();

                var result = new BsonDocument();
                result.Add("_id", keyValue);

                var mongoRepo = new MongoDBRepository<MongoDBContext>();
                var fResult = mongoRepo.FinObjectByKey(collectionName, keyValue).ToList();

                if (fResult != null && fResult.Count == 1)
                {
                    var value = fResult.First().Last().Value as BsonArray;
                    if (value != null)
                    {
                        var doc = fResult.First().Last().Value as BsonArray;
                        doc.Add(document.Last().Value);
                        CopyMidelElmentInResult(document, result);
                        result.Add(document.Last().Name, doc);
                        mongoRepo.ReplaceOne(keyValue, collectionName, result);
                    }
                    else
                    {
                        var doc = fResult.First().Last().Value as BsonDocument;
                        var list = new BsonArray();
                        list.Add(doc);
                        list.Add(document.Last().Value);
                        CopyMidelElmentInResult(document, result);
                        result.Add(doc.Last().Name, list);
                        mongoRepo.ReplaceOne(keyValue, collectionName, result);
                    }
                }
                else
                {

                    CopyMidelElmentInResult(document, result);
                    var list = new BsonArray();
                    list.Add(document.Last().Value);
                    result.Add(document.Last().Name, list);
                    mongoRepo.AddOne(collectionName, result);
                }

            }
            catch(Exception ex)
            {
                APILogger.Write(ex.Message, LogLevel.Error);
            }
           
        }
コード例 #20
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            MongoDBRepository.RegisterMongoDBContext(new DocDbContext());
        }
コード例 #21
0
        public void QueryTest()
        {
            var compRepo = new MongoDBRepository <Company>(nameof(Company)).DbCollection;
            var filter   = Builders <Company> .Filter.Eq("_id", ObjectId.Parse("5bd6920d9656412594cf7657"));

            //var filter = Builders<Company>.Filter.Eq("symbol", "GE");
            var result = compRepo.FindAsync(filter).Result.First();

            Assert.AreEqual(result.symbol, "GE");
            Console.WriteLine($"Id:{result._id}, Comp:{result.companyName}");
        }
コード例 #22
0
 public void MongoDBContextTestCase()
 {
     try
     {
         MongoDBRepository.RegisterMongoDBContext(new CompanyDBContext());
         MongoDBRepository.RegisterMongoDBContext(new FactoryDBContext());
     }
     catch (Exception e)
     {
         Assert.Pass(e.Message);
     }
 }
コード例 #23
0
ファイル: Program.cs プロジェクト: ylasmak/SQLi.NoSql.API
        static void Main(string[] args)
        {

            var mongoRepo = new MongoDBRepository<MongoDBContext>();
            var x = mongoRepo.GetListEntities<FloussyTransaction>(p => p.TransactionList.Any(s => s.Error == ErrorType.Default)).Select(p => p.TransactionList.Where(s => s.Error == ErrorType.Default)).ToList();
            var y = x.ToList();

         //mongoRepo.MongoContext.GetCollection<FloussyTransaction>("FloussyTransaction").Aggregate(pipeline)



        }
コード例 #24
0
 public void RegisterMongoDBContext()
 {
     foreach (Type type in WinAssemblyUtility.GetAssembly <IMongoDBContext>().FindTypes <IMongoDBContext>())
     {
         if (type.IsAbstract)
         {
             continue;
         }
         var context = Activator.CreateInstance(type) as MongoDBContext;
         MongoDBRepository.RegisterMongoDBContext(context);
     }
 }
コード例 #25
0
        public void GetCompanyFinancialAggregateTest()
        {
            long minCap   = 1_000_000;
            long maxCap   = 2_000_000_000;
            var  statRepo = new MongoDBRepository <Stat>("IEXStat").DbCollection.AsQueryable();
            var  compRepo = new MongoDBRepository <Company>(nameof(Company)).DbCollection.AsQueryable();
            var  result   = (from s in statRepo
                             join c in compRepo on s.companyId equals c._id //into joined
                             where s.Marketcap >= minCap && s.Marketcap <= maxCap
                             select new { s.companyId, c.companyName }).ToList();

            Assert.NotNull(result);
        }
コード例 #26
0
        public static IRepository <T> GetRepository <T>(Techs tech)
        {
            IRepository <T> repository;

            switch (tech)
            {
            case Techs.MongoDB:
                repository = new MongoDBRepository <T>();
                break;

            default:
                throw new ArgumentException();
            }

            return(repository);
        }
コード例 #27
0
        public EntityProjection(MongoDBRepository projectionRepository)
        {
            When <EntityCreated>(e =>
            {
                if (e.EntityId == null || e.EntityName == null)
                {
                    return;
                }

                projectionRepository.Connect();
                var entityCollection = projectionRepository.GetCollection("Entity");

                var document = new BsonDocument
                {
                    { "Id", e.EntityId.ToString() },
                    { "Name", e.EntityName }
                };

                entityCollection.InsertOne(document);
            });

            When <BasicDetailsAdded>(e =>
            {
                if (e.DateOfBirth == null || e.CountryOfResidence == null)
                {
                    return;
                }

                projectionRepository.Connect();

                var filter           = Builders <BsonDocument> .Filter.Eq("Id", e.EntityId.ToString());
                var entityCollection = projectionRepository.GetCollection("Entity");

                var searchResult = entityCollection.Find(filter);

                if (searchResult.CountDocuments() == 0)
                {
                    return;
                }

                var update = Builders <BsonDocument> .Update
                             .Set("DateOfBirth", e.DateOfBirth)
                             .Set("CountryOfResidence", e.CountryOfResidence);

                entityCollection.UpdateOne(filter, update);
            });
        }
コード例 #28
0
        /// <summary>
        /// config the business logic
        /// </summary>
        public static void ConfigBusiness()
        {
            //todo ioc is really needed here
            MongoDBRepository <House>               houseBb   = new MongoDBRepository <House>(@"mongodb://127.0.0.1:27017", "OldHouseDb", "House");
            MongoDBRepository <BlogPostEntity>      CheckInDb = new MongoDBRepository <BlogPostEntity>(@"mongodb://127.0.0.1:27017", "OldHouseDb", "CheckIn");
            MongoDBRepository <OldHouseUser>        UserDb    = new MongoDBRepository <OldHouseUser>(@"mongodb://127.0.0.1:27017", "OldHouseDb", "OldHouseUser");
            MongoDBRepository <OldHouseUserProfile> ProfileDb = new MongoDBRepository <OldHouseUserProfile>(@"mongodb://127.0.0.1:27017", "OldHouseDb", "OldHouseUserProfile");

            MongoDBRepository <FeedBackEntity> FeedbackDb = new MongoDBRepository <FeedBackEntity>(@"mongodb://127.0.0.1:27017", "OldHouseDb", "Feedback");

            MyFeedbackService = new EntityService <FeedBackEntity>(FeedbackDb);

            MyHouseService = new HouseService(
                houseBb,
                new BlogPostService(CheckInDb, null),
                new EntityService <OldHouseUserProfile>(ProfileDb),
                new UserManager <OldHouseUser>(UserDb));
            ConfigDtoMapping();
        }
コード例 #29
0
        internal static void InsertChartData(IEnumerable <CIKInfo> cikInfos)
        {
            IEXClientHandler  response = new IEXClientHandler();
            CompanyCollection compColl = new CompanyCollection();

            //symbols from list
            var symbols = cikInfos.Select(x => x.Ticker).ToList();

            //checking for company exists in db
            var dictComp = compColl.GetCompanyId(symbols);

            //insert to db
            var chartCollection = new MongoDBRepository <Chart>("Charts");

            foreach (string symbol in dictComp.Keys)
            {
                try
                {
                    var results = response.GetBatchReport(symbol, new List <IEXDataType> {
                        IEXDataType.chart
                    }, ChartOption._5y, 100);

                    if (!dictComp.ContainsKey(symbol))
                    {
                        Console.WriteLine($"Not data for symbol {symbol}.");
                        continue;
                    }

                    //update charts with companyId
                    Parallel.For(0, results.Charts.Count, (i) =>
                    {
                        results.Charts[i].companyId = dictComp[symbol];
                    });

                    chartCollection.MongoInsertMany(results.Charts).Wait();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
コード例 #30
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press i to initialize data");
            Console.WriteLine("Press r to remove data");
            Console.WriteLine("Press any key to quit");

            var key = Console.ReadKey();

            Console.WriteLine();

            if (key.KeyChar == 'i')
            {
                MongoDBRepository.RegisterMongoDBContext(new UserCenterDBContext());
                new UserCenterInitializer().Init();
            }
            if (key.KeyChar == 'r')
            {
                MongoDBRepository.RegisterMongoDBContext(new UserCenterDBContext());
                new UserCenterInitializer().Remove();
            }
        }
コード例 #31
0
        private static void Opret()
        {
            Udvikler u = new Udvikler {
                Name = "Jakob"
            };


            List <Viden> videnList = new List <Viden>();
            Viden        v         = new Viden {
                Sprog = "C#", Rating = 10
            };

            videnList.Add(v);

            u.Viden = videnList;
            MongoDBRepository repo = new MongoDBRepository(CONNECTIONSSTRING, DATABASENAVN, COLLECTIONNAVN);
            string            res  = repo.CreateIndex();

            //repo.OpretUdvikler(u);

            Console.WriteLine();
        }
コード例 #32
0
        public CaseProjection(MongoDBRepository projectionRepository)
        {
            When <CaseInitiated>(e =>
            {
                if (e.CaseId == null)
                {
                    return;
                }

                projectionRepository.Connect();
                var caseCollection = projectionRepository.GetCollection("Case");

                var document = new BsonDocument
                {
                    { "Id", e.CaseId.ToString() },
                    { "EntityId", e.EntityId.ToString() },
                    { "Type", Enum.GetName(typeof(CaseType), e.CaseType) }
                };

                caseCollection.InsertOne(document);
            });
        }
コード例 #33
0
ファイル: BusinessConfig.cs プロジェクト: Red626/CityGee-Web
        /// <summary>
        /// config the business logic
        /// </summary>
        public static void ConfigBusiness()
        {
            //todo ioc is really needed here
            string database = "OldHouseDb";//"OldHouseDbProduction"
            MongoDBRepository <House>               houseDb   = new MongoDBRepository <House>(@"mongodb://127.0.0.1:27017", database, "House");
            MongoDBRepository <BlogPostEntity>      CheckInDb = new MongoDBRepository <BlogPostEntity>(@"mongodb://127.0.0.1:27017", database, "CheckIn");
            MongoDBRepository <LikeRateFavEntity>   LrfDb     = new MongoDBRepository <LikeRateFavEntity>(@"mongodb://127.0.0.1:27017", database, "LikeRateFavorite");
            MongoDBRepository <OldHouseUser>        UserDb    = new MongoDBRepository <OldHouseUser>(@"mongodb://127.0.0.1:27017", database, "OldHouseUser");
            MongoDBRepository <OldHouseUserProfile> ProfileDb = new MongoDBRepository <OldHouseUserProfile>(@"mongodb://127.0.0.1:27017", database, "OldHouseUserProfile");
            MongoDBRepository <Message>             feedDb    = new MongoDBRepository <Message>(@"mongodb://127.0.0.1:27017", database, "Feed");

            MongoDBRepository <FeedBackEntity> FeedbackDb = new MongoDBRepository <FeedBackEntity>(@"mongodb://127.0.0.1:27017", database, "Feedback");
            MongoDBRepository <Article>        ArticleDb  = new MongoDBRepository <Article>(@"mongodb://127.0.0.1:27017", database, "Article");

            MongoDBRepository <Event>      eventDb      = new MongoDBRepository <Event>(@"mongodb://127.0.0.1:27017", database, "Event");
            MongoDBRepository <Subscriber> subscriberDb = new MongoDBRepository <Subscriber>(@"mongodb://127.0.0.1:27017", database, "Subscriber");

            //string handlerRelativePath = System.AppDomain.CurrentDomain.BaseDirectory.Substring(0, System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\').LastIndexOf(@"\")) + @"\OldHouse.EventHandlers\bin\Debug";
            //EventService.InitService(eventDb, subscriberDb, 100, 1000, handlerRelativePath);
            EventService.InitService(eventDb, subscriberDb, 100, 1000, HttpRuntime.BinDirectory + @"\..\OldHouseEventHandler");

            //a like rate fav service shared by all entity service
            var shareedLrfService = new LikeRateFavService(LrfDb);

            MyFeedbackService = new FeedbackService(FeedbackDb);
            MyArticleService  = new ArticleService(ArticleDb);
            MyHouseService    = new HouseService(
                houseDb,
                new BlogPostService(CheckInDb, shareedLrfService),
                new EntityService <OldHouseUserProfile>(ProfileDb),
                shareedLrfService,
                new UserManager <OldHouseUser>(UserDb),
                new MessageService(feedDb)
                );
            ConfigDtoMapping();

            hotFix();
        }
コード例 #34
0
        internal static void InsertCompanyData(IEnumerable <CIKInfo> cikInfos)
        {
            int total      = cikInfos.Count();
            int count      = 0;
            int batchCount = 50;

            do
            {
                var symbols = cikInfos.Select(x => x.Ticker).Skip(count).Take(batchCount).ToArray();
                count += symbols.Count();

                //get data
                IEXClientHandler response = new IEXClientHandler();
                var results = response.GetBatchReport(symbols, new List <IEXDataType> {
                    IEXDataType.company
                }, IEXApiHandler.IEXData.Stock.ChartOption._1d, 1);

                //insert to db
                var comp = new MongoDBRepository <Company>("Company");
                //repo.MongoInsert(results.Values.Select(x => x.Company).Distinct().ToList()).Wait();
                comp.MongoInsertMany(results.Values.Select(x => x.Company).Distinct().ToList()).Wait();
            } while (count < total);
        }
コード例 #35
0
        public void ConfigureRequestLog(IAppBuilder app)
        {
            var requestLogOption = new RequestLogOption();
            requestLogOption.RequestLogProceAction = (data) =>
            {
                var messageInfo = new MessageInfo();
                messageInfo.Message = "请求日志";
                messageInfo.Body = data;
                messageInfo.Action = (messageData) =>
                {
                    var bodyData = messageData.Body as RequestLogData;
                    if (bodyData == null) return;
                    var requestDataLog = Mapper.MapNew<RequestLogData, RequestDataLog>(bodyData);
                    var mongoDbRepository = new MongoDBRepository<RequestDataLog>();
                    mongoDbRepository.Insert(requestDataLog);

                };
                QueueManagement.getInstance().PushData(messageInfo);
                LogManager.getInstance().WriteRequestLog(messageInfo.Message);
            };

            app.UseRequestLog(requestLogOption);
        }
コード例 #36
0
        static void initRepository()
        {
            Console.WriteLine("请选择要统计的数据库:(只能123,输错了就gg)");
            Console.WriteLine("1.localhost");
            Console.WriteLine("2.测试环境");
            Console.WriteLine("3.生产环境");
            char   key = Console.ReadKey().KeyChar;
            string server;
            string database;

            switch (key)
            {
            case '1':
                server   = @"mongodb://127.0.0.1:27017";
                database = "OldHouseDb";
                break;

            case '2':
                server   = @"mongodb://115.156.252.5:27017";
                database = "OldHouseDb";
                break;

            case '3':
                server   = @"mongodb://115.156.252.5:27017";
                database = "OldHouseDbProduction";
                break;

            default:
                throw new Exception();
            }
            EventDb = new MongoDBRepository <Event>(server, database, "Event");
            HouseDb = new MongoDBRepository <House>(server, database, "House");
            UserDb  = new MongoDBRepository <OldHouseUser>(server, database, "OldHouseUser");

            //注册
            HouseDb.RegisterMap <House>(new string[] { "_overallValue" });
        }
コード例 #37
0
        /// <summary>
        /// 动态加载配置方法
        /// </summary>
        public void Configuration()
        {
            ServcieBeheavior.Func = (input, getNext) =>
            {
                var servcieExecuteLog=new ServcieExecuteLog();
                var dictionary=new Dictionary<string, object>();
                for (var i = 0; i < input.Arguments.Count; i++)
                {
                    dictionary.Add("arg"+(i+1),input.Arguments[i]);
                }

                servcieExecuteLog.ExcecuteArguments = JsonConvert.SerializeObject(dictionary);
                servcieExecuteLog.BeginExecuteDateTime = DateTime.Now;

                var result = getNext().Invoke(input, getNext);

                servcieExecuteLog.EndExecuteDateTime = DateTime.Now;
                servcieExecuteLog.ExecuteInterval = servcieExecuteLog.EndExecuteDateTime -
                                                    servcieExecuteLog.BeginExecuteDateTime;
                if (result.Exception != null)
                {

                }
                var messageInfo = new MessageInfo();
                messageInfo.Message = "服务执行日志";
                messageInfo.Body = servcieExecuteLog;
                messageInfo.Action = (messageData) =>
                {
                    var bodyData = messageData.Body as ServcieExecuteLog;
                    if (bodyData == null) return;
                    var mongoDbRepository = new MongoDBRepository<ServcieExecuteLog>();
                    mongoDbRepository.Insert(bodyData);

                };
                QueueManagement.getInstance().PushData(messageInfo);

                //注:以下处理正式情况不会影响 太大性能
                //   但为了 不占方法执行更多性能 这里采用异步方式
                //Task.Factory.StartNew(data =>
                //{
                //    var messageInfo = new MessageInfo();
                //    messageInfo.Message = "服务执行日志";
                //    messageInfo.Body = data;
                //    messageInfo.Action = (messageData) =>
                //    {
                //        var bodyData = messageData.Body as ServcieExecuteLog;
                //        if (bodyData == null) return;
                //        var mongoDbRepository = new MongoDBRepository<ServcieExecuteLog>();
                //        mongoDbRepository.Insert(bodyData);

                //    };
                //    QueueManagement.getInstance().PushData(messageInfo);
                //}, servcieExecuteLog);

                return result;
            };
            ServiceLocator.Regist(container =>
            {
                container.RegisterType(typeof(IUserService), typeof(UserService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(IBranchService), typeof(BranchService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(IContractService), typeof(ContractService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(IMenuService), typeof(MenuService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(ISpecialService), typeof(SpecialService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(IPaymentService), typeof(PaymentService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(IInvoiceService), typeof(InvoiceService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(IShortMessageService), typeof(ShortMessageService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(ICollectInvoiceService), typeof(CollectInvoiceService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(IGatheringService), typeof(GatheringService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(IDebitService), typeof(DebitService), new InterceptionArguments<ServcieBeheavior>());
                container.RegisterType(typeof(InsuranceInterfaceService), typeof(InsuranceService), new InterceptionArguments<ServcieBeheavior>());
            });
        }
コード例 #38
0
ファイル: SyncTest.cs プロジェクト: scubed2010/MongoRedi
 static SyncTest()
 {
     _userRepository = new MongoDBRepository <User>();
 }
コード例 #39
0
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            var exception = actionExecutedContext.Exception;
            HttpResponseMessage httpResponseMessage;
            var dataResult = new DataResult();
            LogManager.getInstance().WriteException("SysLog", exception);
            bool isEMail = false;

            #region 异常处理
            if (exception is BusinessException)
            {
                dataResult.Code = ResponseStatusCode.Error;
                dataResult.Msg = exception.Message;
                httpResponseMessage = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, dataResult);
            }
            else if (exception is AccountLoginInOtherPlacesException)
            {
                dataResult.Code = ResponseStatusCode.Error_NeedReLogin;
                dataResult.Msg = exception.Message;
                httpResponseMessage = actionExecutedContext.Request.CreateResponse(HttpStatusCode.Unauthorized, dataResult);
            }
            else if (exception is UseStatusException)
            {
                dataResult.Code = ResponseStatusCode.Error_UseStatus;
                dataResult.Msg = exception.Message;
                httpResponseMessage = actionExecutedContext.Request.CreateResponse(HttpStatusCode.Unauthorized, dataResult);
            }
            else if (exception is AuthorizeException)
            {
                isEMail = true;
                dataResult.Code = ResponseStatusCode.Error_Unauthorized;
                dataResult.Msg = exception.Message;
                httpResponseMessage = actionExecutedContext.Request.CreateResponse(HttpStatusCode.Unauthorized, dataResult);
            }
            else if (exception is DataOperationPermissions)
            {
                isEMail = true;
                dataResult.Code = ResponseStatusCode.Error_Forbidden;
                dataResult.Msg = exception.Message;
                httpResponseMessage = actionExecutedContext.Request.CreateResponse(HttpStatusCode.Forbidden, dataResult);
            }
            else if (exception is DataValidationException)
            {
                dataResult.Code = ResponseStatusCode.Error;
                dataResult.Msg = exception.Message;
                httpResponseMessage = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, dataResult);
            }
            else if (exception is QueryArgumentException)
            {
                dataResult.Code = ResponseStatusCode.Error;
                dataResult.Msg = exception.Message;
                httpResponseMessage = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, dataResult);
            }
            else if (exception is ArgumentException)
            {
                dataResult.Code = ResponseStatusCode.Error;
                dataResult.Msg = exception.Message;
                httpResponseMessage = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, dataResult);
            }
            else if (exception is DataConcurrencyException)
            {
                dataResult.Code = ResponseStatusCode.Error_Concurrency;
                dataResult.Msg = exception.Message;
                httpResponseMessage = actionExecutedContext.Request.CreateResponse(HttpStatusCode.Conflict, dataResult);
            }
            else
            {
                isEMail = true;
                dataResult.Code = ResponseStatusCode.Error;
                dataResult.Msg = "系统异常,请联系管理员";
                httpResponseMessage = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, dataResult);
            }
            #endregion

            actionExecutedContext.Response = httpResponseMessage;

            var messageInfo = new MessageInfo();
            messageInfo.Message = "异常信息";
            messageInfo.Body = exception;
            messageInfo.Action = (messageData) =>
            {
                var bodyData = messageData.Body as Exception;
                if (bodyData == null) return;
                var exceptionLog = LogEntityUtils.GetExceptionLog(bodyData);

                var mongoDbRepository = new MongoDBRepository<ExceptionLog>();
                mongoDbRepository.Insert(exceptionLog);

                MailHelper.SendEmail(bodyData);

            };
            QueueManagement.getInstance().PushData(messageInfo);

            base.OnException(actionExecutedContext);
        }
コード例 #40
0
        public async Task TestDelete(string id)
        {
            var repository = new MongoDBRepository();
            await repository.Delete<BaseEntity>(Guid.Parse(id));

            Assert.Throws(typeof(AggregateException), delegate
            {
                var entity = repository.Get<BaseEntity>(Guid.Parse(id)).Result;
            });

        }
コード例 #41
0
 public async Task TestGetById(string id)
 {
     var repository = new MongoDBRepository();
     var entity = await repository.Get<BaseEntity>(Guid.Parse(id));
     Assert.Equal<Guid>(Guid.Parse(id), entity.Id);
 }
コード例 #42
0
 public async Task TestInsert()
 {
     var repository = new MongoDBRepository();
     var entity = await repository.Insert(new BaseEntity() { Name = "Alice" });
     Assert.Equal<string>("Alice", entity.Name);
 }