/// <summary>
 /// Gets a collection of all application events from the data store. The items are sorted in descending order on the
 /// <see cref="IEvent.TimestampUtc"/> property, so the most recent event is first. Returns an empty collection if no
 /// events exist.
 /// </summary>
 /// <returns>Returns a collection of all application events from the data store.</returns>
 public static IEventCollection GetAppEvents()
 {
     using (var repo = new EventRepository())
     {
         return GetEventsFromDtos(repo.GetAll().OrderByDescending(e => e.TimeStampUtc));
     }
 }
        public ActionResult Edit(int? id)
        {
            Event CHevent;

            if (!id.HasValue)
            {
                CHevent = new Event();
            }
            else
            {
                CHevent = new EventRepository().GetByID(id.Value);
                if (CHevent == null)
                {
                    return RedirectToAction("List");
                }
            }

            EventsEditVM model = new EventsEditVM();
            model.ID = CHevent.ID;
            model.Name = CHevent.Name;
            model.Start = CHevent.Start;
            model.End = CHevent.End;
            model.HallID = CHevent.HallID;
            model.Halls = GetHalls();

            model.Users = PopulateAssignedUsers(CHevent);

            return View(model);
        }
Example #3
0
 /// <summary>Creates an instance for the given language.</summary>
 /// <param name="culture">The culture.</param>
 /// <returns>A repository.</returns>
 public IEventRepository ForCulture(CultureInfo culture)
 {
     Contract.Ensures(Contract.Result<IEventRepository>() != null);
     IEventRepository repository = new EventRepository(this.serviceClient);
     repository.Culture = culture;
     return repository;
 }
    public async Task<ActionResult> Create(EventModel model) {
      EventRepository repo = new EventRepository();

      await repo.CreateCalendarEvent(model);

      return RedirectToAction("Index");
    }
Example #5
0
        public void CanCreateAlarmTypeAndLog()
        {
            IRepository<AlarmType> repoA = new AlarmTypeRepository();
            AlarmType alarm = new AlarmType();
            alarm.NameAlarmType = "PruebaAlarma";
            alarm.Description = "Prueba descriptiva alarma";

            repoA.Save(alarm);

            IRepository<User> repoB = new UserRepository();
            User user = new User();
            user = repoB.GetById(1);
            IRepository<Event> repoC = new EventRepository();
            Event eventt = new Event();
            eventt = repoC.GetById(2);

            IRepository<Log> repoD = new LogRepository();
            Log log = new Log();
            log.DateTime = DateTime.Now;
            log.Text = "Prueba descriptiva log";
            log.Event = eventt;
            log.User = user;

            repoD.Save(log);
        }
    public async Task<ActionResult> Index() {
      EventRepository repo = new EventRepository();
      
      var events = await repo.GetCalendarEvents();

      return View(events);
    }
Example #7
0
 /// <summary>
 /// Gets events from storage.
 /// </summary>
 /// <returns>Event list.</returns>
 public List<Event> GetAll()
 {
     using (var repo = new EventRepository())
     {
         return repo.GetAll();
     }
 }
        public override void SetUp()
        {
            base.SetUp();

            DatabaseHelper.CleanEvents();
            DatabaseHelper.CleanEventStreams();

            var eventRepository = new EventRepository(DatabaseHelper.GetConnectionStringBuilder());

            EventSerializer = new Serialization.Newtonsoft.EventSerializer();

            var logger = new SerilogLogger(Log.ForContext<EventStore>());

            var eventStore = new EventStore(
                EventSerializer,
                eventRepository,
                logger,
                Guid.NewGuid);

            AggregateContext = new AggregateContext(
                eventStore,
                null, // TODO: replace with actual SnapshotStore
                new AggregateHydrator(),
                new DummyDispatcher());
        }
        public void All_Returns_Correct_Result(
            EventRepository sut, IEnumerable<Event> data )
        {
            Database.Open().Events.Insert(data);

            var result = sut.All();
            result.ShouldAllBeEquivalentTo(data);
        }
Example #10
0
 public int DeleteEvent(Event eventToDelete)
 {
     using (var repo = new EventRepository())
     {
         repo.Delete(eventToDelete);
         return repo.Save();
     }
 }
Example #11
0
        public RepositoryData()
        {
            this._movieRepository = new MovieRepository();
            this._newsRepository = new NewsRepository();
            this._eventRepository = new EventRepository();
            this._loungeRepository= new LoungeItemRepository();

            this.movielist = new List<Movie>();
        }
        public override void SetUp()
        {
            base.SetUp();

            DatabaseHelper.CleanEvents();
            DatabaseHelper.CleanEventStreams();

            _sut = new EventRepository(DatabaseHelper.GetConnectionStringBuilder());
        }
Example #13
0
 /// <summary>
 /// Saves event to storage.
 /// </summary>
 /// <param name="newEvent">Entity to save.</param>
 /// <returns>The number of events, that does not have saved. Return 0 if everising OK.</returns>
 public int AddEvent(Event newEvent)
 {
     ValidateEvent(newEvent);
     using (var repo = new EventRepository())
     {
         repo.Insert(newEvent);
         return repo.Save();
     }
 }
        public CleaningEventsController()
        {
            assetTypes = new AssetTypeRepository(db);
            assets = new AssetRepository(db);
            var customers = new CustomerRepository(db);
            var orders = new OrderRepository(db);
            var events = new EventRepository(db);

            inventory = new InventoryService(assetTypes, assets, customers, orders, events);
        }
        public DeliveryEventsController()
        {
            assetTypes = new AssetTypeRepository(db);
            assets = new AssetRepository(db);
            orders = new OrderRepository(db);
            customers = new CustomerRepository(db);
            var events = new EventRepository(db);

            inventory = new InventoryService(assetTypes, assets, customers, orders, events);
            shop = new ShopService(orders, customers);
        }
        public ActionResult Edit()
        {
            EventsEditVM model = new EventsEditVM();
            TryUpdateModel(model);

            EventRepository eventRep = new EventRepository(unitOfWork);

            string selectedUsers = Request.Form["assignedUsers"];
            string[] assignedUsers;
            if (selectedUsers == null)
            {
                assignedUsers = new string[0];
            }
            else
            {
                assignedUsers = selectedUsers.Split(',');
            }

            Event CHevent;
            if (model.ID == 0)
            {
                CHevent = new Event();
            }
            else
            {
                CHevent = eventRep.GetByID(model.ID);
                if (CHevent == null)
                {
                    return RedirectToAction("List");
                }
            }

            if (!ModelState.IsValid)
            {
                model.Users = PopulateAssignedUsers(CHevent);
                model.Halls = GetHalls();

                return View(model);
            }

            CHevent.ID = model.ID;
            CHevent.Name = model.Name;
            CHevent.Start = model.Start;
            CHevent.End = model.End;
            CHevent.HallID = model.HallID;
            UpdateEventUsers(CHevent, assignedUsers);

            eventRep.Save(CHevent);
            unitOfWork.Commit();

            System.Threading.Tasks.Task.Run(() => EmailService.SendEmail(CHevent.Users));

            return RedirectToAction("List");
        }
