Example #1
0
        public void TestAddActionRuns()
        {
            bool ran = false;

            Instant due = TimeHelpers.Clock.Now + Duration.FromMilliseconds(100);

            Assert.IsTrue(due > TimeHelpers.Clock.Now);

            ScheduledAction action = Scheduler.Add(() => { ran = true; }, new OneOffSchedule(due));

            Assert.IsTrue(due > TimeHelpers.Clock.Now);

            Assert.IsNotNull(action);
            Assert.IsTrue(action.Enabled);
            Assert.AreEqual(Scheduler.DefaultMaximumHistory, action.MaximumHistory);
            Assert.AreEqual(Scheduler.DefaultMaximumDuration, action.MaximumDuration);
            Thread.Sleep(200);
            Assert.IsTrue(ran);
            Assert.AreEqual(1, action.History.Count());

            ScheduledActionResult history = action.History.FirstOrDefault();

            Assert.IsNotNull(history);
            Assert.IsFalse(history.Cancelled);
            Assert.IsNull(history.Exception);
            Assert.AreEqual(due, history.Due);
            Assert.IsTrue(history.Due <= history.Started);
        }
        public static void ConfigureForNodaTime(this SwaggerGenOptions config, IDateTimeZoneProvider dateTimeZoneProvider)
        {
            var dateTimeZone     = dateTimeZoneProvider[America.NewYork];
            var instant          = SystemClock.Instance.GetCurrentInstant();
            var interval         = new Interval(instant, instant + Duration.FromMilliseconds(182713784L));
            var dateTimeInterval = interval.InZoneStrictly(dateTimeZone);

            var zonedDateTime = dateTimeZone.AtLeniently(instant.InZone(dateTimeZone).LocalDateTime.With(TimeAdjusters.TruncateToMinute));

            var localDateTime  = zonedDateTime.LocalDateTime;
            var localDate      = localDateTime.Date;
            var dateInterval   = localDateTime.Date.GetContainingWeekInterval(IsoDayOfWeek.Monday);
            var localTime      = localDateTime.TimeOfDay;
            var timeInterval   = new TimeInterval(localTime, localTime + Period.FromHours(3) + Period.FromMinutes(45));
            var offsetDateTime = zonedDateTime.ToOffsetDateTime();
            var duration       = Duration.FromDays(2) + Duration.FromHours(3) + Duration.FromMinutes(45);
            var offset         = dateTimeZone.GetUtcOffset(instant);
            var period         = Period.FromTicks(duration.BclCompatibleTicks);

            config.MapStruct(instant);
            config.MapStruct(localDate);
            config.MapStruct(localTime);
            config.MapStruct(localDateTime);
            config.MapStruct(offsetDateTime);
            config.MapStruct(zonedDateTime);
            config.MapStruct(interval);
            config.MapClass(dateInterval);
            config.MapClass(dateTimeInterval);
            config.MapClass(timeInterval);
            config.MapStruct(offset);
            config.MapClass(period);
            config.MapStruct(duration);
            config.MapClass(dateTimeZone);
        }
        public void Test_ZonedDateTime()
        {
            CreateTable("timestamptz");

            var subject = new PostgreSQLCopyHelper <AllNodaTypesEntity>("sample", "noda_time_test")
                          .MapTimeStampTz("col_noda", x => x.ZonedDateTime);

            var timezone = DateTimeZoneProviders.Tzdb.GetZoneOrNull("Africa/Kigali");
            var instant  = Instant.FromUtc(2011, 1, 5, 22, 50, 0) + Duration.FromMilliseconds(193);

            var entity = new AllNodaTypesEntity
            {
                ZonedDateTime = new ZonedDateTime(instant, timezone)
            };

            var entities = new[]
            {
                entity
            };

            subject.SaveAll(connection, entities);

            // Check what's written to DB:
            var rows = GetAll();

            // TODO: How does Postgres <-> NodaTime convert Timezones? There is a good test here, but
            // I couldn't see through it yet:
            //
            //    https://github.com/npgsql/npgsql/blob/766658172f08abb0b87a6b7f01a7ea4b49952a29/test/Npgsql.PluginTests/NodaTimeTests.cs
            //
            var actual = (Instant)rows[0][0];

            Assert.AreEqual(instant, actual);
        }
