public void NewInvocationContextIsConfiguredCorrectly()
 {
     var configuration = new DomainConfiguration();
     configuration.EnsureCommitted();
     var domainContext = new DomainContext(configuration);
     var context = new InvocationContext(domainContext);
     Assert.Same(domainContext, context.DomainContext);
 }
Esempio n. 2
0
        /// <summary>
        /// Creates a new DomainContext and starts its processors, using the previously applied configurations.
        /// </summary>
        /// <returns>A new DomainContext</returns>
        public IDomainContext Start()
        {
            if (this.Configuring != null)
            {
                this.Configuring(this);
            }

            var context = new DomainContext(this.EventStore.Value,
                                            new EventBus(this.MessageBus.Value),
                                            new CommandBus(this.MessageBus.Value),
                                            this.Processors.Value,
                                            this.LoggerFactory.Value,
                                            this.Resolver.Value);

            if (this.Configured != null)
            {
                this.Configured(context);
            }

            this.Configuring = null;
            this.Configured = null;

            context.StartProcessors();

            return context;
        }
 public IEnumerable<PersonConsultation> GetAll()
 {
     var context = new DomainContext(this.ConnectionString);
     return context.PersonConsultations.Include("Doctor").Include("Patient").Include("ConsultationType").Include("PersonConsultationResearches")
         .Include("PersonConsultationLabAnalyzes").Include("PersonConsultationSymptoms").Include("PersonConsultationComplaints")
         .Include("PersonConsultationMeasurings").Include("PersonConsultationDiagnosises").Include("AssignedMedicaments").Include("AssignedMeasurings");
 }
Esempio n. 4
0
		public void WhenHandlerRegistered_ThenCanProcessEntity()
		{
			var id = Guid.NewGuid();
			var product = new Product(id, "DevStore");

			var context = default(IDomainContext);
			var eventStream = new EventStream();
			IDomainEventStore store = new ConsoleEventStore();

			// Keep the handlers so they are not GC'ed.
			var handlers = new object[]
			{ 
				new ConsoleHandler(eventStream), 
				new SendMailHandler(eventStream),
			};

			context = new DomainContext(eventStream, store);
			context.Save(product);

			// Save changes and cause publication of pending events 
			// in the newly created domain object.
			context.SaveChanges();

			Console.WriteLine();

			// Here some command might pull the product from the 
			// context, and invoke a domain method.
			var savedProduct = context.Find<Product>(id);
			product.Publish(1);

			// Saving again causes persistence of the entity state 
			// as well as publishing the events.
			context.SaveChanges();
		}
Esempio n. 5
0
 public IEnumerable<Person> GetAll()
 {
     var context = new DomainContext(this.ConnectionString);
     return context.Persons.Include("AssignedSymptoms").Include("FirstPersonPersons");/*.Include("SecondPersonPersons").Include("PersonContacts").Include("AssignedRiskFactors")
         .Include("Credentials").Include("PersonGroups").Include("PersonOperations").Include("PersonDiseases").Include("PersonAllergicReactions")
         .Include("ConsultationsAsDoctor").Include("ConsultationsAsPatient").Include("PersonHospitalizations");*/
 }
Esempio n. 6
0
 private static IUnitOfWork ReinitializeDatabase(DomainContext dbContext)
 {
     // force to single_user so that we can drop the database in order to prevent this error: "database is currently in use ..."
     dbContext.Database.ExecuteSqlCommand(string.Format("ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE", Fixture.DatabaseName));
     new DatabaseInitializer().InitializeDatabase(dbContext);
     return new UnitOfWork(dbContext);
 }
 public void UnRegister()
 {
     if (this.ctx != null)
     {
         this.ctx.PropertyChanged -= new PropertyChangedEventHandler(this.ctx_PropertyChanged);
     }
     this.ctx = null;
 }
 public void Modify(DomainContext context)
 {
     EntitySet<MockUser> users = context.EntityContainer.GetEntitySet<MockUser>();
     if (!users.Contains(this))
     {
         users.Attach(this);
     }
     this.RaiseDataMemberChanging("MutableProperty");
     this.MutableProperty++;
     this.RaiseDataMemberChanged("MutableProperty");
 }
        public IEnumerable<PersonConsultationLabAnalyze> GetEntitiesByQuery(Func<PersonConsultationLabAnalyze, bool> query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var context = new DomainContext(this.ConnectionString))
            {
                return context.PersonConsultationLabAnalyzes.Include("LabAnalyzeType").Include("PersonConsultation").Where(query).ToList();
            }
        }
        public IEnumerable<AssignedRiskFactor> GetEntitiesByQuery(Func<AssignedRiskFactor, bool> query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var context = new DomainContext(this.ConnectionString))
            {
                return context.AssignedRiskFactors.Include("Person").Include("RiskFactor").Where(query).ToList();
            }
        }