Example #17
0
        /// <summary>
        /// Permanently delete all events from the data store that are system-wide (that is, not associated with a specific gallery) and also
        /// those events belonging to the specified <paramref name="galleryId" />.
        /// </summary>
        /// <param name="galleryId">The gallery ID.</param>
        public static void ClearEventLog(int galleryId)
        {
            using (var repo = new EventRepository())
            {
                foreach (var eDto in repo.Where(e => e.FKGalleryId == galleryId || e.Gallery.IsTemplate))
                {
                    repo.Delete(eDto);
                }

                repo.Save();
            }
        }
Example #18
0
        /// <summary>
        /// Permanently remove the specified event from the data store.
        /// </summary>
        /// <param name="eventId">The value that uniquely identifies this application event (<see cref="IEvent.EventId"/>).</param>
        public static void Delete(int eventId)
        {
            using (var repo = new EventRepository())
            {
                var aeDto = repo.Find(eventId);

                if (aeDto != null)
                {
                    repo.Delete(aeDto);
                    repo.Save();
                }
            }
        }
Example #19
0
        static void Main(string[] args)
        {
            GenericEventHubDb context = new GenericEventHubDb();

            IGenericRepository<Event> genericEventRepo = new GenericRepository<Event>(context);
            IEventRepository eventRepo = new EventRepository(genericEventRepo);

            IGenericRepository<Activity> genericActivityRepo = new GenericRepository<Activity>(context);
            IActivityRepository activityRepo = new ActivityRepository(genericActivityRepo);

            var generator = new EventGenerator(eventRepo, activityRepo);

            // Generate events for next week
            generator.CreateEventsForNextWeek();
        }
Example #20
0
 /// <summary>
 /// Initialize the database and repositories. Inject the database context to repositories.
 /// </summary>
 public BaseController()
 {
     var db = new BarContext();
     BarRepository = new BarRepository(db);
     BottleRepository = new BottleRepository(db);
     DrinkRepository = new DrinkRepository(db);
     DrinkBarRepository = new DrinkBarRepository(db);
     EventRepository = new EventRepository(db);
     IngredientDrinkRepository = new IngredientDrinkRepository(db);
     IngredientRepository = new IngredientRepository(db);
     OrderDrinkRepository = new OrderDrinkRepository(db);
     OrderRepository = new OrderRepository(db);
     QuantityRepository = new QuantityRepository(db);
     UnitRepository = new UnitRepository(db);
     UserBarRepository = new UserBarRepository(db);
     UserRepository = new UserRepository(db);
     UserRoleRepository = new UserRoleRepository(db);
 }
        public void Save()
        {
            IEventRepository iEventRepository = new EventRepository(this.connectionString);

            EventItem eventItem = new EventItem
                (
                    "data",
                    AppActs.DomainModel.Enum.EventType.ApplicationOpen,
                    "openScreen",
                    100,
                    "Main",
                    Guid.NewGuid(),
                    DateTime.Now,
                    "1.1"
                );

            iEventRepository.Save(this.Application.Id, this.Device.Id, eventItem);
        }
Example #22
0
        public void CanGetCreatedItem()
        {
            IEventRepository eventRepository = new EventRepository(Context);
            const string testName            = "Test Event";

            var newEventDto = new EventDto
                                      {
                                          ChurchId = 1,
                                          Name = testName
                                      };

            var eventId     = eventRepository.SaveItem(newEventDto);
            var eventItem   = eventRepository.GetItem(eventId);

            Assert.That(eventItem.Name, Is.EqualTo(testName));

            eventRepository.DeleteItem(eventId);
        }
 public OctopusRepository(IOctopusClient client)
 {
     this.Client = client;
     Feeds = new FeedRepository(client);
     Backups = new BackupRepository(client);
     Machines = new MachineRepository(client);
     MachineRoles = new MachineRoleRepository(client);
     MachinePolicies = new MachinePolicyRepository(client);
     Subscriptions = new SubscriptionRepository(client);
     Environments = new EnvironmentRepository(client);
     Events = new EventRepository(client);
     FeaturesConfiguration = new FeaturesConfigurationRepository(client);
     ProjectGroups = new ProjectGroupRepository(client);
     Projects = new ProjectRepository(client);
     Proxies = new ProxyRepository(client);
     Tasks = new TaskRepository(client);
     Users = new UserRepository(client);
     VariableSets = new VariableSetRepository(client);
     LibraryVariableSets = new LibraryVariableSetRepository(client);
     DeploymentProcesses = new DeploymentProcessRepository(client);
     Releases = new ReleaseRepository(client);
     Deployments = new DeploymentRepository(client);
     Certificates = new CertificateRepository(client);
     Dashboards = new DashboardRepository(client);
     DashboardConfigurations = new DashboardConfigurationRepository(client);
     Artifacts = new ArtifactRepository(client);
     Interruptions = new InterruptionRepository(client);
     ServerStatus = new ServerStatusRepository(client);
     UserRoles = new UserRolesRepository(client);
     Teams = new TeamsRepository(client);
     RetentionPolicies = new RetentionPolicyRepository(client);
     Accounts = new AccountRepository(client);
     Defects = new DefectsRepository(client);
     Lifecycles = new LifecyclesRepository(client);
     OctopusServerNodes = new OctopusServerNodeRepository(client);
     Channels = new ChannelRepository(client);
     ProjectTriggers = new ProjectTriggerRepository(client);
     Schedulers = new SchedulerRepository(client);
     Tenants = new TenantRepository(client);
     TagSets = new TagSetRepository(client);
     BuiltInPackageRepository = new BuiltInPackageRepositoryRepository(client);
     ActionTemplates = new ActionTemplateRepository(client);
     CommunityActionTemplates = new CommunityActionTemplateRepository(client);
 }