Example #4
0
        private void ValidateZoneEquality(Instant instant, DateTimeZone nodaZone, TimeZoneInfo windowsZone)
        {
            // The BCL is basically broken (up to and including .NET 4.5.1 at least) around its interpretation
            // of its own data around the new year. See http://codeblog.jonskeet.uk/2014/09/30/the-mysteries-of-bcl-time-zone-data/
            // for details. We're not trying to emulate this behaviour.
            // It's a lot *better* for .NET 4.6,
            // FIXME: Finish this comment, try again. (We don't test against .NET 4.5 any more...)
            var utc = instant.InUtc();

            if ((utc.Month == 12 && utc.Day == 31) || (utc.Month == 1 && utc.Day == 1))
            {
                return;
            }

            var interval = nodaZone.GetZoneInterval(instant);

            // Check that the zone interval really represents a transition. It could be a change in
            // wall offset, name, or the split between standard time and daylight savings for the interval.
            if (interval.RawStart != Instant.BeforeMinValue)
            {
                var previousInterval = nodaZone.GetZoneInterval(interval.Start - Duration.Epsilon);
                Assert.AreNotEqual(new { interval.WallOffset, interval.Name, interval.StandardOffset },
                                   new { previousInterval.WallOffset, previousInterval.Name, previousInterval.StandardOffset },
                                   "Non-transition from {0} to {1}", previousInterval, interval);
            }
            var nodaOffset = interval.WallOffset;

            // Some midnight transitions in the Noda Time representation are actually corrections for the
            // BCL data indicating 23:59:59.999 on the previous day. If we're testing around midnight,
            // allow the Windows data to be correct for either of those instants.
            var acceptableInstants = new List <Instant> {
                instant
            };
            var localTimeOfDay = instant.InZone(nodaZone).TimeOfDay;

            if ((localTimeOfDay == LocalTime.Midnight || localTimeOfDay == LocalTime.MaxValue) && instant > NodaConstants.BclEpoch)
            {
                acceptableInstants.Add(instant - Duration.FromMilliseconds(1));
            }

            var expectedOffsetAsTimeSpan = nodaOffset.ToTimeSpan();

            // Find an instant that at least has the right offset (so will pass the first assertion).
            var instantToTest = acceptableInstants.FirstOrDefault(candidate => windowsZone.GetUtcOffset(candidate.ToDateTimeUtc()) == expectedOffsetAsTimeSpan);

            // If the test is definitely going to fail, just use the original instant that was passed in.
            if (instantToTest == default)
            {
                instantToTest = instant;
            }

            var windowsOffset = windowsZone.GetUtcOffset(instantToTest.ToDateTimeUtc());

            Assert.AreEqual(windowsOffset, expectedOffsetAsTimeSpan, "Incorrect offset at {0} in interval {1}", instantToTest, interval);
            var bclDaylight = windowsZone.IsDaylightSavingTime(instantToTest.ToDateTimeUtc());

            Assert.AreEqual(bclDaylight, interval.Savings != Offset.Zero,
                            "At {0}, BCL IsDaylightSavingTime={1}; Noda savings={2}",
                            instant, bclDaylight, interval.Savings);
        }
        private JobProgress CalculateProgressAfterRead()
        {
            // There's no need to consider _context.End here. We just calculate the prospective next iteration span
            // and it will be looked at and fixed before the next iteration, if needed.

            if (!string.IsNullOrWhiteSpace(_readResponse.NextToken))
            {
                return(new JobProgress(Progress.NextIterationStart, Progress.NextIterationEnd, _readResponse.NextToken));
            }

            // If the current timespan is completed, we start from one millisecond after the end of this timespan
            // because AWS APIs accept milliseconds as timespan, so the resolution is 1 ms. And the API is
            // inclusive for both start and end, so we don't want events with timestamp equal to previous end
            // be returned twice.
            var start = Progress.NextIterationEnd.Plus(Duration.FromMilliseconds(1));

            var endCutoffInstant = InstantUtils.SecondsAgo(_context.ClockSkewProtectionSeconds);
            var minEndInstant    = start.Plus(Duration.FromSeconds(_context.MinIntervalSeconds));
            var maxEndInstant    = start.Plus(Duration.FromSeconds(_context.MaxIntervalSeconds));

            if (minEndInstant > endCutoffInstant)
            {
                return(new JobProgress(start, minEndInstant, null));
            }

            var end = maxEndInstant;

            if (end > endCutoffInstant)
            {
                end = endCutoffInstant;
            }

            return(new JobProgress(start, end, null));
        }
        private static DomainParticipantQos ConfigureFlowController(
            uint tokenBucketPeriodMs)
        {
            // We'll get the QoS defined in the XML profile "cfc_Profile"
            // (the default profile in USER_QOS_PROFILES.xml) and tweak the
            // token bucket period
            DomainParticipantQos baseQos =
                QosProvider.Default.GetDomainParticipantQos();

            if (tokenBucketPeriodMs == 0)
            {
                return(baseQos);
            }

            // This is the name we use in the XML file
            const string flowControllerName =
                "dds.flow_controller.token_bucket.custom_flowcontroller";

            // baseQos.WithProperty(...) creates a new DomainParticipantQos
            // object with the changes we specify in the lambda function.
            return(baseQos.WithProperty(property =>
            {
                // In WithProperty the input argument 'property' contains the
                // current values of baseQos.Property. We will just modify these
                // two properties.
                var period = Duration.FromMilliseconds(tokenBucketPeriodMs);
                property[$"{flowControllerName}.token_bucket.period.sec"] =
                    period.Seconds.ToString();
                property[$"{flowControllerName}.token_bucket.period.nanosec"] =
                    period.Nanoseconds.ToString();
            }));
        }
