protected override void RunCallback() { var dbFactory = new DbFactory(); var time = new TimeService(dbFactory); var log = GetLogger(); var settings = new SettingsService(dbFactory); var styleHistoryService = new StyleHistoryService(log, time, dbFactory); var styleManager = new StyleManager(log, time, styleHistoryService); var lastSyncDate = settings.GetListingsPriceSyncDate(_api.Market, _api.MarketplaceId); LogWrite("Last sync date=" + lastSyncDate); if (!lastSyncDate.HasValue || (time.GetUtcTime() - lastSyncDate) > _betweenProcessingInverval) { var sync = new eBayItemsSync(log, time, _api, dbFactory, styleManager, null, null, null); sync.SendPriceUpdates(); settings.SetListingsPriceSyncDate(time.GetUtcTime(), _api.Market, _api.MarketplaceId); } }
protected override void RunCallback() { var dbFactory = new DbFactory(); var time = new TimeService(dbFactory); var log = GetLogger(); var settings = new SettingsService(dbFactory); var lastSyncDate = settings.GetListingsSendDate(_api.Market, _api.MarketplaceId); LogWrite("Last sync date=" + lastSyncDate); if (!lastSyncDate.HasValue || (time.GetUtcTime() - lastSyncDate) > _betweenProcessingInverval) { var sync = new JetItemsSync(log, time, _api, dbFactory, AppSettings.JetImageDirectory, AppSettings.JetImageBaseUrl); sync.SendItemUpdates(); settings.SetListingsSendDate(time.GetUtcTime(), _api.Market, _api.MarketplaceId); } }
private static void SetupTimeService() { Thread.Sleep(10000); TimeServiceSettings settings = new TimeServiceSettings(); TimeService.SystemTimeChanged += TimeService_SystemTimeChanged; TimeService.TimeSyncFailed += TimeService_TimeSyncFailed; TimeService.SetTimeZoneOffset(120); IPAddress address = GetNtpAddress("0.it.pool.ntp.org"); if (address != null) { settings.PrimaryServer = address.GetAddressBytes(); } address = GetNtpAddress("1.it.pool.ntp.org"); if (address != null) { settings.AlternateServer = address.GetAddressBytes(); } TimeService.Settings = settings; UpdateNow(); }
private bool CanRefundPerk() { var player = GetPC(); var dbPlayer = DataService.Player.GetByID(player.GlobalID); if (dbPlayer.DatePerkRefundAvailable == null) { return(true); } DateTime refundDate = (DateTime)dbPlayer.DatePerkRefundAvailable; bool canRefund = refundDate <= DateTime.UtcNow; if (canRefund) { return(true); } TimeSpan delta = refundDate - DateTime.UtcNow; string time = TimeService.GetTimeLongIntervals(delta.Days, delta.Hours, delta.Minutes, delta.Seconds, false); GetPC().FloatingText("You can refund another perk in " + time); return(false); }
private void LoadMainPage() { ClearPageResponses("MainPage"); var player = GetPC(); var dbPlayer = DataService.Player.GetByID(player.GlobalID); var header = "You may use this tome to refund one of your perks. Refunding may only occur once every 24 hours (real world time). Selecting a perk from this list will refund all levels you have purchased of that perk. The refunded SP may be used to purchase other perks immediately afterwards.\n\n"; if (dbPlayer.DatePerkRefundAvailable != null && dbPlayer.DatePerkRefundAvailable > DateTime.UtcNow) { TimeSpan delta = (DateTime)dbPlayer.DatePerkRefundAvailable - DateTime.UtcNow; var time = TimeService.GetTimeLongIntervals(delta.Days, delta.Hours, delta.Minutes, delta.Seconds, false); header += "You can refund another perk in " + time; } else { var pcPerks = DataService.PCPerk.GetAllByPlayerID(player.GlobalID) .OrderBy(o => { var perk = DataService.Perk.GetByID(o.PerkID); return(perk.Name); }).ToList(); foreach (var pcPerk in pcPerks) { var perk = DataService.Perk.GetByID(pcPerk.PerkID); AddResponseToPage("MainPage", perk.Name + " (Lvl. " + pcPerk.PerkLevel + ")", true, pcPerk.ID); } } SetPageHeader("MainPage", header); }
protected void BindTimeZone(string MyCountry) { //Create blank list List <RentALanguageTeacher.App_Code.Time.TimeZoneDDL> list = new List <RentALanguageTeacher.App_Code.Time.TimeZoneDDL>(); //Populate List from country list = TimeService.FillTimeZoneDDL(MyCountry); //Create Default RentALanguageTeacher.App_Code.Time.TimeZoneDDL DefaultCountry = new RentALanguageTeacher.App_Code.Time.TimeZoneDDL(); DefaultCountry.ZoneId = 0; DefaultCountry.ZoneName = "Select your TimeZone"; list.Add(DefaultCountry); //Bind DDL TimeZone.DataSource = list; TimeZone.DataValueField = "ZoneId"; TimeZone.DataTextField = "ZoneName"; TimeZone.DataBind(); //Select Default Value TimeZone.SelectedValue = "0"; //Enable TimeZone.Enabled = true; }
private static void Run() { if (IsDisabled) { return; } using (new Profiler(nameof(ServerRestartProcessor) + "." + nameof(Run))) { var now = DateTime.UtcNow; if (now >= RestartTime) { _.ExportAllCharacters(); foreach (var player in NWModule.Get().Players) { _.BootPC(player, "Server is automatically rebooting. This is a temporary solution until we can fix performance problems. Thank you for your patience and understanding."); } NWNXAdmin.ShutdownServer(); } else if (now >= _nextNotification) { var delta = RestartTime - now; string rebootString = TimeService.GetTimeLongIntervals(delta.Days, delta.Hours, delta.Minutes, delta.Seconds, false); string message = "Server will automatically reboot in " + rebootString; foreach (var player in NWModule.Get().Players) { // Send a message about the next reboot. player.FloatingText(message); // If the player has a lease which is expiring in <= 24 hours, notify them. int leasesExpiring = DataService.Where <PCBase>(x => x.DateRentDue.AddHours(-24) <= now && x.PlayerID == player.GlobalID).Count; if (leasesExpiring > 0) { string leaseDetails = leasesExpiring == 1 ? "1 lease" : leasesExpiring + " leases"; player.FloatingText("You have " + leaseDetails + " expiring in less than 24 hours (real world time). Please extend the lease or your land will be forfeited."); } } Console.WriteLine(message); // We're in the last hour before rebooting. Schedule the next notification 45 minutes from now. if (delta.TotalHours <= 1 && delta.TotalMinutes >= 45) { _nextNotification = DateTime.UtcNow.AddMinutes(45); } // Notify every minute when it comes close to the reboot time. else if (delta.TotalMinutes <= 15) { _nextNotification = DateTime.UtcNow.AddMinutes(1); } // Otherwise notify on the standard timing. else { _nextNotification = DateTime.UtcNow.AddMinutes(NotificationIntervalMinutes); } } } }
protected void BindCountry() { //Create blank list List <RentALanguageTeacher.App_Code.Time.CountryDDL> list = new List <RentALanguageTeacher.App_Code.Time.CountryDDL>(); //Fill list list = TimeService.FillCountryDDL(); //Create Default Value RentALanguageTeacher.App_Code.Time.CountryDDL DefaultCountry = new RentALanguageTeacher.App_Code.Time.CountryDDL(); DefaultCountry.CountryCode = "Default"; DefaultCountry.CountryName = "Select your Country"; list.Add(DefaultCountry); //Bind DDL Country.DataSource = list; Country.DataValueField = "CountryCode"; Country.DataTextField = "CountryName"; Country.DataBind(); Country.SelectedValue = "Default"; //Disable TimeZone TimeZone.Enabled = false; }
protected override void RunCallback() { _api.Connect(); var dbFactory = new DbFactory(); var time = new TimeService(dbFactory); var settings = new SettingsService(dbFactory); var lastSyncDate = settings.GetListingsSendDate(_api.Market, _api.MarketplaceId); LogWrite("Last sync date=" + lastSyncDate); if (!lastSyncDate.HasValue || (time.GetUtcTime() - lastSyncDate) > _betweenProcessingInverval) { var sync = new MagentoItemsSync(_api, dbFactory, GetLogger(), time); sync.SyncAttributeOptions(); //sync.SyncCategories(); sync.SendItemUpdates(); settings.SetListingsSendDate(time.GetUtcTime(), _api.Market, _api.MarketplaceId); } }
public void Calling_TimeService_And_GettingUTCOffset_WithEdgeCases_Should_ReturnCorrectOffset() { // Arrange var placeId = "usa/anchorage"; var beforeDstStart = new DateTimeOffset (2015, 3, 8, 1, 0, 0, TimeSpan.FromHours (0)); var afterDstStart = new DateTimeOffset (2015, 3, 8, 3, 0, 0, TimeSpan.FromHours (0)); var beforeDstEnd = new DateTimeOffset (2015, 11, 1, 1, 0, 0, TimeSpan.FromHours (0)); var afterDstEnd = new DateTimeOffset (2015, 11, 1, 2, 0, 0, TimeSpan.FromHours (0)); // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); var result = timeservice.CurrentTimeForPlace (new LocationId (placeId)); var firstLocation = result.SingleOrDefault (); var beforeDstStartOffset = firstLocation.GetUTCOffsetFromLocalTime (beforeDstStart); var afterDstStartOffset = firstLocation.GetUTCOffsetFromLocalTime (afterDstStart); var beforeDstEndOffset = firstLocation.GetUTCOffsetFromLocalTime (beforeDstEnd); var afterDstEndOffset = firstLocation.GetUTCOffsetFromLocalTime (afterDstEnd); // Assert Assert.AreEqual (TimeSpan.FromHours (-9), beforeDstStartOffset); Assert.AreEqual (TimeSpan.FromHours (-8), afterDstStartOffset); Assert.AreEqual (TimeSpan.FromHours (-8), beforeDstEndOffset); Assert.AreEqual (TimeSpan.FromHours (-9), afterDstEndOffset); }
public void ReturnsTimeAsUtc() { TimeService.SetProvider(new ValidTimeProvider()); var time = TimeService.UtcNow; Assert.AreEqual(DateTimeKind.Utc, time.Kind); }
private void Init() { //服务模块初始化 ResSvc resSvc = GetComponent <ResSvc>(); resSvc.InitSvc(); AudioSvc audioSvc = GetComponent <AudioSvc>(); audioSvc.InitSvc(); TimeService timeSvc = GetComponent <TimeService>(); timeSvc.InitSvc(); MainCitySys mainCitySys = GetComponent <MainCitySys>(); mainCitySys.InitSys(); BattleSys battleSys = GetComponent <BattleSys>(); battleSys.InitSys(); dynamicWnd.SetWndState(); }
private void GetInternetTime() { try { var NTPTime = new TimeServiceSettings(); NTPTime.AutoDayLightSavings = true; NTPTime.ForceSyncAtWakeUp = true; NTPTime.RefreshTime = 3600; //Thread.Sleep(1500); NTPTime.PrimaryServer = Dns.GetHostEntry("2.ca.pool.ntp.org").AddressList[0].GetAddressBytes(); NTPTime.AlternateServer = Dns.GetHostEntry("time.nist.gov").AddressList[0].GetAddressBytes(); //Thread.Sleep(1500); TimeService.Settings = NTPTime; TimeService.SetTimeZoneOffset(LocalTimeZone); // MST Time zone : GMT-7 TimeService.SystemTimeChanged += OnSystemTimeChanged; TimeService.TimeSyncFailed += OnTimeSyncFailed; TimeService.Start(); //Thread.Sleep(500); TimeService.UpdateNow(0); //Thread.Sleep(9000); //Debug.Print("It is : " + DateTime.Now); var time = DateTime.Now; Utility.SetLocalTime(time); TimeService.Stop(); } catch (Exception ex) { Debug.Print(ex.Message); } }
public static void Main(string[] args) { var timeService = new TimeService(); var currentTime = timeService.GetCurrentTime(); Console.WriteLine(currentTime); }
public virtual async Task <ComposedValue> GetComposedValue( string parameter, Session session, CancellationToken cancellationToken) { var chatTail = await ChatService.GetChatTail(1, cancellationToken); var uptime = await TimeService.GetUptime(10, cancellationToken); var sum = (double?)null; if (double.TryParse(parameter, out var value)) { sum = await SumService.GetSum(new [] { value }, true, cancellationToken); } var lastChatMessage = chatTail.Messages.SingleOrDefault()?.Text ?? "(no messages)"; var user = await Auth.GetUser(session, cancellationToken); var activeUserCount = await ChatService.GetActiveUserCount(cancellationToken); return(new ComposedValue() { Parameter = $"{parameter} - local", Uptime = uptime, Sum = sum, LastChatMessage = lastChatMessage, User = user, ActiveUserCount = activeUserCount }); }
public static bool SetTime(bool connected) { #if MF_FRAMEWORK_VERSION_V4_3 if (!connected) { return(false); } try { //network settle time Util.Delay(networkSettleTime); var ntpAddress = GetTimeServiceAddress(ntpServer); if (ntpAddress == null) { return(false); } TimeService.UpdateNow(ntpAddress, 200); return(true); } catch { return(false); } #else return(true); #endif }
public async Task ShowsRunningAndScheduledTasksAsync() { var timeService = new TimeService(TimeSpan.FromSeconds(1)); var schedulingService = new SchedulingService(timeService); var scheduledTask1 = new ScheduledTask { Name = "task 1", Start = timeService.CurrentDateTime.AddHours(5) }; schedulingService.AddScheduledTask(scheduledTask1); var scheduledTask2 = new ScheduledTask { Name = "task 2", Start = timeService.CurrentDateTime, Action = async() => { await TaskShim.Delay(TimeSpan.FromMinutes(1)); } }; schedulingService.AddScheduledTask(scheduledTask2); await TaskShim.Delay(TimeSpan.FromSeconds(1)); var summary = schedulingService.GetSummary(); Assert.IsNotNull(summary); }
public HeiflowTimeControl(TimeService global, TimeService mf) { InitializeComponent(); _GlobalTimeService = global; _MFTimeService = mf; this.tabControl1.SelectedTab = this.tabPageMF; }
public void SetupBase() { _plantProviderMock = new Mock <IPlantProvider>(); _plantProviderMock.SetupGet(x => x.Plant).Returns(TestPlant); _plantProvider = _plantProviderMock.Object; var currentUserProviderMock = new Mock <ICurrentUserProvider>(); currentUserProviderMock.Setup(x => x.GetCurrentUserOid()).Returns(_currentUserOid); _currentUserProvider = currentUserProviderMock.Object; var eventDispatcher = new Mock <IEventDispatcher>(); _eventDispatcher = eventDispatcher.Object; _timeProvider = new ManualTimeProvider(new DateTime(2020, 2, 1, 0, 0, 0, DateTimeKind.Utc)); TimeService.SetProvider(_timeProvider); _dbContextOptions = new DbContextOptionsBuilder <PreservationContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; // ensure current user exists in db using (var context = new PreservationContext(_dbContextOptions, _plantProvider, _eventDispatcher, _currentUserProvider)) { if (context.Persons.SingleOrDefault(p => p.Oid == _currentUserOid) == null) { AddPerson(context, _currentUserOid, "Ole", "Lukkøye"); } } SetupNewDatabase(_dbContextOptions); }
public AppServices(ITogglApi api, ITogglDatabase database) { Scheduler = System.Reactive.Concurrency.Scheduler.Default; TimeService = new TimeService(Scheduler); var errorHandlingService = new ErrorHandlingService(NavigationServiceSubstitute, AccessRestrictionStorageSubsitute); syncErrorHandlingService = new SyncErrorHandlingService(errorHandlingService); var dataSource = new TogglDataSource( database, TimeService, AnalyticsServiceSubstitute); SyncManager = TogglSyncManager.CreateSyncManager( database, api, dataSource, TimeService, AnalyticsServiceSubstitute, LastTimeUsageStorageSubstitute, Scheduler, StopwatchProvider, AutomaticSyncingService); syncErrorHandlingService.HandleErrorsOf(SyncManager); }
protected override void RunCallback() { var dbFactory = new DbFactory(); CompanyDTO company = null; using (var db = dbFactory.GetRDb()) { company = db.Companies.GetByIdWithSettingsAsDto(CompanyId); } var time = new TimeService(dbFactory); var addressService = AddressService.Default; var emailSmtpSettings = SettingsBuilder.GetSmtpSettingsFromCompany(company, AppSettings.IsDebug, AppSettings.IsSampleLabels); var emailService = new EmailService(GetLogger(), emailSmtpSettings, addressService); var actionService = new SystemActionService(GetLogger(), time); emailService.ProcessEmailActions(dbFactory, time, company, actionService); emailService.AutoAnswerEmails(dbFactory, time, company); }
private void OnButtonUp(object sender, RoutedEventArgs evt) { ButtonEventArgs e = (ButtonEventArgs)evt; if (e.Button == Microsoft.SPOT.Hardware.Button.VK_UP) { // reset the time to an arbitrary value TimeService.SetUtcTime(128752416000000000); TimeService.SetTimeZoneOffset(-480); // time origin } else if (e.Button == Microsoft.SPOT.Hardware.Button.VK_SELECT) { // Perform a one time sync with the time server TimeServiceStatus status = TimeService.UpdateNow(TimeServerIPAddress, 10); TimeService.SetTimeZoneOffset(-480); // time origin } else if (e.Button == Microsoft.SPOT.Hardware.Button.VK_DOWN) { // start a scheduled periodic sync TimeServiceSettings settings = new TimeServiceSettings(); settings.PrimaryServer = TimeServerIPAddress; settings.RefreshTime = 10; // sync every 10 seconds TimeService.Settings = settings; TimeService.Start(); TimeService.SetTimeZoneOffset(-480); // time origin } }
protected override void RunCallback() { var dbFactory = new DbFactory(); var time = new TimeService(dbFactory); var log = GetLogger(); var settings = new SettingsService(dbFactory); var styleHistoryService = new StyleHistoryService(log, time, dbFactory); var styleManager = new StyleManager(log, time, styleHistoryService); var lastSyncDate = settings.GetListingsReadDate(_api.Market, _api.MarketplaceId); LogWrite("Last sync date=" + lastSyncDate); var sync = new eBayItemsSync(log, time, _api, dbFactory, styleManager, AppSettings.eBayImageDirectory, AppSettings.eBayImageBaseUrl, AppSettings.LabelDirectory); if (!lastSyncDate.HasValue || (time.GetUtcTime() - lastSyncDate) > _betweenProcessingInverval) { sync.ReadItemsInfo(); settings.SetListingsReadDate(time.GetUtcTime(), _api.Market, _api.MarketplaceId); } }
public async Task CompletesTasksAfterSpecificPeriodAsync() { var timeService = new TimeService(TimeSpan.FromSeconds(1)); var schedulingService = new SchedulingService(timeService); var scheduledTask1 = new ScheduledTask { Name = "task 1", Start = timeService.CurrentDateTime.AddHours(5) }; schedulingService.AddScheduledTask(scheduledTask1); bool isTaskCompleted = false; var scheduledTask2 = new ScheduledTask { Name = "task 2", Start = timeService.CurrentDateTime, Action = async() => { await TaskShim.Delay(TimeSpan.FromSeconds(2)); isTaskCompleted = true; } }; schedulingService.AddScheduledTask(scheduledTask2); var isCanceled = false; schedulingService.TaskCanceled += (sender, e) => { if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2)) { isCanceled = true; } }; var isCompleted = false; schedulingService.TaskCompleted += (sender, e) => { if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2)) { isCompleted = true; } }; await TaskShim.Delay(TimeSpan.FromSeconds(5)); schedulingService.Stop(); // Additional wait time to allow canceling etc await TaskShim.Delay(TimeSpan.FromSeconds(1)); Assert.IsTrue(isCompleted); Assert.IsTrue(isTaskCompleted); Assert.IsFalse(isCanceled); }
protected override void InitializeApp(IMvxPluginManager pluginManager, IMvxApplication app) { const string clientName = "Giskard"; var packageInfo = ApplicationContext.PackageManager.GetPackageInfo(ApplicationContext.PackageName, 0); var version = packageInfo.VersionName; var sharedPreferences = ApplicationContext.GetSharedPreferences(clientName, FileCreationMode.Private); var database = new Database(); var scheduler = Scheduler.Default; var timeService = new TimeService(scheduler); var suggestionProviderContainer = new SuggestionProviderContainer( new MostUsedTimeEntrySuggestionProvider(database, timeService, maxNumberOfSuggestions) ); var appVersion = Version.Parse(version); var userAgent = new UserAgent(clientName, version); var mailService = new MailService(ApplicationContext); var dialogService = new DialogService(); var platformConstants = new PlatformConstants(); var keyValueStorage = new SharedPreferencesStorage(sharedPreferences); var settingsStorage = new SettingsStorage(appVersion, keyValueStorage); var feedbackService = new FeedbackService(userAgent, mailService, dialogService, platformConstants); var foundation = TogglFoundation .ForClient(userAgent, appVersion) .WithDatabase(database) .WithScheduler(scheduler) .WithTimeService(timeService) .WithMailService(mailService) .WithApiEnvironment(environment) .WithGoogleService <GoogleService>() .WithRatingService <RatingService>() .WithLicenseProvider <LicenseProvider>() .WithAnalyticsService(analyticsService) .WithPlatformConstants(platformConstants) .WithRemoteConfigService <RemoteConfigService>() .WithApiFactory(new ApiFactory(environment, userAgent)) .WithBackgroundService(new BackgroundService(timeService)) .WithSuggestionProviderContainer(suggestionProviderContainer) .WithApplicationShortcutCreator(new ApplicationShortcutCreator(ApplicationContext)) .StartRegisteringPlatformServices() .WithDialogService(dialogService) .WithFeedbackService(feedbackService) .WithLastTimeUsageStorage(settingsStorage) .WithBrowserService <BrowserService>() .WithKeyValueStorage(keyValueStorage) .WithUserPreferences(settingsStorage) .WithOnboardingStorage(settingsStorage) .WithNavigationService(navigationService) .WithAccessRestrictionStorage(settingsStorage) .WithPasswordManagerService <OnePasswordService>() .WithErrorHandlingService(new ErrorHandlingService(navigationService, settingsStorage)) .Build(); foundation.RevokeNewUserIfNeeded().Initialize(); base.InitializeApp(pluginManager, app); }
public void Init() { TimeService = new TimeService(); Maze = new Mock <IMaze>(); Pacman = new Mock <IPacman>(); PursueAlgo = new Mock <IPursueAlgo>(); Count = 3; }
public MessageEntity(string text, string date, int timeZone, string picture, string name) { this.name = name; this.picture = picture; this.text = text; this.date = TimeService.GetDateTime(int.MaxValue - int.Parse(date) - timeZone * 3600).ToString("dd.MM.yyyy, HH:mm:ss"); unixTime = date; }
public ExtensionManPackage() { this.Name = PackageName; TimeService = new TimeService("Base Timeline"); IsMandatory = true; FullName = "Extension Manager"; InitValues(); }
public TimeServiceTests() { _messages = new Mock <IDiscordMessages>(); _dateTime = new Mock <IDateTime>(); _users = new Mock <IMiunieUserProvider>(); _timeManipulator = new Mock <ITimeManipulationProvider>(); _service = new TimeService(_messages.Object, _dateTime.Object, _users.Object, _timeManipulator.Object); }
public void Setup() { var timeService = new TimeService(); _trackService = new TrackService(timeService, SpecialLengthSettings.Object); _sessionSettings = Sessions.Object.SessionList.First(); }
public void TimeService_GetCurrentDateTime_ReturnsDateTimeNow() { var timeService = new TimeService(); var timeSpan = DateTime.Now - timeService.GetCurrentDateTime(); Console.WriteLine(timeSpan.TotalMilliseconds); Assert.AreEqual(DateTime.Now, timeService.GetCurrentDateTime()); }
public async Task CompletesTasksAfterSpecificPeriod() { var timeService = new TimeService(TimeSpan.FromSeconds(1)); var schedulingService = new SchedulingService(timeService); var scheduledTask1 = new ScheduledTask { Name = "task 1", Start = timeService.CurrentDateTime.AddHours(5) }; schedulingService.AddScheduledTask(scheduledTask1); bool isTaskCompleted = false; var scheduledTask2 = new ScheduledTask { Name = "task 2", Start = timeService.CurrentDateTime, Action = async () => { await TaskShim.Delay(TimeSpan.FromSeconds(2)); isTaskCompleted = true; } }; schedulingService.AddScheduledTask(scheduledTask2); var isCanceled = false; schedulingService.TaskCanceled += (sender, e) => { if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2)) { isCanceled = true; } }; var isCompleted = false; schedulingService.TaskCompleted += (sender, e) => { if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2)) { isCompleted = true; } }; await TaskShim.Delay(TimeSpan.FromSeconds(5)); schedulingService.Stop(); // Additional wait time to allow canceling etc await TaskShim.Delay(TimeSpan.FromSeconds(1)); Assert.IsTrue(isCompleted); Assert.IsTrue(isTaskCompleted); Assert.IsFalse(isCanceled); }
public async Task RestartsRecurringTasks() { // Note: this is a real-time service! Don't wait for minutes here, otherwise unit tests will take too long ;-) var timeService = new TimeService(TimeSpan.FromMinutes(1)); var schedulingService = new SchedulingService(timeService); var scheduledTask1 = new ScheduledTask { Name = "task 1", Start = timeService.CurrentDateTime.AddHours(5) }; schedulingService.AddScheduledTask(scheduledTask1); var taskCompletedCounter = 0; var scheduledTask2 = new ScheduledTask { Name = "task 2", Start = timeService.CurrentDateTime, Action = () => { taskCompletedCounter++; return TaskHelper.Completed; }, Recurring = TimeSpan.FromSeconds(2) }; schedulingService.AddScheduledTask(scheduledTask2); var isCanceled = false; schedulingService.TaskCanceled += (sender, e) => { if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2)) { isCanceled = true; } }; var isCompleted = false; schedulingService.TaskCompleted += (sender, e) => { if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2)) { isCompleted = true; } }; await TaskShim.Delay(TimeSpan.FromSeconds(5)); schedulingService.Stop(); Assert.IsTrue(isCompleted); Assert.IsFalse(isCanceled); Assert.AreEqual(3, taskCompletedCounter); }
public void Calling_TimeService_And_GettingUTCOffset_WithNonExistingLocalTime_Should_ThrowException() { // Arrange var placeId = 187; var localTime = new DateTime (2015, 3, 29, 2, 30, 0); // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); var result = timeservice.CurrentTimeForPlace (new LocationId (placeId)); var firstLocation = result.SingleOrDefault (); // Assert firstLocation.GetUTCOffsetFromLocalTime (localTime); }
public async Task ReturnsFalseForNonExpiredTaskAsync() { var timeService = new TimeService(TimeSpan.FromSeconds(1)); var scheduledTask = new ScheduledTask { MaximumDuration = TimeSpan.FromMinutes(2) }; var runningTask = new RunningTask(scheduledTask, DateTime.Now); await TaskShim.Delay(TimeSpan.FromSeconds(1)); Assert.IsFalse(runningTask.IsExpired(timeService)); }
public TimeReturnValue AddTime(HostSecurityToken oHostSecurityToken, Time time, TimeAdditionalDetail additionalTime, bool postToAccounts) { TimeReturnValue returnValue = null; if (Functions.ValidateIWSToken(oHostSecurityToken)) { oTimeService = new TimeService(); returnValue = oTimeService.AddTime(Functions.GetLogonIdFromToken(oHostSecurityToken), time, additionalTime, postToAccounts); } else { returnValue = new TimeReturnValue(); returnValue.Success = false; returnValue.Message = "Invalid Token"; } return returnValue; }
/// <summary> /// /// </summary> /// <param name="oHostSecurityToken"></param> /// <param name="collectionRequest"></param> /// <returns></returns> public AdvocacyTypeSearchReturnValue AdvocacyTypeSearch(HostSecurityToken oHostSecurityToken, CollectionRequest collectionRequest) { AdvocacyTypeSearchReturnValue returnValue = null; if (Functions.ValidateIWSToken(oHostSecurityToken)) { oTimeService = new TimeService(); returnValue = oTimeService.AdvocacyTypeSearch(Functions.GetLogonIdFromToken(oHostSecurityToken), collectionRequest); } else { returnValue = new AdvocacyTypeSearchReturnValue(); returnValue.Success = false; returnValue.Message = "Invalid Token"; } return returnValue; }
public void Calling_TimeService_And_GettingUTCOffset_Should_ReturnCorrectOffset() { // Arrange var placeId = 187; var localWinterTime = new DateTime (2015, 2, 15, 2, 30, 0); var localSummerTime = new DateTime (2015, 7, 15, 2, 30, 0); var localFallTime = new DateTime (2015, 11, 15, 2, 30, 0); // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); var result = timeservice.CurrentTimeForPlace (new LocationId (placeId)); var firstLocation = result.SingleOrDefault (); var utcWinterOffset = firstLocation.GetUTCOffsetFromLocalTime (localWinterTime); var utcSummerOffset = firstLocation.GetUTCOffsetFromLocalTime (localSummerTime); var utcFallOffset = firstLocation.GetUTCOffsetFromLocalTime (localFallTime); // Assert Assert.AreEqual (TimeSpan.FromHours (1), utcWinterOffset); Assert.AreEqual (TimeSpan.FromHours (2), utcSummerOffset); Assert.AreEqual (TimeSpan.FromHours (1), utcFallOffset); }
public async Task RemovesScheduledTasks() { var timeService = new TimeService(TimeSpan.FromMinutes(1)); var schedulingService = new SchedulingService(timeService); var scheduledTask1 = new ScheduledTask { Name = "task 1", Start = timeService.CurrentDateTime.AddHours(5) }; schedulingService.AddScheduledTask(scheduledTask1); var scheduledTask2 = new ScheduledTask { Name = "task 2", Start = timeService.CurrentDateTime, Action = async () => { await TaskShim.Delay(TimeSpan.FromMinutes(1)); } }; schedulingService.AddScheduledTask(scheduledTask2); Assert.AreEqual(2, schedulingService.ScheduledTasks.Count); schedulingService.RemoveScheduledTask(scheduledTask2); Assert.AreEqual(1, schedulingService.ScheduledTasks.Count); }
/// <summary> /// Get Contact service search on industry /// </summary> /// <param name="oHostSecurityToken"></param> /// <param name="collectionRequest"></param> /// <param name="criteria"></param> /// <returns></returns> public ServiceContactSearchReturnValue ServiceContactSearch(HostSecurityToken oHostSecurityToken, CollectionRequest collectionRequest, Guid assocParentOrgID, string OrderBy) { ServiceContactSearchReturnValue returnValue = null; if (Functions.ValidateIWSToken(oHostSecurityToken)) { oTimeService = new TimeService(); returnValue = oTimeService.ServiceContactSearch(Functions.GetLogonIdFromToken(oHostSecurityToken), collectionRequest, assocParentOrgID, OrderBy); } else { returnValue = new ServiceContactSearchReturnValue(); returnValue.Success = false; returnValue.Message = "Invalid Token"; } return returnValue; }
public void Calling_TimeService_WithTextualId_Should_ReturnCorrectTimezone() { // Arrange var placeName = "norway/oslo"; var expectedTimezoneAbbr = "CEST"; var expectedTimezoneName = "Central European Summer Time"; var expectedOffsetHour = 2; var expectedOffsetMinute = 0; var expectedBasicOffset = 3600; var expectedDstOffset = 3600; var expectedTotalOffset = 7200; // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); var result = timeservice.CurrentTimeForPlace (new LocationId(placeName)); var firstLocation = result.SingleOrDefault (); // Assert Assert.AreEqual (expectedTimezoneAbbr, firstLocation.Time.Timezone.Abbrevation); Assert.AreEqual (expectedTimezoneName, firstLocation.Time.Timezone.Name); Assert.AreEqual (expectedOffsetHour, firstLocation.Time.Timezone.Offset.Hours); Assert.AreEqual (expectedOffsetMinute, firstLocation.Time.Timezone.Offset.Minutes); Assert.AreEqual (expectedBasicOffset, firstLocation.Time.Timezone.BasicOffset); Assert.AreEqual (expectedDstOffset, firstLocation.Time.Timezone.DSTOffset); Assert.AreEqual (expectedTotalOffset, firstLocation.Time.Timezone.TotalOffset); }
public void Calling_TimeService_WithTextualId_Should_ReturnCorrectTimeChanges() { // Arrange var placeName = "norway/oslo"; var expectedFirstNewOffset = 7200; var expectedFirstNewDstOffset = 3600; var expectedSecondNewOffset = 3600; // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); var result = timeservice.CurrentTimeForPlace (new LocationId(placeName)); var firstLocation = result.SingleOrDefault (); var firstChange = firstLocation.TimeChanges.FirstOrDefault (); var secondChange = firstLocation.TimeChanges.Skip (1).FirstOrDefault (); // Assert Assert.IsTrue (firstChange.NewDaylightSavingTime.HasValue); Assert.AreEqual (expectedFirstNewDstOffset, firstChange.NewDaylightSavingTime.Value); Assert.AreEqual (expectedFirstNewOffset, firstChange.NewTotalOffset); Assert.AreEqual (expectedSecondNewOffset, secondChange.NewTotalOffset); }
public void Calling_TimeService_WithTextualId_Should_ReturnCorrectTime() { // Arrange var placeName = "norway/oslo"; var now = DateTime.Now; // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); var result = timeservice.CurrentTimeForPlace (new LocationId(placeName)); var firstLocation = result.SingleOrDefault (); // Assert Assert.AreEqual (now.Year, firstLocation.Time.DateTime.Year); }
/// <summary> /// /// </summary> /// <param name="oHostSecurityToken"></param> /// <param name="collectionRequest"></param> /// <param name="criteria"></param> /// <returns></returns> public ChargeRateSearchReturnValue ChargeRateOnPublicFundingSearch(HostSecurityToken oHostSecurityToken, CollectionRequest collectionRequest, ChargeRateSearchCriteria criteria) { ChargeRateSearchReturnValue returnValue = null; if (Functions.ValidateIWSToken(oHostSecurityToken)) { oTimeService = new TimeService(); returnValue = oTimeService.ChargeRateOnPublicFundingSearch(Functions.GetLogonIdFromToken(oHostSecurityToken), collectionRequest, criteria); } else { returnValue = new ChargeRateSearchReturnValue(); returnValue.Success = false; returnValue.Message = "Invalid Token"; } return returnValue; }
/// <summary> /// /// </summary> /// <param name="oHostSecurityToken"></param> /// <param name="collectionRequest"></param> /// <returns></returns> public ServiceSearchReturnValue ServiceSearch(HostSecurityToken oHostSecurityToken, CollectionRequest collectionRequest, int associationRoleId) { ServiceSearchReturnValue returnValue = null; if (Functions.ValidateIWSToken(oHostSecurityToken)) { oTimeService = new TimeService(); returnValue = oTimeService.ServiceSearch(Functions.GetLogonIdFromToken(oHostSecurityToken), collectionRequest, associationRoleId); } else { returnValue = new ServiceSearchReturnValue(); returnValue.Success = false; returnValue.Message = "Invalid Token"; } return returnValue; }
/// <summary> /// Get all the unposted time sheet for the current date for the logged in fee earner /// </summary> /// <param name="oHostSecurityToken"></param> /// <param name="collectionRequest"></param> /// <param name="criteria"></param> /// <returns></returns> public UnPostedTimeSearchReturnValue UnPostedTimeSheetSearch(HostSecurityToken oHostSecurityToken, CollectionRequest collectionRequest, UnPostedTimeSearchCriteria criteria) { UnPostedTimeSearchReturnValue returnValue = null; if (Functions.ValidateIWSToken(oHostSecurityToken)) { oTimeService = new TimeService(); returnValue = oTimeService.UnPostedTimeSheetSearch(Functions.GetLogonIdFromToken(oHostSecurityToken), collectionRequest, criteria); } else { returnValue = new UnPostedTimeSearchReturnValue(); returnValue.Success = false; returnValue.Message = "Invalid Token"; } return returnValue; }
/// <summary> /// Validates the period. /// </summary> /// <param name="oHostSecurityToken">User token</param> /// <param name="criteria">The criteria.</param> /// <returns></returns> public PeriodDetailsReturnValue ValidatePeriod(HostSecurityToken oHostSecurityToken, PeriodCriteria criteria) { PeriodDetailsReturnValue returnValue = null; if (Functions.ValidateIWSToken(oHostSecurityToken)) { oTimeService = new TimeService(); returnValue = oTimeService.ValidatePeriod(Functions.GetLogonIdFromToken(oHostSecurityToken), criteria); } else { returnValue = new PeriodDetailsReturnValue(); returnValue.Success = false; returnValue.Message = "Invalid Token"; } return returnValue; }
public void Calling_TimeService_WithCoordinates_Should_ReturnCorrectTime() { // Arrange var osloCoords = new Coordinates (59.914m, 10.752m); var expectedId = String.Format ("+{0}+{1}", osloCoords.Latitude.ToString (CultureInfo.InvariantCulture), osloCoords.Longitude.ToString (CultureInfo.InvariantCulture)); var now = DateTime.Now; // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); timeservice.IncludeCoordinates = true; var result = timeservice.CurrentTimeForPlace (new LocationId (osloCoords)); var firstLocation = result.SingleOrDefault (); // Assert Assert.AreEqual (now.Year, firstLocation.Time.DateTime.Year); Assert.AreEqual (expectedId, firstLocation.Id); }
public void Calling_TimeService_WithCoordinates_Should_ReturnCorrectGeo() { // Arrange var osloCoords = new Coordinates (59.914m, 10.752m); var expectedId = String.Format ("+{0}+{1}", osloCoords.Latitude.ToString (CultureInfo.InvariantCulture), osloCoords.Longitude.ToString (CultureInfo.InvariantCulture)); // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); var result = timeservice.CurrentTimeForPlace (new LocationId (osloCoords)); var firstLocation = result.SingleOrDefault (); // Assert Assert.AreEqual (osloCoords.Latitude, firstLocation.Geography.Coordinates.Latitude); Assert.AreEqual (osloCoords.Longitude, firstLocation.Geography.Coordinates.Longitude); Assert.AreEqual (expectedId, firstLocation.Id); Assert.IsNull (firstLocation.Geography.Country); Assert.IsNull (firstLocation.Geography.State); Assert.IsNull (firstLocation.Geography.Name); }
/// <summary> /// Post todays time sheets for accounting /// </summary> /// <param name="oHostSecurityToken">User token</param> /// <param name="timeSheet">Fee Earner Time Sheet</param> /// <returns></returns> public ReturnValue PostTime(HostSecurityToken oHostSecurityToken, TimeSheet timeSheet) { ReturnValue returnValue = null; if (Functions.ValidateIWSToken(oHostSecurityToken)) { oTimeService = new TimeService(); returnValue = oTimeService.PostTime(Functions.GetLogonIdFromToken(oHostSecurityToken), timeSheet); } else { returnValue = new ReturnValue(); returnValue.Success = false; returnValue.Message = "Invalid Token"; } return returnValue; }
public async Task CancelsRunningTasksAboveMaximumDuration() { var timeService = new TimeService(TimeSpan.FromSeconds(1)); var schedulingService = new SchedulingService(timeService); var scheduledTask1 = new ScheduledTask { Name = "task 1", Start = timeService.CurrentDateTime.AddHours(5) }; schedulingService.AddScheduledTask(scheduledTask1); bool isTaskCompleted = false; var scheduledTask2 = new ScheduledTask { Name = "task 2", Start = timeService.CurrentDateTime, Action = async () => { await TaskShim.Delay(TimeSpan.FromMinutes(1)); isTaskCompleted = true; }, MaximumDuration = TimeSpan.FromSeconds(30) }; schedulingService.AddScheduledTask(scheduledTask2); var isCanceled = false; schedulingService.TaskCanceled += (sender, e) => { if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2)) { isCanceled = true; } }; var isCompleted = false; schedulingService.TaskCompleted += (sender, e) => { if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2)) { isCompleted = true; } }; await TaskShim.Delay(TimeSpan.FromSeconds(2)); Assert.IsFalse(isCompleted); Assert.IsFalse(isTaskCompleted); Assert.IsTrue(isCanceled); schedulingService.Stop(); }
public void Calling_TimeService_WithTextualId_Should_ReturnCorrectGeo() { // Arrange var expectedCountry = "Norway"; var expectedPlace = "Oslo"; var placeName = String.Format ("{0}/{1}", expectedCountry, expectedPlace).ToLower (); var expectedCountryId = "no"; var expectedPlaceId = "187"; // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); var result = timeservice.CurrentTimeForPlace (new LocationId(placeName)); var firstLocation = result.SingleOrDefault (); // Assert Assert.AreEqual (expectedCountry, firstLocation.Geography.Country.Name); Assert.AreEqual (expectedCountryId, firstLocation.Geography.Country.Id); Assert.AreEqual (expectedPlace, firstLocation.Geography.Name); Assert.AreEqual (expectedPlaceId, firstLocation.Id); }
public async Task DisablesTimerWhenNoTasksAreScheduled() { var timeService = new TimeService(TimeSpan.FromMinutes(1)); var schedulingService = new SchedulingService(timeService); schedulingService.Start(); }
/// <summary> /// Validates the time type. /// </summary> /// <param name="oHostSecurityToken">User token</param> /// <param name="criteria">The criteria.</param> /// <returns></returns> public ReturnValue ValidateTimeTypeForPosting(HostSecurityToken oHostSecurityToken, TimeTypeCriteria criteria) { ReturnValue returnValue = null; if (Functions.ValidateIWSToken(oHostSecurityToken)) { oTimeService = new TimeService(); returnValue = oTimeService.ValidateTimeTypeForPosting(Functions.GetLogonIdFromToken(oHostSecurityToken), criteria); } else { returnValue = new ReturnValue(); returnValue.Success = false; returnValue.Message = "Invalid Token"; } return returnValue; }
protected internal void SetTimeservice(TimeService service) { _timeService = service; }
public void Calling_TimeService_WithNumericId_Should_ReturnCorrectLocation() { // Arrange var placeId = 179; // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); var result = timeservice.CurrentTimeForPlace (new LocationId(placeId)); var firstLocation = result.SingleOrDefault (); // Assert Assert.AreEqual (placeId.ToString (), firstLocation.Id); }
public TimeReturnValue GetAddtionalDetailTime(HostSecurityToken oHostSecurityToken, Time time) { TimeReturnValue returnValue = null; if (Functions.ValidateIWSToken(oHostSecurityToken)) { oTimeService = new TimeService(); returnValue = oTimeService.GetAddtionalDetailTime(Functions.GetLogonIdFromToken(oHostSecurityToken), time); } else { returnValue = new TimeReturnValue(); returnValue.Success = false; returnValue.Message = "Invalid Token"; } return returnValue; }
public void Calling_TimeService_WithTextualId_Should_ReturnCorrectAstronomy() { // Arrange var placeName = "norway/oslo"; var expectedObjectName = AstronomyObjectType.Sun; var expectedRise = AstronomyEventType.Rise; var expectedSet = AstronomyEventType.Set; // Act var timeservice = new TimeService (Config.AccessKey, Config.SecretKey); var result = timeservice.CurrentTimeForPlace (new LocationId(placeName)); var firstLocation = result.SingleOrDefault (); var firstObject = firstLocation.Astronomy.FirstOrDefault (); var rise = firstObject.Events.FirstOrDefault (); var set = firstObject.Events.Skip (1).FirstOrDefault (); // Assert Assert.AreEqual (expectedObjectName, firstObject.Name); Assert.AreEqual (expectedRise, rise.Type); Assert.AreEqual (expectedSet, set.Type); // Sunrise in Oslo is most likely never before 3 and never after 10 // Sunset in Oslo is most likely never before 14 and never after 22 Assert.IsTrue (rise.Time.Hour >= 3 && rise.Time.Hour <= 10); Assert.IsTrue (set.Time.Hour >= 14 && set.Time.Hour <= 22); }