Example #24
0
        public void Event_Dispatch_CanSendICS()
        {
            EventRepository eventRepo = new EventRepository(_uow);
            AttendeeRepository attendeesRepo = new AttendeeRepository(_uow);
            List<AttendeeDO> attendees =
                new List<AttendeeDO>
                {
                    _fixture.TestAttendee1(),
                    _fixture.TestAttendee2()
                };
            attendees.ForEach(attendeesRepo.Add);

            EventDO eventDO = new EventDO
            {
                Description = "This is my test invitation",
                Summary = @"My test invitation",
                Location = @"Some place!",
                StartDate = DateTime.Today.AddMinutes(5),
                EndDate = DateTime.Today.AddMinutes(15),
                Attendees = attendees,
                Emails = new List<EmailDO>()
            };
            eventRepo.Add(eventDO);
            Calendar.DispatchEvent(_uow, eventDO);

            //Verify success
            //use imap to load unread messages from the test customer account
            //verify that one of the messages is a proper ICS message
            //retry every 15 seconds for 1 minute

            

            //create an Email message addressed to the customer and attach the file.
            
           



            //skip for v.1: add EmailID to outbound queue



        }
Example #25
0
        /// <summary>
        /// Make a new instance for a Log object.
        /// </summary>
        /// <param name="LogMessage"></param>
        /// <param name="EventID"></param>
        /// <param name="UserID"></param>
        /// <returns>A generic object.</returns>
        Object ILoggable.GetNewLog(string LogMessage, int EventID, int UserID)
        {
            var NewLog = new Log();
            IRepository<Event> eventRepo = new EventRepository();
            IRepository<User> eventUser = new UserRepository();

            try
            {
                NewLog.DateTime = DateTime.Now;
                NewLog.Text = LogMessage;
                NewLog.Event = eventRepo.GetById(EventID);
                NewLog.User = eventUser.GetById(UserID);

                return NewLog;
            }
            catch (Exception)
            {
                return null;
            }
        }
Example #26
0
        public RpgController()
        {
            EventRepository = new EventRepository(_context);
            EventLinkItemRepository = new EventLinkItemRepository(_context);
            QuestRepository = new QuestRepository(_context);
            HeroRepository = new HeroRepository(_context);
            SkillRepository = new SkillRepository(_context);
            GuildRepository = new GuildRepository(_context);
            SkillSchoolRepository = new SkillSchoolRepository(_context);
            TrainingRoomRepository = new TrainingRoomRepository(_context);
            CharacteristicRepository = new CharacteristicRepository(_context);
            CharacteristicTypeRepository = new CharacteristicTypeRepository(_context);
            StateRepository = new StateRepository(_context);
            StateTypeRepository = new StateTypeRepository(_context);

            //using (var scope = StaticContainer.Container.BeginLifetimeScope())
            //{
            //    EventRepository = scope.Resolve<IEventRepository>();
            //    QuestRepository = scope.Resolve<IQuestRepository>();
            //    HeroRepository = scope.Resolve<IHeroRepository>();
            //    SkillRepository = scope.Resolve<ISkillRepository>();
            //}
        }
Example #27
0
        public string CheckIntersectionDates(Event newEvent)
        {
            using (var repo = new EventRepository())
            {
                var intersectDates = repo.GetAll(e => (e.DateBegin < newEvent.DateEnd && newEvent.DateBegin < e.DateEnd) && e.Id != newEvent.Id);

                if (intersectDates.Count == 0)
                {
                    return string.Empty;
                }

                var message = "Some events already exists in this period." + Environment.NewLine;
                message = intersectDates.Take(5).Aggregate(message, (current, eventDate) => current +
                (eventDate.Name + " " + eventDate.DateBegin.ToString(DateFormat) + " - " + eventDate.DateEnd.ToString(DateFormat) + ", "));
                if (intersectDates.Count > 5)
                {
                    message += "and others, ";
                }
                message = message.Remove(message.Length - 2, 2) + ".";

                message += Environment.NewLine + Environment.NewLine + "Do you really want to save another event on this period?";
                return message;
            }
        }
Example #28
0
 public QueueAdminController(BookingCandidateRepository candidateRepository, EventRepository eventRepository)
 {
     _candidateRepository = candidateRepository;
     _eventRepository     = eventRepository;
 }
Example #29
0
 public RepositoryTest()
 {
     EventStorage        = Substitute.For <IEventStorage>();
     DomainEventMediator = Substitute.For <IDomainEventMediator>();
     _eventRepository    = new EventRepository(EventStorage, DomainEventMediator);
 }
Example #30
0
 public void Dispose()
 {
     _eventRepository = null;
 }
        private async Task UpdateLastStateEntry(HostsRepository hostsrepo, HostStatesRepository staterepo, EventRepository eventrepo, CancellationToken stoppingToken)
        {
            var hosts = await hostsrepo.GetAllActive();

            await hosts.ForEachAsync(10, async (host) =>
            {
                await UpdateSingleHostStateEntry(hostsrepo, staterepo, eventrepo, host);
            });
        }
Example #32
0
        public EventTest()
        {
            var repository = new EventRepository();

            _eventService = new EventService(repository);
        }