Example #7
0
        private Timestamp GetNextNormalizedTimestamp(Timestamp tCurrent, Duration cycle, Duration offset, CalcInstance adapter)
        {
            Timestamp tNext = Time.GetNextNormalizedTimestamp(cycle, offset);

            Duration minDuration = Duration.FromMilliseconds(1);
            Duration c           = cycle < minDuration ? minDuration : cycle;

            while (tNext <= tCurrent)
            {
                tNext += c;
            }

            Trigger trigger = adapter.triggerDurationWarning.GetTrigger(isOK: tNext == tCurrent + cycle);

            if (trigger == Trigger.On)
            {
                Log_Warn("Cycle", $"Cycle length of {cycle} not long enough for calculation {adapter.Name}!", null, new ObjectRef[] { adapter.ID });
            }
            else if (trigger == Trigger.Off)
            {
                Log_ReturnToNormal("Cycle", $"Cycle length of {cycle} is long enough for calculation {adapter.Name}.", new ObjectRef[] { adapter.ID });
            }

            return(tNext);
        }
Example #8
0
        internal void CanThrottleMessagesPer100Milliseconds_Test1()
        {
            // Arrange
            var throttler = new Throttler <string>(
                this.container,
                this.receiver.Endpoint.Send,
                Duration.FromMilliseconds(100),
                10,
                "1");

            // Act
            for (var i = 0; i < 21; i++)
            {
                throttler.Endpoint.SendAsync($"Message-{i + 1}");
            }

            Task.Delay(10).Wait();

            // Should receives only the first 10 messages
            var count1 = this.receiver.Messages.Count;

            // Wait for the throttle duration interval
            // Should receive the next 10 messages
            Task.Delay(100).Wait();
            throttler.Stop().Wait();

            // Assert
            Assert.Equal(10, count1);
            Assert.Equal(20, this.receiver.Messages.Count);
            Assert.Equal(1, throttler.QueueCount);
            Assert.True(throttler.IsActive);
        }
Example #9
0
        public async Task Run(int delayMs, Instant?start)
        {
            await using var conn = await _db.Obtain();

            HashSet <Guid> lastIds = null;

            while (true)
            {
                var url       = GetFeedUrl(start, 1000);
                var feedItems = await GetFeedItems(url);

                if (feedItems.Count == 0)
                {
                    break;
                }

                if (lastIds != null && lastIds.SetEquals(feedItems.Select(i => i.Id)))
                {
                    break;
                }

                var saved = await _feedStore.SaveFeedItems(conn, feedItems);

                _logger.Information("Fetched {ItemCount} new feed items starting at {BeforeFilter} ({NewItems} new)", feedItems.Count,
                                    start, saved);

                start = feedItems.Max(i => i.Timestamp) - Duration.FromMilliseconds(1);

                lastIds = feedItems.Select(i => i.Id).ToHashSet();
                await Task.Delay(TimeSpan.FromMilliseconds(delayMs));
            }

            _logger.Information("Done fetching feed!");
        }
        public static SwaggerDocsConfig ConfigureForNodaTime(this SwaggerDocsConfig config, IDateTimeZoneProvider timeZoneProvider)
        {
            var timeZone       = timeZoneProvider[America.NewYork];
            var instant        = SystemClock.Instance.GetCurrentInstant();
            var zonedDateTime  = instant.InZone(timeZone);
            var localDate      = zonedDateTime.Date;
            var localTime      = zonedDateTime.TimeOfDay;
            var localDateTime  = zonedDateTime.LocalDateTime;
            var offsetDateTime = zonedDateTime.ToOffsetDateTime();
            var duration       = Duration.FromMilliseconds(182713784L);
            var interval       = new Interval(instant, instant + duration);
            var offset         = timeZone.GetUtcOffset(instant);
            var period         = Period.Between(localDateTime, localDateTime.PlusTicks(duration.BclCompatibleTicks));

            config.MapStruct(instant);
            config.MapStruct(localDate);
            config.MapStruct(localTime);
            config.MapStruct(localDateTime);
            config.MapStruct(offsetDateTime);
            config.MapStruct(zonedDateTime);
            config.MapStruct(interval);
            config.MapStruct(offset);
            config.MapClass(period);
            config.MapStruct(duration);
            config.MapClass(timeZone);

            return(config);
        }