Esempio n. 11
0
        public IEnumerable<Research> GetEntitiesByQuery(Func<Research, bool> query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var context = new DomainContext(this.ConnectionString))
            {
                return context.Researches.Include("PersonConsultationResearches").Where(query).ToList();
            }
        }
        public static void ChangeSentTimeout(DomainContext aContext, TimeSpan aSendTimeout)
        {
            PropertyInfo lChangeFactoryProperty = aContext.DomainClient.GetType().GetProperty("ChannelFactory");
            if (lChangeFactoryProperty == null)
            {
                throw new InvalidOperationException("There is no ChannelFactory property on the DomainClient.");
            }

            ChannelFactory lFactory = (ChannelFactory)lChangeFactoryProperty.GetValue(aContext.DomainClient, null);
            lFactory.Endpoint.Binding.ReceiveTimeout = aSendTimeout;
            lFactory.Endpoint.Binding.ReceiveTimeout = aSendTimeout;
        }
        public IEnumerable<HospitalDepartment> GetEntitiesByQuery(Func<HospitalDepartment, bool> query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var context = new DomainContext(this.ConnectionString))
            {
                return context.HospitalDepartments.Include("Hospital").Include("PersonHospitalizations").Where(query).ToList();
            }
        }
        public IEnumerable<PersonAllergicReaction> GetEntitiesByQuery(Func<PersonAllergicReaction, bool> query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var context = new DomainContext(this.ConnectionString))
            {
                return context.PersonAllergicReactions.Include("Person").Include("AllergicReaction").Where(query).ToList();
            }
        }
        public IEnumerable<OnceRiskFactorNotification> GetEntitiesByQuery(Func<OnceRiskFactorNotification, bool> query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var context = new DomainContext(this.ConnectionString))
            {
                return context.OnceRiskFactorNotifications.Where(query).ToList();
            }
        }
Esempio n. 16
0
        public IEnumerable<AsignedSymptom> GetEntitiesByQuery(Func<AsignedSymptom, bool> query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var context = new DomainContext(this.ConnectionString))
            {
                return context.AsignedSymptoms.Include("Person").Include("Symptom").Where(query);
            }
        }
        public IEnumerable<AssignedMedicamentMeasuring> GetEntitiesByQuery(Func<AssignedMedicamentMeasuring, bool> query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var context = new DomainContext(this.ConnectionString))
            {
                return context.AssignedMedicamentMeasurings.Include("AssignedMedicament").Include("MeasuringType")
                    .Where(query).ToList();
            }
        }
Esempio n. 18
0
        public IEnumerable<MedicamentForm> GetEntitiesByQuery(Func<MedicamentForm, bool> query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var context = new DomainContext(this.ConnectionString))
            {
                return context.MedicamentForms.Include("Medicaments")
                    .Where(query).ToList();
            }
        }
        public void DeleteEntity(Guid id)
        {
            using (var context = new DomainContext(this.ConnectionString))
            {
                var onceRiskFactorNotification = context.OnceRiskFactorNotifications.FirstOrDefault(v => v.Id == id);
                if (onceRiskFactorNotification == null)
                {
                    return;
                }

                context.OnceRiskFactorNotifications.Remove(onceRiskFactorNotification);
                context.SaveChanges();
            }
        }
        public void DeleteEntity(Guid id)
        {
            using (var context = new DomainContext(this.ConnectionString))
            {
                var allergicReaction = context.AllergicReactions.FirstOrDefault(v => v.Id == id);
                if (allergicReaction == null)
                {
                    return;
                }

                context.AllergicReactions.Remove(allergicReaction);
                context.SaveChanges();
            }
        }