Example #33
0
 public OctopusRepository(IOctopusClient client, RepositoryScope repositoryScope = null)
 {
     Client                    = client;
     Scope                     = repositoryScope ?? RepositoryScope.Unspecified();
     Accounts                  = new AccountRepository(this);
     ActionTemplates           = new ActionTemplateRepository(this);
     Artifacts                 = new ArtifactRepository(this);
     Backups                   = new BackupRepository(this);
     BuiltInPackageRepository  = new BuiltInPackageRepositoryRepository(this);
     CertificateConfiguration  = new CertificateConfigurationRepository(this);
     Certificates              = new CertificateRepository(this);
     Channels                  = new ChannelRepository(this);
     CommunityActionTemplates  = new CommunityActionTemplateRepository(this);
     Configuration             = new ConfigurationRepository(this);
     DashboardConfigurations   = new DashboardConfigurationRepository(this);
     Dashboards                = new DashboardRepository(this);
     Defects                   = new DefectsRepository(this);
     DeploymentProcesses       = new DeploymentProcessRepository(this);
     Deployments               = new DeploymentRepository(this);
     Environments              = new EnvironmentRepository(this);
     Events                    = new EventRepository(this);
     FeaturesConfiguration     = new FeaturesConfigurationRepository(this);
     Feeds                     = new FeedRepository(this);
     Interruptions             = new InterruptionRepository(this);
     LibraryVariableSets       = new LibraryVariableSetRepository(this);
     Lifecycles                = new LifecyclesRepository(this);
     Licenses                  = new LicensesRepository(this);
     MachinePolicies           = new MachinePolicyRepository(this);
     MachineRoles              = new MachineRoleRepository(this);
     Machines                  = new MachineRepository(this);
     Migrations                = new MigrationRepository(this);
     OctopusServerNodes        = new OctopusServerNodeRepository(this);
     PerformanceConfiguration  = new PerformanceConfigurationRepository(this);
     PackageMetadataRepository = new PackageMetadataRepository(this);
     ProjectGroups             = new ProjectGroupRepository(this);
     Projects                  = new ProjectRepository(this);
     ProjectTriggers           = new ProjectTriggerRepository(this);
     Proxies                   = new ProxyRepository(this);
     Releases                  = new ReleaseRepository(this);
     RetentionPolicies         = new RetentionPolicyRepository(this);
     Schedulers                = new SchedulerRepository(this);
     ServerStatus              = new ServerStatusRepository(this);
     Spaces                    = new SpaceRepository(this);
     Subscriptions             = new SubscriptionRepository(this);
     TagSets                   = new TagSetRepository(this);
     Tasks                     = new TaskRepository(this);
     Teams                     = new TeamsRepository(this);
     Tenants                   = new TenantRepository(this);
     TenantVariables           = new TenantVariablesRepository(this);
     UserRoles                 = new UserRolesRepository(this);
     Users                     = new UserRepository(this);
     VariableSets              = new VariableSetRepository(this);
     Workers                   = new WorkerRepository(this);
     WorkerPools               = new WorkerPoolRepository(this);
     ScopedUserRoles           = new ScopedUserRoleRepository(this);
     UserPermissions           = new UserPermissionsRepository(this);
     UserTeams                 = new UserTeamsRepository(this);
     UserInvites               = new UserInvitesRepository(this);
     loadRootResource          = new Lazy <RootResource>(LoadRootDocumentInner, true);
     loadSpaceRootResource     = new Lazy <SpaceRootResource>(LoadSpaceRootDocumentInner, true);
 }
Example #34
0
        public void TestMethod1()
        {
            EventRepository eventRepository = new EventRepository();

            eventRepository.Delete(-1);
        }
Example #35
0
 public EventsController(EventRepository repository, AttendanceRepository attendanceRepository)
 {
     _repository           = repository;
     _attendanceRepository = attendanceRepository;
 }
        public void SaveThrowsDataAccessLayerException()
        {
            IEventRepository iEventRepository = new EventRepository(this.connectionString);

            iEventRepository.Save(0, 0, new EventItem("07545197580", AppActs.DomainModel.Enum.EventType.Event, "searched", 30, "Main", Guid.NewGuid(), DateTime.Now, "1.1.1.1"));
        }