Example #11
0
        private static Duration _offsetFromStart(LocalTime time, TimePeriod period)
        {
            var offset = Duration.Zero;

            offset += Duration.FromTicks(time.TickOfSecond);
            offset += Duration.FromMilliseconds(time.Second);

            switch (period)
            {
            case TimePeriod.Hour:
                offset += Duration.FromMinutes(time.Minute);
                break;

            case TimePeriod.Minute:
                break;

            case TimePeriod.TenMinutes:
                offset += Duration.FromMinutes(time.Minute % 10);
                break;

            case TimePeriod.QuarterHour:
                offset += Duration.FromMinutes(time.Minute % 15);
                break;

            case TimePeriod.HalfHour:
                offset += Duration.FromMinutes(time.Minute % 30);
                break;
            }

            return(offset);
        }
Example #12
0
        public static void WaitForFile(string path, string pattern, int duration, int interval)
        {
            path = GetPathForFile(path);
            var bFound = Directory.GetFiles(path, pattern).Length > 0;
            var start  = System.DateTime.Now;

            while (!bFound && (System.DateTime.Now < start + TimeSpan.FromMilliseconds(duration)))
            {
                bFound = Directory.GetFiles(path, pattern).Length > 0;

                if (bFound)
                {
                    break;
                }

                Delay.Duration(Duration.FromMilliseconds(interval), false);
            }

            if (bFound)
            {
                Report.Success("Validation", "File with pattern '" + pattern + "' was found in directory '" + path + "'.");
            }
            else
            {
                Report.Failure("Validation", "File with pattern '" + pattern + "' wasn't found in directory '" + path + "'.");
            }
        }
Example #13
0
        internal void Equals_VariousValues_ReturnsExpectedResult(
            decimal price1,
            decimal price2,
            int millisecondsOffset,
            bool expected)
        {
            // Arrange
            var tick1 = new TradeTick(
                this.symbol,
                Price.Create(price1),
                Quantity.Create(10000),
                Maker.Buyer,
                new MatchId("123456789"),
                StubZonedDateTime.UnixEpoch());

            var tick2 = new TradeTick(
                this.symbol,
                Price.Create(price2),
                Quantity.Create(10000),
                Maker.Buyer,
                new MatchId("123456789"),
                StubZonedDateTime.UnixEpoch() + Duration.FromMilliseconds(millisecondsOffset));

            // Act
            var result1 = tick1.Equals(tick2);
            var result2 = tick1 == tick2;

            // Assert
            Assert.Equal(expected, result1);
            Assert.Equal(expected, result2);
        }
        public void FromMilliseconds_Double(double milliseconds, int expectedDays, long expectedNanoOfDay)
        {
            var actual   = Duration.FromMilliseconds(milliseconds);
            var expected = new Duration(expectedDays, expectedNanoOfDay);

            Assert.AreEqual(expected, actual);
        }
Example #15
0
 /// <summary>
 /// Changes the specified due time and period.
 /// </summary>
 /// <param name="period">The optional minimum gap (in milliseconds) between the start of the task invocation and the start of the previous task invocation; use <see langword="null"/> to leave the value unchanged.</param>
 /// <param name="dueTime">The optional due time (in milliseconds) between the last time the timeouts were changed and the start of the task invocation; use <see langword="null"/> to leave the value unchanged.</param>
 /// <param name="minimumGap">The optional minimum gap (in milliseconds) between the start of the task invocation and the end of the previous task invocation; use <see langword="null"/> to leave the value unchanged.</param>
 public void Change(int?period = null, int?dueTime = null, int?minimumGap = null)
 {
     Change(
         period.HasValue ? Duration.FromMilliseconds(period.Value) : (Duration?)null,
         dueTime.HasValue ? Duration.FromMilliseconds(dueTime.Value) : (Duration?)null,
         minimumGap.HasValue ? Duration.FromMilliseconds(minimumGap.Value) : (Duration?)null);
 }