Esempio n. 21
0
        public JsonResult GetGroups(string id)
        {
            int facultId;

            if (int.TryParse(id, out facultId))
            {
                using (var db = new DomainContext())
                {
                    var data = db.Ajax.GroupsByFacult(facultId);
                    return(Json(data, JsonRequestBehavior.AllowGet));
                }
            }
            return(Json(null, JsonRequestBehavior.AllowGet));
        }
Esempio n. 22
0
 public ChatMessageWriteCommand(
     IChatMessageRepository chatMessageRepository,
     IChatRoomListRepository chatRoomListRepository,
     IChatRoomRepository chatRoomRepository,
     IUserRepository userRepository,
     DomainContext domainContext
     )
 {
     _chatMessageRepository  = chatMessageRepository;
     _chatRoomListRepository = chatRoomListRepository;
     _chatRoomRepository     = chatRoomRepository;
     _domainContext          = domainContext;
     _userRepository         = userRepository;
 }
Esempio n. 23
0
        public void DeleteEntity(Guid id)
        {
            using (var context = new DomainContext(this.ConnectionString))
            {
                var riskFactor = context.RiskFactors.FirstOrDefault(v => v.Id == id);
                if (riskFactor == null)
                {
                    return;
                }

                context.RiskFactors.Remove(riskFactor);
                context.SaveChanges();
            }
        }
        public void Save()
        {
            Activity                = new Activity();
            Activity.Name           = Name;
            Activity.ExpectedEffort = int.Parse(ExpectedEffort);
            if (Tags != null)
            {
                Activity.Tags = DomainContext.ActivityTags.GetOrCreate(Tags);
            }
            DomainContext.Activities.Add(Activity);
            DomainContext.Commit();

            Close(true);
        }
Esempio n. 25
0
        public SqliteExporter(string outputPath)
        {
            var path = Path.Combine(outputPath, "database.db");

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            _domainContext = new SqliteDomainContext(path);
            _domainContext.Database.EnsureCreated();
            _domainContext.ChangeTracker.AutoDetectChangesEnabled = false;
            _contextMapper = new MidsDomainContextMapper(_domainContext);
        }
Esempio n. 26
0
        public void DeleteEntity(Guid id)
        {
            using (var context = new DomainContext(this.ConnectionString))
            {
                var symptom = context.Symptoms.FirstOrDefault(v => v.Id == id);
                if (symptom == null)
                {
                    return;
                }

                context.Symptoms.Remove(symptom);
                context.SaveChanges();
            }
        }
Esempio n. 27
0
        public void DeleteEntity(Guid id)
        {
            using (var context = new DomainContext(this.ConnectionString))
            {
                var medicament = context.Medicaments.FirstOrDefault(v => v.Id == id);
                if (medicament == null)
                {
                    return;
                }

                context.Medicaments.Remove(medicament);
                context.SaveChanges();
            }
        }
        public void DeleteEntity(Guid id)
        {
            using (var context = new DomainContext(this.ConnectionString))
            {
                var personConsultationMeasuring = context.PersonConsultationMeasurings.FirstOrDefault(v => v.Id == id);
                if (personConsultationMeasuring == null)
                {
                    return;
                }

                context.PersonConsultationMeasurings.Remove(personConsultationMeasuring);
                context.SaveChanges();
            }
        }
        public void DeleteEntity(Guid id)
        {
            using (var context = new DomainContext(this.ConnectionString))
            {
                var consultationType = context.ConsultationTypes.FirstOrDefault(v => v.Id == id);
                if (consultationType == null)
                {
                    return;
                }

                context.ConsultationTypes.Remove(consultationType);
                context.SaveChanges();
            }
        }
Esempio n. 30
0
        public void DeleteEntity(Guid id)
        {
            using (var context = new DomainContext(this.ConnectionString))
            {
                var hospital = context.Hospitals.FirstOrDefault(v => v.Id == id);
                if (hospital == null)
                {
                    return;
                }

                context.Hospitals.Remove(hospital);
                context.SaveChanges();
            }
        }
Esempio n. 31
0
        public void DeleteEntity(Guid id)
        {
            using (var context = new DomainContext(this.ConnectionString))
            {
                var diagnosis = context.Diagnosises.FirstOrDefault(v => v.Id == id);
                if (diagnosis == null)
                {
                    return;
                }

                context.Diagnosises.Remove(diagnosis);
                context.SaveChanges();
            }
        }