Example #37
0
 public DashboardRepository(EventRepository eventRepository, EventParticipatedUsersRepository eventParticipatedUsersRepository)
 {
     _eventRepository = eventRepository;
     _eventParticipatedUserRepository = eventParticipatedUsersRepository;
 }
        public ShowcaseRepositoryTest()
        {
            var config = new ContentfulConfig("test")
                         .Add("DELIVERY_URL", "https://fake.url")
                         .Add("TEST_SPACE", "SPACE")
                         .Add("TEST_ACCESS_KEY", "KEY")
                         .Add("TEST_MANAGEMENT_KEY", "KEY")
                         .Build();

            _httpClient           = new Mock <IHttpClient>();
            _topicFactory         = new Mock <IContentfulFactory <ContentfulReference, SubItem> >();
            _crumbFactory         = new Mock <IContentfulFactory <ContentfulReference, Crumb> >();
            _timeprovider         = new Mock <ITimeProvider>();
            _eventHomepageFactory = new Mock <IContentfulFactory <ContentfulEventHomepage, EventHomepage> >();
            _alertFactory         = new Mock <IContentfulFactory <ContentfulAlert, Alert> >();
            _mockLogger           = new Mock <ILogger <ShowcaseRepository> >();
            _timeprovider.Setup(o => o.Now()).Returns(new DateTime(2017, 03, 30));

            var socialMediaFactory = new Mock <IContentfulFactory <ContentfulSocialMediaLink, SocialMediaLink> >();

            socialMediaFactory.Setup(o => o.ToModel(It.IsAny <ContentfulSocialMediaLink>())).Returns(new SocialMediaLink("sm-link-title", "sm-link-slug", "sm-link-icon", "https://link.url", "sm-link-accountName", "sm-link-screenReader"));

            _alertFactory.Setup(o => o.ToModel(It.IsAny <ContentfulAlert>())).Returns(new Alert("title", "", "", "", DateTime.MinValue, DateTime.MaxValue, string.Empty, false));

            var _videoFactory = new Mock <IContentfulFactory <ContentfulVideo, Video> >();

            var _profileFactory = new Mock <IContentfulFactory <ContentfulProfile, Profile> >();

            var _triviaFactory = new Mock <IContentfulFactory <ContentfulTrivia, Trivia> >();

            var callToActionBanner = new Mock <IContentfulFactory <ContentfulCallToActionBanner, CallToActionBanner> >();

            callToActionBanner.Setup(_ => _.ToModel(It.IsAny <ContentfulCallToActionBanner>())).Returns(
                new CallToActionBanner
            {
                Title      = "title",
                AltText    = "altText",
                ButtonText = "button text",
                Image      = "url",
                Link       = "url"
            });

            var spotlightBannerFactory = new Mock <IContentfulFactory <ContentfulSpotlightBanner, SpotlightBanner> >();

            var contentfulFactory = new ShowcaseContentfulFactory(_topicFactory.Object, _crumbFactory.Object, _timeprovider.Object, socialMediaFactory.Object, _alertFactory.Object, _profileFactory.Object, _triviaFactory.Object, callToActionBanner.Object, _videoFactory.Object, spotlightBannerFactory.Object);

            var newsListFactory = new Mock <IContentfulFactory <ContentfulNews, News> >();

            var contentfulClientManager = new Mock <IContentfulClientManager>();

            _contentfulClient = new Mock <IContentfulClient>();
            contentfulClientManager.Setup(o => o.GetClient(config)).Returns(_contentfulClient.Object);

            _eventFactory = new Mock <IContentfulFactory <ContentfulEvent, Event> >();
            _cacheWrapper = new Mock <ICache>();

            var _logger = new Mock <ILogger <EventRepository> >();

            _configuration = new Mock <IConfiguration>();
            _configuration.Setup(_ => _["redisExpiryTimes:Events"]).Returns("60");

            var eventRepository = new EventRepository(config, contentfulClientManager.Object, _timeprovider.Object, _eventFactory.Object, _eventHomepageFactory.Object, _cacheWrapper.Object, _logger.Object, _configuration.Object);

            _repository = new ShowcaseRepository(config, contentfulFactory, contentfulClientManager.Object, newsListFactory.Object, eventRepository, _mockLogger.Object);
        }
Example #39
0
 public HeaderViewComponent(EmailSenderService emailSenderService, GalleryRepository galleryRepo, AppointmentRepository appoitmentRepo, NoticeRepository noticeRepo, SetupRepository setupRepo, PageCategoryRepository pageCategoryRepo, EventRepository eventRepo, ServicesRepository serviceRepository)
 {
     _galleryRepo        = galleryRepo;
     _noticeRepo         = noticeRepo;
     _setupRepo          = setupRepo;
     _pageCategoryRepo   = pageCategoryRepo;
     _eventRepo          = eventRepo;
     _appointmentRepo    = appoitmentRepo;
     _serviceRepository  = serviceRepository;
     _emailSenderService = emailSenderService;
 }
Example #40
0
 public XtracurEventsController()
 {
     this.xtracurDivisionRepository = new XtracurDivisionRepository();
     this.eventRepository           = new EventRepository();
 }
Example #41
0
 public AddNewEventViewModel()
 {
     eventRepository = new EventRepository();
 }
 public EventSourceManager(EventRepository eventRepository, MatchSynchronizer matchSynchronizer)
 {
     _eventRepository   = eventRepository;
     _matchSynchronizer = matchSynchronizer;
 }
Example #43
0
        public IEnumerable <EventViewModel> GetAll()
        {
            EventRepository eventRepo = new EventRepository(_context);

            return(eventRepo.GetAllEvents());
        }
        private async Task UpdateSingleHostStateEntry(HostsRepository hostsrepo, HostStatesRepository staterepo, EventRepository eventrepo, Data.Host host)
        {
            _logger.LogTrace($"Checking host {host.Name} ({host.Hostname})");

            var state = staterepo.GetForHost(host.Id)
                        .Last();

            var ping = new Ping();

            try
            {
                var reply = await ping.SendPingAsync(host.Hostname, 2000);

                switch (reply.Status)
                {
                case IPStatus.Success:
                    state.Delay = (int)reply.RoundtripTime;
                    switch (reply.RoundtripTime)
                    {
                    case long n when n < 70:
                        state.Status = HostState.StatusEnum.Online;
                        break;

                    case long n when n < 300:
                        state.Status = HostState.StatusEnum.Warning;
                        break;

                    case long n when n < 2000:
                        state.Status = HostState.StatusEnum.Critical;
                        break;

                    default:
                        state.Status = HostState.StatusEnum.Error;
                        break;
                    }

                    await eventrepo.Enqueue(new HostOnlineEvent { HostId = host.Id });

                    break;

                case IPStatus.TimedOut:
                    state.Status = HostState.StatusEnum.Offline;
                    await eventrepo.Enqueue(new HostOfflineEvent { HostId = host.Id });

                    break;

                default:
                    _logger.LogError($"Unknown IPStatus {reply.Status} while checking {host.Hostname}");
                    state.Status = HostState.StatusEnum.Error;
                    break;
                }
            }
            catch (Exception)
            {
                _logger.LogWarning($"Error while checking {host.Name} ({host.Hostname})");
                state.Status = HostState.StatusEnum.Error;
            }
            finally
            {
                _logger.LogTrace($"Check complete for host {host.Name} ({host.Hostname})");
            }
        }
 public EventsManagementService(EventRepository eventRepository)
 {
     _eventRepository = eventRepository;
 }
Example #46
0
 public void Setup()
 {
     _fileWrapper     = new Mock <IFileWrapper>();
     _eventRepository = new EventRepository(_fileWrapper.Object);
 }