Example #16
0
        public override async Task TakeMeasurementAsync()
        {
            if (CurrentState != SensorStateEnum.Initialized)
            {
                throw new InvalidOperationException("Can't take measurement on uninitialized sensor!");
            }

            _bme680.ConfigureHeatingProfile(Bme680HeaterProfile.Profile2,
                                            Temperature.FromDegreesCelsius(280), Duration.FromMilliseconds(80),
                                            Temperature.FromDegreesCelsius(_lastMeasurement.Temperature));
            var measurementDuration = _bme680.GetMeasurementDuration(_bme680.HeaterProfile);

            /* Force the sensor to take a measurement. */
            _bme680.SetPowerMode(Bme680PowerMode.Forced);
            await Task.Delay(measurementDuration.ToTimeSpan());

            _bme680.TryReadTemperature(out var temp);
            _bme680.TryReadHumidity(out var humidity);
            _bme680.TryReadPressure(out var pressure);
            _bme680.TryReadGasResistance(out var gasResistance);

            _lastMeasurement.Temperature = Math.Round(temp.DegreesCelsius, 2);
            _lastMeasurement.Pressure    = Math.Round(pressure.Hectopascals, 2);
            _lastMeasurement.Humidity    = Math.Round(humidity.Percent, 2);
            _lastMeasurement.VolatileOrganicCompounds = Math.Round(gasResistance.Kiloohms, 2);

            Logger?.LogDebug($"{DateTimeOffset.Now}:BME680: reading");
            Logger?.LogInformation(
                $"temperature:{_lastMeasurement.Temperature:N2} \u00B0C|" +
                $"pressure:{_lastMeasurement.Pressure:N2} hPa|" +
                $"humidity:{_lastMeasurement.Humidity:N2} %rH|" +
                $"voc:{_lastMeasurement.VolatileOrganicCompounds}");
        }
Example #17
0
        public void Add_MethodEquivalents()
        {
            const int  minutes      = 23;
            const int  hours        = 3;
            const int  milliseconds = 40000;
            const long seconds      = 321;
            const long nanoseconds  = 12345;
            const long ticks        = 5432112345;

            ZonedDateTime before = SampleZone.AtStrictly(new LocalDateTime(2011, 6, 12, 15, 0));

            Assert.AreEqual(before + Duration.OneDay, ZonedDateTime.Add(before, Duration.OneDay));
            Assert.AreEqual(before + Duration.OneDay, before.Plus(Duration.OneDay));

            Assert.AreEqual(before + Duration.FromHours(hours), before.PlusHours(hours));
            Assert.AreEqual(before + Duration.FromHours(-hours), before.PlusHours(-hours));

            Assert.AreEqual(before + Duration.FromMinutes(minutes), before.PlusMinutes(minutes));
            Assert.AreEqual(before + Duration.FromMinutes(-minutes), before.PlusMinutes(-minutes));

            Assert.AreEqual(before + Duration.FromSeconds(seconds), before.PlusSeconds(seconds));
            Assert.AreEqual(before + Duration.FromSeconds(-seconds), before.PlusSeconds(-seconds));

            Assert.AreEqual(before + Duration.FromMilliseconds(milliseconds), before.PlusMilliseconds(milliseconds));
            Assert.AreEqual(before + Duration.FromMilliseconds(-milliseconds), before.PlusMilliseconds(-milliseconds));

            Assert.AreEqual(before + Duration.FromTicks(ticks), before.PlusTicks(ticks));
            Assert.AreEqual(before + Duration.FromTicks(-ticks), before.PlusTicks(-ticks));

            Assert.AreEqual(before + Duration.FromNanoseconds(nanoseconds), before.PlusNanoseconds(nanoseconds));
            Assert.AreEqual(before + Duration.FromNanoseconds(-nanoseconds), before.PlusNanoseconds(-nanoseconds));
        }