Esempio n. 32
0
        public static void ChangeSentTimeout(DomainContext aContext, TimeSpan aSendTimeout)
        {
            PropertyInfo lChangeFactoryProperty = aContext.DomainClient.GetType().GetProperty("ChannelFactory");

            if (lChangeFactoryProperty == null)
            {
                throw new InvalidOperationException("There is no ChannelFactory property on the DomainClient.");
            }

            ChannelFactory lFactory = (ChannelFactory)lChangeFactoryProperty.GetValue(aContext.DomainClient, null);

            lFactory.Endpoint.Binding.ReceiveTimeout = aSendTimeout;
            lFactory.Endpoint.Binding.ReceiveTimeout = aSendTimeout;
        }
Esempio n. 33
0
        protected string GetReplyTextMessage(DomainContext domainContext, string toUserName, string content)
        {
            ResponsiveXMLMessage_TextMessage replyMessage = new ResponsiveXMLMessage_TextMessage();

            replyMessage.Content = content;

            replyMessage.ToUserName = toUserName;
            //这几个字段还是要的,因为当直接以HTTP返回的形式返回XML格式的数据时
            //是要求这几个字段的
            replyMessage.FromUserName = domainContext.UserName;
            replyMessage.CreateTime   = WeixinApiHelper.ConvertDateTimeToInt(DateTime.Now);

            return(XMLMessageHelper.XmlSerialize(replyMessage));
        }
Esempio n. 34
0
 public AccountController(ILogger <AccountController> logger, IUserService userService, IJwtAuthService jwtAuthManager, INewsRepository newsRepository, IEmployeeRepository employeeRepository, IVoteListRepository voteListRepository, DomainContext context, SystemContext systemContext, IReadCommand <ProfileResult> profileReadCommand, IVoteRepository voteRepository)
 {
     _logger             = logger;
     _userService        = userService;
     _jwtAuthManager     = jwtAuthManager;
     _employeeRepository = employeeRepository;
     _voteListRepository = voteListRepository;
     _newsRepository     = newsRepository;
     _context            = context;
     _systemContext      = systemContext;
     _voteListRepository = voteListRepository;
     _profileReadCommand = profileReadCommand;
     _voteRepository     = voteRepository;
 }
        public ActionResult MemberInfo()
        {
            WeixinJsApiConfig jsApiConfig = new WeixinJsApiConfig();

            jsApiConfig = DomainContext.GetJsApiConfig(HttpContext.Request.Url.ToString());
            jsApiConfig.JsApiList.Add("scanQRCode");
            ViewBag.JsApiConfig = jsApiConfig;

            MemberInfoViewModel model = new MemberInfoViewModel();

            model.MemberCardLevelList = _memberManager.GetMemberCardList(DomainContext.Domain.Id,
                                                                         DomainContext.AppId);
            return(View(model));
        }
Esempio n. 36
0
 public ActionResult AddFromTxt(TxtFile model)
 {
     if (ModelState.IsValid)
     {
         using (var db = new DomainContext())
         {
             var result = db.Auditories.AddListFromTxt(model.Txt);
             db.SaveChanges();
             ViewBag.Result = result;
             return(View());
         }
     }
     return(View(model));
 }