Example #47
0
 public EventController()
 {
     _eventRepository = new EventRepository();
     _validator       = new CreateEventRequestValidator();
 }
 public EventController()
 {
     this.repo = EventRepository.GetInstance();
 }
        private void InsertEventDetails(DataTable eventTable)
        {
            try
            {
                RoleRepository roleRepository = new RoleRepository();
                Role           role           = roleRepository.FindRoleId(ConstantValues.POC);

                foreach (DataRow row in eventTable.Rows)
                {
                    string          eventID         = row["Event ID"].ToString();
                    EventRepository eventRepository = new EventRepository();
                    Event           Event           = eventRepository.FindEvent(eventID);
                    if (Event == null)
                    {
                        Event         = new Event();
                        Event.EventId = eventID;
                        if (!row.IsNull("Month"))
                        {
                            Event.Month = row["Month"].ToString();
                        }
                        if (!row.IsNull("Base Location"))
                        {
                            Event.Location = row["Base Location"].ToString();
                        }
                        if (!row.IsNull("Beneficiary Name"))
                        {
                            Event.BeneficaryName = row["Beneficiary Name"].ToString();
                        }
                        if (!row.IsNull("Venue Address"))
                        {
                            Event.Address = row["Venue Address"].ToString();
                        }
                        if (!row.IsNull("Council Name"))
                        {
                            Event.CouncilName = row["Council Name"].ToString();
                        }
                        if (!row.IsNull("Project"))
                        {
                            Event.Project = row["Project"].ToString();
                        }
                        if (!row.IsNull("Category"))
                        {
                            Event.Category = row["Category"].ToString();
                        }
                        if (!row.IsNull("Event Name"))
                        {
                            Event.EventName = row["Event Name"].ToString();
                        }
                        if (!row.IsNull("Event Description"))
                        {
                            Event.EventDescription = row["Event Description"].ToString();
                        }
                        if (!row.IsNull("Event Date (DD-MM-YY)"))
                        {
                            String[] date      = row["Event Date (DD-MM-YY)"].ToString().Split(new[] { '-' });
                            int      day       = Convert.ToInt32(date[0]);
                            int      month     = Convert.ToInt32(date[1]);
                            int      a         = 20;
                            int      year      = int.Parse(a.ToString() + date[2].ToString());
                            DateTime eventDate = new DateTime(year, month, day);
                            Event.EventDate = eventDate;
                        }
                        if (!row.IsNull("Total no. of volunteers"))
                        {
                            Event.VolunteerCount = Convert.ToInt32(row["Total no. of volunteers"]);
                        }
                        if (!row.IsNull("Total Volunteer Hours"))
                        {
                            Event.VolunteerHours = Convert.ToInt32(row["Total Volunteer Hours"]);
                        }
                        if (!row.IsNull("Total Travel Hours"))
                        {
                            Event.TravelHours = Convert.ToInt32(row["Total Travel Hours"]);
                        }
                        if (!row.IsNull("Overall Volunteering Hours"))
                        {
                            Event.TotalVolunteeringHours = Convert.ToInt32(row["Overall Volunteering Hours"]);
                        }
                        if (!row.IsNull("Lives Impacted"))
                        {
                            Event.LivesImpacted = Convert.ToInt32(row["Lives Impacted"]);
                        }
                        if (!row.IsNull("Activity Type"))
                        {
                            Event.ActivityType = Convert.ToInt32(row["Activity Type"]);
                        }
                        if (!row.IsNull("Status"))
                        {
                            Event.Status = row["Status"].ToString();
                        }
                        eventRepository.AddEvent(Event);

                        // Add POC User

                        String[] pocID = null; String[] pocName = null;

                        if (role != null)
                        {
                            if (!row.IsNull("POC ID"))
                            {
                                pocID = row["POC ID"].ToString().Split(new[] { ';' });
                            }
                            if (!row.IsNull("POC Name"))
                            {
                                pocName = row["POC Name"].ToString().Split(new[] { ';' });
                            }
                            for (int i = 0; i < pocID.Length; i++)
                            {
                                User user = new User
                                {
                                    AssociateID   = pocID[i],
                                    AssociateName = pocName[i],
                                    RoleID        = role.RoleID,
                                    EventId       = eventID
                                };
                                UserRepository userRepository = new UserRepository();
                                userRepository.AddUser(user);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogger logger = new ExceptionLogger()
                {
                    ControllerName      = "ExcelToDB",
                    ActionrName         = "InsertEventDetails",
                    ExceptionMessage    = ex.Message,
                    ExceptionStackTrace = ex.StackTrace,
                    LogDateTime         = DateTime.Now
                };
                ExceptionRepository exceptionRepository = new ExceptionRepository();
                exceptionRepository.AddException(logger);
                throw ex;
            }
        }
Example #50
0
 public EventService(EventRepository eventRepository, ImageRepository imageRepository)
 {
     this._eventRepository = eventRepository;
     this._imageRepository = imageRepository;
 }
Example #51
0
 public EventViewModel()
 {
     _eventRepository = new EventRepository(https://localhost:5001/);
 }
 public DayBookingsController(EventRepository eventRepository, DayBookingRepository dayBookingRepository)
 {
     _eventRepository      = eventRepository;
     _dayBookingRepository = dayBookingRepository;
 }
 public EventsController()
 {
     _eventRepository = new EventRepository();
 }
Example #54
0
        //
        // GET: /Event/

        public EventController()
        {
            Repository = unitOfWork.EventRepository;
        }
 /// <summary>Creates an instance for the given language.</summary>
 /// <param name="culture">The culture.</param>
 /// <returns>A repository.</returns>
 public IEventRepository ForCulture(CultureInfo culture)
 {
     IEventRepository repository = new EventRepository(this.serviceClient);
     repository.Culture = culture;
     return repository;
 }
Example #56
0
 public EventServiceImpl(EventRepository eventRepository, EventMaker eventMaker, IHostingEnvironment hostingEnvironment)
 {
     _eventRepository    = eventRepository;
     _eventMaker         = eventMaker;
     _hostingEnvironment = hostingEnvironment;
 }
 public void Setup()
 {
     target = new EventRepository(config.WriteModel.GetInstanceProvider(), config.WriteModel.GetPersistenceEngine(), config.WriteModel.GetRawStreamEntryFactory());
 }
Example #58
0
 public EventGroupService(EventGroupRepository egr, EventRepository er, GroupRepository gr)
 {
     _egRepo    = egr;
     _eventRepo = er;
     _groupRepo = gr;
 }
Example #59
0
 public LiveController()
 {
     _showRepository = new ShowRepository();
     _eventRepository = new EventRepository();
 }
Example #60
0
        private static async Task Main(string[] args)
        {
            var disposables = new List <IDisposable>();

            Console.WriteLine("Program started...");

            var binder     = new VersionedBinder();
            var serializer = new JsonNetSerializer(binder);

            var bus  = new ObservableMessageBus();
            var repo = new EventRepository(new DefaultInstanceProvider(), new WriteModel.InMemory.PersistenceEngine(serializer), new WriteModel.InMemory.RawStreamEntryFactory());

            // let bus subscribe to repository and publish its committed events
            repo.SubscribeTo <IMessage <IEvent> >()
            .Subscribe((e) => bus.Publish(e));

            // normal event processing
            bus.SubscribeTo <IMessage <IEvent> >().Subscribe((e) =>
            {
                Console.WriteLine("Look, an event: " + e.ToString());
            });

            bus.SubscribeTo <SomethingDone>()
            .Subscribe((e) =>
            {
                Console.WriteLine("Something done: " + e.Bla);
            });
            bus.SubscribeTo <Renamed>()
            .Subscribe((e) =>
            {
                Console.WriteLine("Renamed: " + e.Name);
            });

            // complex event processing
            bus.SubscribeTo <IEvent>()
            .Buffer(2, 1)
            .Where(x =>
                   x.First() is SomethingDone &&
                   x.Last() is INameChangeEvent)
            .Subscribe((e) =>
            {
                Console.WriteLine("IMessage<IEvent>: Look, a new name after something done: " + (e.First() as SomethingDone).Bla + " -> " + (e.Last() as INameChangeEvent).Name);
            });

            bus.SubscribeTo <IEvent>()
            .Buffer(2, 1)
            .Where(x =>
                   x.First() is SomethingDone &&
                   x.Last() is INameChangeEvent)
            .Subscribe((e) =>
            {
                Console.WriteLine("IEvent: Look, a new name after something done: " + (e.First() as SomethingDone).Bla + " -> " + (e.Last() as INameChangeEvent).Name);
            });

            bus
            .SubscribeToAndUpdate <IMessage <TestAggregateRename>, TestAggregate>((aggr, cmd) =>
            {
                aggr.Rename(cmd.Body.Name);
            }, repo);

            bus.SubscribeTo <IMessage <TestAggregateDoSomething> >()
            .Select(command => Observable.FromAsync(async() =>
            {
                var aggregate = await repo.GetAsync <TestAggregate>(command.Body.Id);
                aggregate.DoSomething(command.Body.Foo);
                await repo.SaveAsync(aggregate);
            }))
            .Concat()
            .Subscribe();

            Console.WriteLine("Start executing...");

            var agg = new TestAggregate("abc" + Guid.NewGuid(), "test");

            agg.DoSomething("bla bla bla");

            agg.Rename("foo thing bar");

            agg.DoSomething("ha ha");

            agg.DoSomethingSpecial("<write poem>");

            agg.Rename("hu?");

            agg.DoSomething("hello?");

            agg.Rename("Hi!");


            await repo.SaveAsync(agg);

            agg = await repo.GetAsync <TestAggregate>(agg.Id);

            var projection  = TestState.LoadState(agg.StateModel);
            var projection2 = agg.StateModel;

            Console.WriteLine("Name: " + projection.Name + ", " + projection.SomethingDone);
            Console.WriteLine("Name: " + projection2.Name + ", " + projection2.SomethingDone);

            Console.WriteLine("Try to mess with state:");

            bus.Send(new TypedMessage <TestAggregateDoSomething>(Guid.NewGuid().ToString(), new TestAggregateDoSomething {
                Id = agg.Id, Foo = "Command DoSomething Bla"
            }, null, null, null, DateTime.UtcNow, 0));
            bus.Send(new TypedMessage <TestAggregateRename>(Guid.NewGuid().ToString(), new TestAggregateRename {
                Id = agg.Id, Name = "Command Renamed Name"
            }, null, null, null, DateTime.UtcNow, 0));

            agg = await repo.GetAsync <TestAggregate>(agg.Id);

            projection2 = agg.StateModel;

            Console.WriteLine("Name: " + projection2.Name);

            // Console.WriteLine("Change-count: " + AlternateState.LoadState((AlernateState)null, agg.ev).ChangeCount);


            //SQLite3.Config(ConfigOption.Serialized);

            Console.WriteLine("-------");
            Console.WriteLine("Database Persistence");
            Console.WriteLine("-------");

            SQLiteConnectionWithLock connectionFactory()
            {
                if (writeConn != null)
                {
                    return(writeConn);
                }

                //SQLite3.Config(ConfigOption.Serialized);

                var databaseFile = "writeDatabase.db";

                var connectionString = new SQLiteConnectionString(databaseFile, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.FullMutex, true, null);

                writeConn = new SQLiteConnectionWithLock(connectionString);

                using (writeConn.Lock())
                {
                    writeConn.CreateCommand(@"PRAGMA synchronous = NORMAL;
PRAGMA journal_mode = WAL;", Array.Empty <object>()).ExecuteScalar <int>();
                }

                return(writeConn);
            }

            SQLiteConnectionWithLock readConnectionFactory()
            {
                if (readConn != null)
                {
                    return(readConn);
                }
                //SQLite3.Config(ConfigOption.Serialized);

                var databaseFile = "readDatabase.db";

                var connectionString = new SQLiteConnectionString(databaseFile, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.FullMutex, true, null);

                readConn = new SQLiteConnectionWithLock(connectionString);

                using (readConn.Lock())
                {
                    readConn.CreateCommand(@"PRAGMA synchronous = NORMAL;
PRAGMA temp_store = MEMORY;
PRAGMA page_size = 4096;
PRAGMA cache_size = 10000;
PRAGMA journal_mode = WAL;", Array.Empty <object>()).ExecuteScalar <int>();
                }

                return(readConn);
            }

            var engine = new PersistenceEngine(connectionFactory, serializer);

            engine.InitializeAsync().Wait();

            var observerFactory = new PollingObserverFactory(engine, TimeSpan.FromMilliseconds(500));
            var observer        = await observerFactory.CreateObserverAsync(0);

            var subscription = observer.Subscribe((s) =>
            {
                //Console.WriteLine("Polling: " + s.StreamName + "@" + s.StreamRevision + " - " + s.CheckpointNumber);
            });

            disposables.Add(subscription);
            disposables.Add(observer);

            await observer.StartAsync();

            var repository = new EventRepository(
                new DefaultInstanceProvider(),
                engine,
                new RawStreamEntryFactory());

            string entityId = null;

            Console.WriteLine("Generate 1000 entities");

            var list = new List <IEventSourcedEntity>();

            for (var i = 0; i < 1000; i++)
            {
                Console.Write(".");

                entityId = Guid.NewGuid().ToString();
                var entity = new TestAggregate(entityId, "test " + DateTime.Now.ToShortTimeString());

                entity.Rename("asdfasdf");
                entity.DoSomething("bla" + DateTime.Now.ToShortTimeString());

                list.Add(entity);
            }

            await repository.SaveAsync(list);

            list.Clear();


            var loadedEntity = await repository.GetAsync <TestAggregate>(entityId);

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var count = await engine.LoadStreamEntriesAsync().CountAsync();

            stopwatch.Stop();
            Console.WriteLine($"Load {count} entries: {stopwatch.ElapsedMilliseconds}ms");
            Console.ReadKey();

            Console.WriteLine("Commits: " + await engine.LoadStreamEntriesAsync()
                              //.Result
                              .CountAsync());
            Console.WriteLine("Rename count: " + await engine.LoadStreamEntriesAsync(payloadTypes: new[] { typeof(Renamed) })
                              //.Result
                              .CountAsync());

            Console.WriteLine("Rename checkpointnumbers of renames descending: " + string.Join(", ", await engine
                                                                                               .LoadStreamEntriesAsync(ascending: false, payloadTypes: new[] { typeof(Renamed), typeof(SomethingDone) })
                                                                                               //.Result
                                                                                               .Select(x => "" + x.CheckpointNumber).ToArrayAsync()));
            Console.WriteLine("Rename count: " + await engine.LoadStreamEntriesAsync(minCheckpointNumber: await engine.GetCurrentEventStoreCheckpointNumberAsync()
                                                                                     //.Result
                                                                                     - 5, payloadTypes: new[] { typeof(Renamed) })
                              //.Result
                              .CountAsync());
            Console.WriteLine("Current CheckpointNumber: " + await engine.GetCurrentEventStoreCheckpointNumberAsync()
                              //.Result
                              );

            var c = readConnectionFactory();

            //c.RunInTransactionAsync((SQLiteConnection connection) =>
            //{
            c.RunInLock((SQLiteConnection connection) =>
            {
                connection.CreateTable <CheckpointInfo>(CreateFlags.AllImplicit);
            });

            var viewModelResetter   = new StorageResetter(readConnectionFactory());
            var checkpointPersister = new CheckpointPersister <CheckpointInfo>(readConnectionFactory());

            //Console.ReadKey();

            var readRepository = new ReadRepository(readConnectionFactory);

            //return;

            /*
             * var live = new CatchUpProjector<TestState>(
             *  new TestState(),
             *  new NullCheckpointPersister(),
             *  engine,
             *  viewModelResetter);
             *
             * Stopwatch stopwatch = new Stopwatch();
             * stopwatch.Start();
             * live.Start();
             * stopwatch.Stop();
             * Console.WriteLine("live: " + stopwatch.ElapsedMilliseconds + "ms");
             *
             * var live2 = new CatchUpProjector<VowelCountState>(
             *  new VowelCountState(),
             *  new NullCheckpointPersister(),
             *  engine,
             *  viewModelResetter);
             * live2.Start();
             *
             * var resetter = new StorageResetter(readConnectionFactory());
             * //resetter.Reset(new[] { typeof(PersistentEntity) });
             */

            var persistentState = new CatchUpProjector <PersistentState>(
                new PersistentState(readRepository),
                checkpointPersister,
                engine,
                viewModelResetter,
                observerFactory);

            stopwatch.Start();

            await persistentState.StartAsync();

            _ = Task.Run(async() =>
            {
                while (true)
                {
                    Console.WriteLine(persistentState.StateModel.Count);
                    await Task.Delay(1000).ConfigureAwait(false);
                }
            });

            Console.ReadKey();
            stopwatch.Stop();
            Console.WriteLine($"persistent: {persistentState.StateModel.Count} msgs, {stopwatch.ElapsedMilliseconds}ms -> {persistentState.StateModel.Count / (stopwatch.ElapsedMilliseconds / 1000.0)}");

            /*
             * Console.ReadKey();
             * Console.WriteLine(live.StateModel.Name);
             * Console.WriteLine(live.StateModel.SomethingDone);
             * Console.WriteLine(live.StateModel.StreamName);
             *
             *
             * Console.WriteLine("a: " + live2.StateModel.ACount);
             * Console.WriteLine("e: " + live2.StateModel.ECount);
             * Console.WriteLine("i: " + live2.StateModel.ICount);
             * Console.WriteLine("o: " + live2.StateModel.OCount);
             * Console.WriteLine("u: " + live2.StateModel.UCount);
             */
            Console.ReadKey();

            foreach (var disp in disposables)
            {
                disp.Dispose();
            }
            observer.Dispose();
        }