Example #18
0
        internal void CleanUp()
        {
            // Skip non-transactional modification methods because they could cause database connections to be reinitialized.
            cleanUpDatabaseConnectionsAndExecuteNonTransactionalModificationMethods(skipNonTransactionalModificationMethods: true);

            if (errorPrefix.Any() || errorException != null)
            {
                TelemetryStatics.ReportError(errorPrefix, errorException);
                MiniProfiler.Stop();
            }
            else
            {
                var duration = SystemClock.Instance.GetCurrentInstant() - beginInstant;
                MiniProfiler.Stop();
                if (MiniProfiler.Current != null)
                {
                    duration = Duration.FromMilliseconds((double)MiniProfiler.Current.DurationMilliseconds);
                }
                const int thresholdInSeconds = 30;
                if (duration > Duration.FromSeconds(thresholdInSeconds) && !ConfigurationStatics.IsDevelopmentInstallation)
                {
                    TelemetryStatics.ReportError(
                        "Request took " + duration.TotalSeconds + " seconds to process. The threshold is " + thresholdInSeconds + " seconds.",
                        null);
                }
            }
        }
Example #19
0
        public void TestAddActionCancel()
        {
            bool            ran      = false;
            Instant         due      = TimeHelpers.Clock.Now + Duration.FromMilliseconds(100);
            Duration        duration = Duration.FromMilliseconds(20);
            ScheduledAction action   = Scheduler.Add(
                () =>
            {
                ran = true;
                // This needs to sleep longer than the max duration to ensure it will be cancelled
                Thread.Sleep((int)duration.TotalMilliseconds() * 2);
            },
                new OneOffSchedule(due),
                maximumDuration: duration);

            Assert.IsNotNull(action);
            Assert.IsTrue(action.Enabled);
            Assert.AreEqual(Scheduler.DefaultMaximumHistory, action.MaximumHistory);
            Assert.AreEqual(duration, action.MaximumDuration);
            Thread.Sleep(200);
            Assert.IsTrue(ran);
            Assert.AreEqual(1, action.History.Count());

            ScheduledActionResult history = action.History.FirstOrDefault();

            Assert.IsNotNull(history);
            Assert.IsTrue(history.Cancelled);
            Assert.IsNull(history.Exception);
            Assert.AreEqual(due, history.Due);
            Assert.IsTrue(history.Due <= history.Started);
        }
 public void DoNotSaveIfAsked(RepoItemInfo buttonInfo)
 {
     if (buttonInfo.Exists(Duration.FromMilliseconds(1000)))
     {
         Report.Log(ReportLevel.Info, "Mouse", "(Optional Action)\r\nMouse Left Click item 'buttonInfo' at Center.", buttonInfo);
         buttonInfo.FindAdapter <Button>().Click();
     }
 }
Example #21
0
        public void ConstructionFromMilliseconds()
        {
            Duration duration = Snippet.For(Duration.FromMilliseconds(600));

            Assert.AreEqual(600, duration.Milliseconds);
            Assert.AreEqual(0.6, duration.TotalSeconds);
            Assert.AreEqual("0:00:00:00.6", duration.ToString());
        }
        public void RoundTrip()
        {
            var startInstant = Instant.FromUtc(2012, 1, 2, 3, 4, 5) + Duration.FromMilliseconds(670);
            var endInstant   = Instant.FromUtc(2013, 6, 7, 8, 9, 10) + Duration.FromNanoseconds(123456789);
            var interval     = new Interval(startInstant, endInstant);

            AssertConversions(interval, "{\"Start\":\"2012-01-02T03:04:05.67Z\",\"End\":\"2013-06-07T08:09:10.123456789Z\"}", settings);
        }