Esempio n. 37
0
        public ActionResult Create(Lector lector)
        {
            if (ModelState.IsValid)
            {
                using (var db = new DomainContext())
                {
                    db.Lectors.Add(lector);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }

            return(View(lector));
        }
        public void DeleteEntity(Guid id)
        {
            using (var context = new DomainContext(this.ConnectionString))
            {
                var assignedMedicamentMeasuring = context.AssignedMedicamentMeasurings.FirstOrDefault(v => v.Id == id);
                if (assignedMedicamentMeasuring == null)
                {
                    return;
                }

                context.AssignedMedicamentMeasurings.Remove(assignedMedicamentMeasuring);
                context.SaveChanges();
            }
        }
Esempio n. 39
0
            /// <summary>
            /// Changes the WCF endpoint Timeout for the specified domain context. 
            /// </summary>
            /// <param name="context">The domain context to modify.</param>
            /// <param name="timeout">The new timeout value.</param>
            public static void ChangeWcfTimeout(DomainContext context, TimeSpan timeout)
            {
                PropertyInfo channelFactoryProperty = context.DomainClient.GetType().GetProperty("ChannelFactory");
                if (channelFactoryProperty == null)
                {
                    throw new InvalidOperationException("There is no 'ChannelFactory' property on the DomainClient.");
                }

                ChannelFactory factory = (ChannelFactory) channelFactoryProperty.GetValue(context.DomainClient, null);
                factory.Endpoint.Binding.OpenTimeout = timeout;
                factory.Endpoint.Binding.ReceiveTimeout = timeout;
                factory.Endpoint.Binding.SendTimeout = timeout;
                factory.Endpoint.Binding.CloseTimeout = timeout;
            }
Esempio n. 40
0
        public IEnumerable<Person> GetEntitiesByQuery(Func<Person, bool> query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var context = new DomainContext(this.ConnectionString))
            {
                return context.Persons.Include("AssignedSymptoms").Include("FirstPersonPersons").Include("SecondPersonPersons").Include("PersonContacts").Include("AssignedRiskFactors")
                    .Include("Credentials").Include("PersonGroups").Include("PersonOperations").Include("PersonDiseases").Include("PersonAllergicReactions")
                    .Include("ConsultationsAsDoctor").Include("ConsultationsAsPatient").Include("PersonHospitalizations")
                    .Where(query).ToList();
            }
        }
        private static void Print(DomainContext context)
        {
            var queryCompetion = context.Competions
                                 .Include(c => c.Players)
                                 .Include(c => c.Games)
                                 .ThenInclude(c => c.Competitors)
                                 .OrderBy(c => c.Id)
                                 .Last();

            // PrintWithBetterConsoleTables.Print(queryCompetion);
            // PrintWithConsoleTables.Print(queryCompetion);
            PrintWithConsoleTableExt.Print(queryCompetion);

            // PrintCompetition2(context);
        }
Esempio n. 42
0
        public ReadModel(IStreamResolver streamResolver, IEventLookup eventLookup,
                         IDataContext dataContext, IDatabaseLookup databaseLookup)
        {
            _eventLookup = eventLookup;
            _dataContext = dataContext;

            _eventHandlers = new List <Action <BaseEvent> >();

            var eventDbFile = databaseLookup.GetDatabase(streamResolver.GetStream());
            var options     = new DbContextOptionsBuilder <DomainContext>()
                              .UseSqlite($"Data Source={eventDbFile}")
                              .Options;

            _context = new DomainContext(options);
        }
 public EmployeeWriteCommand(
     IContactRepository contactRepository,
     IPassportRepository passportRepository,
     IOrganizationRepository organizationRepository,
     IStateRegistrationRepository stateRegistrationRepository,
     IEmployeeRepository employeeRepository,
     DomainContext domainContext)
 {
     _contactRepository           = contactRepository;
     _passportRepository          = passportRepository;
     _organizationRepository      = organizationRepository;
     _stateRegistrationRepository = stateRegistrationRepository;
     _employeeRepository          = employeeRepository;
     _domainContext = domainContext;
 }
Esempio n. 44
0
 public InvitationWriteCommand(
     IAlienRepository alienRepository,
     IEmployeeRepository employeeRepository,
     IInvitationRepository invitationRepository,
     IVisitDetailRepository visitDetailRepository,
     AlienWriteCommand alienWriteCommand,
     DomainContext domainContext)
 {
     _alienRepository       = alienRepository;
     _employeeRepository    = employeeRepository;
     _invitationRepository  = invitationRepository;
     _visitDetailRepository = visitDetailRepository;
     _alienWriteCommand     = alienWriteCommand;
     _domainContext         = domainContext;
 }
Esempio n. 45
0
 public ReportController(
     IReportRepository reportRepository,
     IInvitationRepository invitationRepository,
     IDepartureRepository departureRepository,
     IAppendixRepository appendixRepository,
     IListOfScientistRepository listOfScientistRepository,
     DomainContext domainContext)
 {
     _reportRepository          = reportRepository;
     _invitationRepository      = invitationRepository;
     _departureRepository       = departureRepository;
     _appendixRepository        = appendixRepository;
     _domainContext             = domainContext;
     _listOfScientistRepository = listOfScientistRepository;
 }
Esempio n. 46
0
 public void CanNotCreateDatabaseIfNotConfigured()
 {
     using (var db = new DomainContext(new DbContextOptionsBuilder <DomainContext>().Options))
     {
         bool isCreated = false;
         try
         {
             isCreated = db.Database.EnsureCreated();
         }
         catch (Exception ex)
         {
             isCreated = false;
         }
         Assert.False(isCreated);
     }
 }
 public static void ChangeWcfTimeout(DomainContext context, TimeSpan sendTimeout, TimeSpan receiveTimeout)
 {
     try
     {
         PropertyInfo property = context.GetType().GetProperty("ChannelFactory");
         if (property != null)
         {
             System.ServiceModel.ChannelFactory factory = (System.ServiceModel.ChannelFactory)property.GetValue(context, null);
             factory.Endpoint.Binding.ReceiveTimeout = receiveTimeout;
             factory.Endpoint.Binding.SendTimeout    = sendTimeout;
         }
     }
     catch (Exception e)
     {
     }
 }
Esempio n. 48
0
        protected override void OnDocking(DomainContext domainContext)
        {
            base.OnDocking(domainContext);

            ManagementDomainContext managementDomainContext = domainContext as ManagementDomainContext;

            if (managementDomainContext != null)
            {
                managementDomainContext.SyncMember();
            }
            else
            {
                _logService.Write("ManagementDomainPool 在处理 Docking 事件时遇到了非 ManagementDomainContext ",
                                  TraceEventType.Error);
            }
        }
Esempio n. 49
0
        public void Execute(IJobExecutionContext context)
        {
            List <MemberEntity> needUpdateMemberList = _memberManager.GetNeedUpdateList();

            if (needUpdateMemberList == null || needUpdateMemberList.Count == 0)
            {
                return;
            }

            _log.Write("更新会员信息", String.Format("取得待更新会员数:{0}", needUpdateMemberList.Count), TraceEventType.Verbose);

            foreach (MemberEntity member in needUpdateMemberList)
            {
                DomainContext domainContext = _domainPool.GetDomainContext(member.Domain);

                if (domainContext == null)
                {
                    _memberManager.NeedUpdate(member.Id, false);
                    _log.Write("更新会员信息失败", "没有Domain信息\r\n" + JsonHelper.Serializer(member), TraceEventType.Warning);
                    continue;
                }

                RequestApiResult <WeixinUser> getUserInfoResult =
                    UserApiWrapper.GetUserInfo(domainContext, member.OpenId);

                if (getUserInfoResult.Success == false)
                {
                    _log.Write("更新会员信息失败", JsonHelper.Serializer(getUserInfoResult), TraceEventType.Warning);
                    continue;
                }

                if (getUserInfoResult.ApiResult.Subscribe == 0)
                {
                    _memberManager.NeedUpdate(member.Id, false);
                    continue;
                }

                AddMemberArgs args = new AddMemberArgs();
                args.WeixinUser = getUserInfoResult.ApiResult;
                //更新当前用户信息
                _memberManager.UpdateMember(member, args);

                _memberManager.NeedUpdate(member.Id, false);
            }

            _log.Write("更新会员信息", "更新完毕。", TraceEventType.Verbose);
        }
Esempio n. 50
0
        private static void AddPersistancy(this IServiceCollection services, ProvisioningBrokerOptions brokerOptions = default)
        {
            services.AddDbContext <DomainContext>(options =>
            {
                var callingAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
                var connectionString    = brokerOptions?.ConnectionStrings?.GetValue <string>(nameof(DomainContext));

                if (string.IsNullOrEmpty(connectionString))
                {
                    return;
                }

                services.AddSingleton(factory =>
                {
                    var connection = new SqliteConnection(connectionString);

                    connection.Open();

                    return(connection);
                });

                var dbOptions = options.UseSqlite(services.BuildServiceProvider().GetService <SqliteConnection>(),
                                                  sqliteOptions =>
                {
                    sqliteOptions.MigrationsAssembly(callingAssemblyName);
                    sqliteOptions.MigrationsHistoryTable(callingAssemblyName + "_MigrationHistory");
                }).Options;

                using var context = new DomainContext(dbOptions, new FakeMediator());

                if (!context.Database.EnsureCreated())
                {
                    return;
                }

                if (brokerOptions.EnableAutoMigrations)
                {
                    context.Database.Migrate();
                }

                var seedingTask = DomainContextSeeder.SeedAsync(context);

                seedingTask.Wait();
            });

            services.AddScoped <IUnitOfWork>(factory => factory.GetRequiredService <DomainContext>());
        }