Example #23
0
        static void Main(string[] args)
        {
            _dpf = DomainParticipantFactory.Instance;
            ErrorHandler.checkHandle(_dpf, "Domain Participant Factory");

            _dp = _dpf.CreateParticipant(Domain);

            //Initialize QOS
            pQos  = new PublisherQos();
            dwQos = new DataWriterQos();

            fdmDataType = new FDMTypeSupport();
            string     FDMDATATypeName = fdmDataType.TypeName;
            ReturnCode status          = fdmDataType.RegisterType(_dp, FDMDATATypeName);

            ErrorHandler.checkStatus(status, "FDMDATA: Cannot Register Type");


            //Create FDMDATA Topic
            fdmDataTopic = _dp.FindTopic("FDMDATA", Duration.FromMilliseconds(1000));
            if (fdmDataTopic == null)
            {
                fdmDataTopic = _dp.CreateTopic("FDMDATA", FDMDATATypeName);
            }
            ErrorHandler.checkHandle(fdmDataTopic, "Cannot Create Topic FDMDATA");

            //Get Publisher QOS and Set Partition Name
            _dp.GetDefaultPublisherQos(ref pQos);
            pQos.Partition.Name    = new String[1];
            pQos.Partition.Name[0] = PartitionName;

            //Create Subscriber for FDMDATA Topic
            Publisher = _dp.CreatePublisher(pQos);
            ErrorHandler.checkHandle(Publisher, "Cannot Create FDMDATA Publisher");

            //Get Data Writer QOS and Set History Depth
            Publisher.GetDefaultDataWriterQos(ref dwQos);
            ErrorHandler.checkHandle(dwQos, "Cannot get Data Writer Qos");
            dwQos.History.Depth    = 5;
            dwQos.Reliability.Kind = ReliabilityQosPolicyKind.BestEffortReliabilityQos;


            //Create DataReader for FDMDATA Topic
            parentWriter = Publisher.CreateDataWriter(fdmDataTopic, dwQos);
            ErrorHandler.checkHandle(parentWriter, "Cannot Create FDMDATA Data Writer");

            //Narrow abstract parentWriter into its typed representative
            fdmDataWriter = parentWriter as FDMDataWriter;
            ErrorHandler.checkHandle(fdmDataWriter, "Cannot Narrow FDMDATA Data Writer");

            fdmData = new FDM();
            while (true)
            {
                StartPublish();
                Console.WriteLine("Publishing data! ");
                Thread.Sleep(10);
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            _dpf = DomainParticipantFactory.Instance;
            ErrorHandler.checkHandle(_dpf, "Domain Participant Factory");

            _dp = _dpf.CreateParticipant(Domain);

            //Initialize QOS
            sQos  = new SubscriberQos();
            drQos = new DataReaderQos();

            fdmDataType = new FDMTypeSupport();
            string     FDMDATATypeName = fdmDataType.TypeName;
            ReturnCode status          = fdmDataType.RegisterType(_dp, FDMDATATypeName);

            ErrorHandler.checkStatus(status, "FDMDATA: Cannot Register Type");

            //Create FDMDATA Topic
            fdmDataTopic = _dp.FindTopic("FDMDATA", Duration.FromMilliseconds(1000));
            if (fdmDataTopic == null)
            {
                fdmDataTopic = _dp.CreateTopic("FDMDATA", FDMDATATypeName);
            }
            ErrorHandler.checkHandle(fdmDataTopic, "Cannot Create Topic FDMDATA");

            //Get Subscriber QOS and Set Partition Name
            _dp.GetDefaultSubscriberQos(ref sQos);
            sQos.Partition.Name    = new String[1];
            sQos.Partition.Name[0] = PartitionName;

            //Create Subscriber for FDMDATA Topic
            Subscriber = _dp.CreateSubscriber(sQos);
            ErrorHandler.checkHandle(Subscriber, "Cannot Create FDMDATA Subscriber");

            //Get Data Reader QOS and Set History Depth
            Subscriber.GetDefaultDataReaderQos(ref drQos);
            ErrorHandler.checkHandle(drQos, "Cannot get Data Reader Qos");
            drQos.History.Depth    = 5;
            drQos.Reliability.Kind = ReliabilityQosPolicyKind.BestEffortReliabilityQos;

            //Create DataReader for FDMDATA Topic
            parentReader = Subscriber.CreateDataReader(fdmDataTopic, drQos);
            ErrorHandler.checkHandle(parentReader, "Cannot Create FDMDATA Data Reader");

            //Narrow abstract parentReader into its typed representative
            fdmDataReader = parentReader as FDMDataReader;
            ErrorHandler.checkHandle(fdmDataReader, "Cannot Narrow FDMDATA Data Reader");
            // drQos.Durability.Kind = DurabilityQosPolicyKind.TransientLocalDurabilityQos;

            fdmData = new FDM();
            //Rececieve Loop
            while (true)
            {
                StartReceive();

                Console.WriteLine("abc: " + fdmData.aa.ToString());
            }
        }
Example #25
0
        private async Task HandleAsync(SchedulerBatch <T> document)
        {
            if (document.RetryCount > schedulerOptions.ExecutionRetries.Length)
            {
                await schedulerStore.CompleteAsync(document.Id);

                return;
            }

            var canRetry = document.RetryCount < schedulerOptions.ExecutionRetries.Length;

            try
            {
                var isConfirmed = true;

                if (Debugger.IsAttached)
                {
                    isConfirmed = await onSuccess(document.Jobs, !canRetry, default);
                }
                else
                {
                    using (var timeout = new CancellationTokenSource(schedulerOptions.Timeout))
                    {
                        isConfirmed = await onSuccess(document.Jobs, !canRetry, timeout.Token);
                    }
                }

                if (isConfirmed)
                {
                    await schedulerStore.CompleteAsync(document.Id);
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Failed to handle job.");

                if (canRetry)
                {
                    var wait = Duration.FromMilliseconds(schedulerOptions.ExecutionRetries[document.RetryCount]);

                    var nextTime = document.DueTime.Plus(wait);

                    await schedulerStore.RetryAsync(document.Id, nextTime);
                }
                else
                {
                    try
                    {
                        await onError(document.Jobs, ex, default);
                    }
                    catch (Exception ex2)
                    {
                        log.LogError(ex2, "Failed to handle job.");
                    }
                }
            }
        }
        public void GenerateCodeLiteral_returns_duration_literal()
        {
            Assert.Equal("NodaTime.Duration.FromHours(5)", CodeLiteral(Duration.FromHours(5)));

            Assert.Equal("NodaTime.Duration.FromDays(4) + NodaTime.Duration.FromHours(5) + NodaTime.Duration.FromMinutes(6L) + " +
                         "NodaTime.Duration.FromSeconds(7L) + NodaTime.Duration.FromMilliseconds(8L)",
                         CodeLiteral(Duration.FromDays(4) + Duration.FromHours(5) + Duration.FromMinutes(6) + Duration.FromSeconds(7) +
                                     Duration.FromMilliseconds(8)));
        }
Example #27
0
        /// <summary>
        /// Returns the next time interval with a ceiling based on the given duration.
        /// </summary>
        /// <param name="time">The time.</param>
        /// <param name="duration">The duration ceiling.</param>
        /// <returns>The <see cref="ZonedDateTime"/> plus the rounded duration ceiling.</returns>
        public static ZonedDateTime Ceiling(this ZonedDateTime time, Duration duration)
        {
            Debug.NotDefault(time, nameof(time));
            Debug.NotDefault(duration, nameof(duration));

            var offset = CeilingOffsetMilliseconds(time, duration);

            return(time + Duration.FromMilliseconds(offset));
        }
 private static Duration CreateDuration(double days, double hours, double minutes, double seconds, double milliseconds = 0d, double ticks = 0d)
 {
     return(Duration.FromDays(days)
            + Duration.FromHours(hours)
            + Duration.FromMinutes(minutes)
            + Duration.FromSeconds(seconds)
            + Duration.FromMilliseconds(milliseconds)
            + Duration.FromTicks(ticks));
 }
Example #29
0
 static void AppendSpecial(Timestamp t, List <VTTQ> list)
 {
     list.Add(VTTQ.Make(DataValue.FromString(""), t + Duration.FromSeconds(10), t, Quality.Good));
     list.Add(VTTQ.Make(DataValue.FromString("A"), t + Duration.FromSeconds(11), t, Quality.Good));
     list.Add(VTTQ.Make(DataValue.FromString("Ä"), t + Duration.FromSeconds(18), t, Quality.Good));
     list.Add(VTTQ.Make(DataValue.FromString("AB"), t + Duration.FromSeconds(19), t, Quality.Good));
     list.Add(VTTQ.Make(DataValue.FromString("ÖÜÄ"), t + Duration.FromSeconds(30), t, Quality.Good));
     list.Add(VTTQ.Make(DataValue.FromString(new string('P', 255)), t + Duration.FromSeconds(34), t, Quality.Good));
     list.Add(VTTQ.Make(DataValue.FromString(new string('a', 500)), t + Duration.FromSeconds(38), t, Quality.Good));
     list.Add(VTTQ.Make(DataValue.FromString(new string('ä', 9000)), t + Duration.FromMilliseconds(55005), t, Quality.Good));
     list.Add(VTTQ.Make(DataValue.Empty, t + Duration.FromSeconds(30), t, Quality.Good));
 }
Example #30
0
        public void Deserialize()
        {
            string json = "{\"Start\":\"2012-01-02T03:04:05.67Z\",\"End\":\"2013-06-07T08:09:10.1234567Z\"}";

            var interval = JsonConvert.DeserializeObject <Interval>(json, settings);

            var startInstant     = Instant.FromUtc(2012, 1, 2, 3, 4, 5) + Duration.FromMilliseconds(670);
            var endInstant       = Instant.FromUtc(2013, 6, 7, 8, 9, 10) + Duration.FromTicks(1234567);
            var expectedInterval = new Interval(startInstant, endInstant);

            Assert.AreEqual(expectedInterval, interval);
        }