Esempio n. 51
0
        public void Open()
        {
            this.OnOpening(EventArgs.Empty);
            this.dispatcher.Invoke(() =>
            {
                this.Info(Resources.Message_ProgramInfo, AppUtility.ProductName, AppUtility.ProductVersion);

                this.repository = this.repositoryProvider.CreateInstance(this.repositoryPath, this.workingPath);
                this.Info("Repository module : {0}", this.settings.RepositoryModule);
                this.Info("Repository path : " + this.repositoryPath);
                foreach (var logger in this.GetService <IEnumerable <ILogService> >())
                {
                    this.Info($"{logger.Name} log path : {logger.FileName}");
                }
                this.Info(Resources.Message_ServiceStart);

                this.configs = new CremaConfiguration(Path.Combine(this.basePath, "configs.xml"), this.propertiesProvider);

                this.userContext = new UserContext(this);
                this.userContext.Dispatcher.Invoke(() => this.userContext.Initialize());
                this.dataBases     = new DataBaseCollection(this);
                this.domainContext = new DomainContext(this, this.userContext);

                if (this.settings.NoCache == false)
                {
                    foreach (var item in this.dataBases)
                    {
                        this.domainContext.Restore(Authentication.System, item);
                    }
                }

                this.plugins = this.container.GetService(typeof(IEnumerable <IPlugin>)) as IEnumerable <IPlugin>;
                this.plugins = this.plugins.TopologicalSort();
                foreach (var item in this.plugins)
                {
                    var authentication = new Authentication(new AuthenticationProvider(item), item.ID);
                    item.Initialize(authentication);
                    this.Info("Plugin : {0}", item.Name);
                }

                this.dispatcher.InvokeAsync(() => this.dataBases.RestoreState(this.settings));

                GC.Collect();
                this.Info("Crema module has been started.");
                this.OnOpened(EventArgs.Empty);
            });
        }
Esempio n. 52
0
        public ActionResult Archive(string code)
        {
            if (code != "ARCHIVEREN")
            {
                ViewBag.Message = "Invoer incorrect, probeer opnieuw.";
                return(View());
            }

            //ViewBag.Message = "code: " + code;

            using (var context = new DomainContext())
            {
                context.SP_ArchiveYear();
            }

            return(View());
        }
Esempio n. 53
0
    /// <summary>
    /// Changes the WCF endpoint SendTimeout for the specified domain
    /// context.
    /// </summary>
    /// <param name="context">The domain context to modify.</param>
    /// <param name="sendTimeout">The new timeout value.</param>
    public static void ChangeWcfSendTimeout(DomainContext context,
                                            TimeSpan sendTimeout)
    {
        PropertyInfo channelFactoryProperty =
            context.DomainClient.GetType().GetProperty("ChannelFactory");

        if (channelFactoryProperty == null)
        {
            throw new InvalidOperationException(
                      "There is no 'ChannelFactory' property on the DomainClient.");
        }

        ChannelFactory factory = (ChannelFactory)
                                 channelFactoryProperty.GetValue(context.DomainClient, null);

        factory.Endpoint.Binding.SendTimeout = sendTimeout;
    }
 public void GetById_returns_no_aggregate_with_a_different_ID_than_defined()
 {
     Given("a set of events with different aggregate ids in an event store",
           testContext =>
     {
         var eventStore = new InMemoryEventStore();
         eventStore.Insert(Uuid.NewId(), "Customer", new List <DomainEvent> {
             new CustomerCreated(), new CustomerNameChanged()
         });
         eventStore.Insert(Uuid.NewId(), "Customer", new List <DomainEvent> {
             new CustomerCreated()
         });
         eventStore.Insert(Uuid.NewId(), "Customer", new List <DomainEvent> {
             new CustomerCreated()
         });
         testContext.State.EventStore = eventStore;
     })
     .And("an empty snapshot store",
          testContext =>
     {
         testContext.State.SnapshotStore = new InMemorySnapshotStore();
     })
     .And("a configured domain context",
          testContext =>
     {
         var eventBus                    = new Mock <IEventBus>().Object;
         IEventStore eventStore          = testContext.State.EventStore;
         ISnapshotStore snapshotStore    = testContext.State.SnapshotStore;
         var domainRepository            = new DomainRepository(eventStore, snapshotStore);
         var domainContext               = new DomainContext(eventBus, eventStore, snapshotStore, domainRepository);
         testContext.State.DomainContext = domainContext;
     })
     .When("GetById for an aggregate with unknown id is called",
           testContext =>
     {
         var aggregate =
             ((DomainContext)testContext.State.DomainContext).GetById <Customer>(Uuid.NewId());
         testContext.State.Aggregate = aggregate;
     })
     .Then("it should return null",
           testContext =>
     {
         object obj = testContext.State.Aggregate;
         obj.Should().BeNull();
     });
 }
Esempio n. 55
0
        /// <inheritdoc/>
        public bool TryGetRelevantType(
            DomainContext context,
            string name,
            out Type relevantType)
        {
            relevantType = null;
            var entitySetProperty = this.AddedEntitySets
                                    .SingleOrDefault(p => p.Name == name);

            if (entitySetProperty != null)
            {
                relevantType = entitySetProperty
                               .PropertyType.GetGenericArguments()[0];
            }

            return(relevantType != null);
        }
Esempio n. 56
0
        public ResponseWrapper <List <LoginModel> > GetLogins()
        {
            using (var db = new DomainContext())
            {
                var logins   = db.Logins.ToList();
                var response = logins
                               .Select(x =>
                                       new LoginModel
                {
                    LoginId  = x.LoginId,
                    Username = x.Username
                })
                               .ToList();

                return(new ResponseWrapper <List <LoginModel> >(_validationDictionary, response));
            }
        }
        // ToDo: Read Dependency Injection

        private static void Execute(DomainContext context, string[] playerNames)
        {
            Console.WriteLine("Create Context");

            var competion = new Competion();

            context.Competions.Add(competion);
            // context.Players.AddIfNotExist((p) => p.Name == "david" )

            competion.RegisterPlayers(playerNames);
            competion.GenerateGames();
            competion.Start();

            context.SaveChanges();

            PrintCompetition(competion);
        }
Esempio n. 58
0
        public DatabaseFixture()
        {
            var configuration = new ConfigurationBuilder()
                                .AddUserSecrets("57a04ea5-19b4-483f-af4d-a96930e166e5")
                                .Build();

            TestDatabase = new TestDatabaseBuilder()
                           .WithConfiguration(configuration)
                           .Build();
            TestDatabase.Create();

            var builder = new DbContextOptionsBuilder <DomainContext>()
                          .UseNpgsql(TestDatabase.ConnectionString);

            DbContext = new DomainContext(builder.Options);
            DbContext.Database.EnsureCreated();
        }
Esempio n. 59
0
        public void SetUp()
        {
            _connection = new SqliteConnection("datasource=:memory:");
            _connection.Open();

            var options = new DbContextOptionsBuilder <DomainContext>()
                          .UseSqlite(_connection)
                          .Options;

            typeof(Root).GetFields(BindingFlags.Static | BindingFlags.NonPublic)
            .Single(f => f.FieldType == typeof(Container))
            .SetValue(null, new Container());
            Root.InitializeContainer(options);

            _dbContext = Root.Container.GetInstance <DomainContext>();
            _dbContext.Database.EnsureCreated();
        }
        protected override void SetUpEachTest()
        {
            base.SetUpEachTest();

            MockRepository     = NewMock <IRepository>();
            MockDomainFactory  = NewMock <IDomainFactory>();
            MockQueryFactory   = NewMock <IQueryFactory>();
            MockNetworkContext = NewMock <INetworkContext>();

            var logger = new MultiLogger(LogggersToUse.ToArray());

            ApplicationContext.Setup(new StaticContextStorage(), logger, MockNetworkContext.Object);
            EnableComparisonLogging();

            DomainContext.Setup(MockRepository.Object,
                                MockDomainFactory.Object,
                                MockQueryFactory.Object);
        }