public void TestParseDateTime1()
 {
     DateTimeParser parser = new DateTimeParser("yyyy-MM-dd");
     string dateTimeString = "1996-04-01";
     DateTime actual = parser.ParseDateTime(dateTimeString);
     DateTime expected = new DateTime(1996, 4, 1);
     Assert.AreEqual(actual, expected);
 }
Example #2
0
 private static void RunDateTimeParserDemo()
 {
     // Create and use datetime parser using specified datetime formats
     string format = "yyyy-MM-dd";
     DateTimeParser parser = new DateTimeParser(format);
     DateTime result = parser.ParseDateTime("1996-04-01");
     DateTime result2 = parser.ParseDateTime("2011-12-28");
 }
Example #3
0
        private void AssertParse(string text, long?expectedNumRepeats, string expectedDate, TimePeriod expectedTimePeriod)
        {
            TimerScheduleSpec spec = TimerScheduleISO8601Parser.Parse(text);

            Assert.AreEqual(expectedNumRepeats, (object)spec.OptionalRepeatCount);
            if (expectedTimePeriod == null)
            {
                Assert.IsNull(spec.OptionalTimePeriod);
            }
            else
            {
                Assert.AreEqual(expectedTimePeriod, spec.OptionalTimePeriod,
                                string.Format("expected '{0}' got '{1}'", expectedTimePeriod.ToStringISO8601(), spec.OptionalTimePeriod.ToStringISO8601()));
            }
            if (expectedDate == null)
            {
                Assert.IsNull(spec.OptionalDate);
            }
            else
            {
                Assert.AreEqual(DateTimeParser.ParseDefaultMSecWZone(expectedDate), spec.OptionalDate.TimeInMillis);
            }
        }
Example #4
0
        public void TestDateTimeParser()
        {
            if (TestUtils.EvaluateSpec(TestSpec, out string message))
            {
                Assert.Inconclusive(message, GetMessage(TestSpec));
            }

            if (Debugger.IsAttached && TestSpec.Debug)
            {
                Debugger.Break();
            }

            var referenceDateTime = TestSpec.GetReferenceDateTime();

            var extractResults = Extractor.Extract(TestSpec.Input, referenceDateTime);
            var actualResults  = extractResults.Select(o => DateTimeParser.Parse(o, referenceDateTime)).ToArray();

            var expectedResults = TestSpec.CastResults <DateTimeParseResult>();

            Assert.AreEqual(expectedResults.Count(), actualResults.Count(), GetMessage(TestSpec));

            foreach (var tuple in Enumerable.Zip(expectedResults, actualResults, Tuple.Create))
            {
                var expected = tuple.Item1;
                var actual   = tuple.Item2;
                Assert.AreEqual(expected.Type, actual.Type, GetMessage(TestSpec));
                Assert.AreEqual(expected.Text, actual.Text, GetMessage(TestSpec));

                var actualValue   = actual.Value as DateTimeResolutionResult;
                var expectedValue = JsonConvert.DeserializeObject <DateTimeResolutionResult>(expected.Value.ToString());

                Assert.IsNotNull(actualValue, GetMessage(TestSpec));
                Assert.AreEqual(expectedValue.Timex, actualValue.Timex, GetMessage(TestSpec));
                CollectionAssert.AreEqual(expectedValue.FutureResolution, actualValue.FutureResolution, GetMessage(TestSpec));
                CollectionAssert.AreEqual(expectedValue.PastResolution, actualValue.PastResolution, GetMessage(TestSpec));
            }
        }
Example #5
0
        public async Task <int> Create(CreateShareClassInputModel model)
        {
            ShareClassPostDto        dto           = AutoMapperConfig.MapperInstance.Map <ShareClassPostDto>(model);
            ShareClassForeignKeysDto dtoForeignKey = AutoMapperConfig.MapperInstance.Map <ShareClassForeignKeysDto>(model);

            dto.EndDate     = DateTimeParser.ToSqlFormat(model.EndDate);
            dto.ContainerId = await this.repositoryContainer.All()
                              .Where(f => f.SfOfficialSubFundName == model.SubFundContainer)
                              .Select(fc => fc.SfId)
                              .FirstOrDefaultAsync();

            await this.SetForeignKeys(dto, dtoForeignKey);

            SqlCommand command = this.AssignBaseParameters(dto, SqlProcedureDictionary.CreateShareClass);

            // Assign particular parameters
            command.Parameters.AddRange(new[]
            {
                new SqlParameter("@subfundcontainer", SqlDbType.Int)
                {
                    Value = dto.ContainerId
                },
                new SqlParameter("@sc_endDate", SqlDbType.NVarChar)
                {
                    Value = dto.EndDate
                },
            });

            await this.sqlManager.ExecuteProcedure(command);

            var subFundId = this.repository.All()
                            .Where(sf => sf.ScOfficialShareClassName == dto.ShareClassName)
                            .Select(sf => sf.ScId)
                            .FirstOrDefault();

            return(subFundId);
        }
        public override void Run(EPServiceProvider epService)
        {
            epService.EPAdministrator.Configuration.AddEventType(typeof(MySimpleScheduleEvent));
            epService.EPAdministrator.Configuration.AddEventType <SupportBean_S0>();

            epService.EPRuntime.SendEvent(new CurrentTimeEvent(DateTimeParser.ParseDefaultMSec("2002-05-01T09:00:00.000")));
            epService.EPAdministrator.CreateEPL("create context MyCtx start MySimpleScheduleEvent as sse");
            EPStatement stmt = epService.EPAdministrator.CreateEPL("context MyCtx\n" +
                                                                   "select count(*) as c \n" +
                                                                   "from SupportBean_S0\n" +
                                                                   "output last At(context.sse.atminute, context.sse.athour, *, *, *, *) and when terminated\n");
            var listener = new SupportUpdateListener();

            stmt.Events += listener.Update;

            epService.EPRuntime.SendEvent(new MySimpleScheduleEvent(10, 15));
            epService.EPRuntime.SendEvent(new SupportBean_S0(0));

            epService.EPRuntime.SendEvent(new CurrentTimeEvent(DateTimeParser.ParseDefaultMSec("2002-05-01T10:14:59.000")));
            Assert.IsFalse(listener.GetAndClearIsInvoked());

            epService.EPRuntime.SendEvent(new CurrentTimeEvent(DateTimeParser.ParseDefaultMSec("2002-05-01T10:15:00.000")));
            Assert.IsTrue(listener.GetAndClearIsInvoked());
        }
Example #7
0
        public void TestDateTimeParser()
        {
            TestPreValidation();

            var referenceDateTime = TestSpec.GetReferenceDateTime();

            var extractResults = Extractor.Extract(TestSpec.Input, referenceDateTime);
            var actualResults  = extractResults.Select(o => DateTimeParser.Parse(o, referenceDateTime)).ToArray();

            var expectedResults = TestSpec.CastResults <DateTimeParseResult>();

            Assert.AreEqual(expectedResults.Count(), actualResults.Count(), GetMessage(TestSpec));

            foreach (var tuple in Enumerable.Zip(expectedResults, actualResults, Tuple.Create))
            {
                var expected = tuple.Item1;
                var actual   = tuple.Item2;
                Assert.AreEqual(expected.Type, actual.Type, GetMessage(TestSpec));
                Assert.AreEqual(expected.Text, actual.Text, GetMessage(TestSpec));

                var actualValue   = actual.Value as DateTimeResolutionResult;
                var expectedValue = JsonConvert.DeserializeObject <DateTimeResolutionResult>(expected.Value.ToString());

                Assert.IsNotNull(actualValue, GetMessage(TestSpec));
                Assert.AreEqual(expectedValue.Timex, actualValue.Timex, GetMessage(TestSpec));
                CollectionAssert.AreEqual(expectedValue.FutureResolution, actualValue.FutureResolution, GetMessage(TestSpec));
                CollectionAssert.AreEqual(expectedValue.PastResolution, actualValue.PastResolution, GetMessage(TestSpec));

                if (expectedValue.TimeZoneResolution != null)
                {
                    Assert.IsNotNull(actualValue.TimeZoneResolution, GetMessage(TestSpec));
                    Assert.AreEqual(expectedValue.TimeZoneResolution.Value, actualValue.TimeZoneResolution.Value, GetMessage(TestSpec));
                    Assert.AreEqual(expectedValue.TimeZoneResolution.UtcOffsetMins, actualValue.TimeZoneResolution.UtcOffsetMins, GetMessage(TestSpec));
                }
            }
        }
        public void ImportFile(string path)
        {
            path = path.Replace("\"", "");
            var results = _ImportWorkingHourUseCase.Import(path);

            UserConfigurationManager.Instance.SetConfiguration(new ImportParamConfig {
                Param = path
            });

            if (results.Any())
            {
                var min = results.Min(r => r.Ymd.Value);
                var max = results.Max(r => r.Ymd.Value);

                var minDate = DateTimeParser.ConvertFromYmd(min)?.ToString("yyyy/MM/dd") ?? "";
                var maxDate = DateTimeParser.ConvertFromYmd(max)?.ToString("yyyy/MM/dd") ?? "";

                SnackbarService.Current.ShowMessage($"{results.Length}件 ({minDate} ~ {maxDate}) の勤務時間情報を取り込みました");
            }
            else
            {
                SnackbarService.Current.ShowMessage($"取込対象の勤務時間情報はありません");
            }
        }
Example #9
0
        private void RunAssertionPlusMinusTimePeriod(EPServiceProvider epService)
        {
            string startTime = "2002-05-30T09:00:00.000";

            epService.EPRuntime.SendEvent(new CurrentTimeEvent(DateTimeParser.ParseDefaultMSec(startTime)));

            string[] fields      = "val0,val1,val2,val3,val4,val5".Split(',');
            string   eplFragment = "select " +
                                   "current_timestamp.Plus(1 hour 10 sec 20 msec) as val0," +
                                   "utildate.Plus(1 hour 10 sec 20 msec) as val1," +
                                   "longdate.Plus(1 hour 10 sec 20 msec) as val2," +
                                   "current_timestamp.Minus(1 hour 10 sec 20 msec) as val3," +
                                   "utildate.Minus(1 hour 10 sec 20 msec) as val4," +
                                   "longdate.Minus(1 hour 10 sec 20 msec) as val5" +
                                   " from SupportDateTime";
            EPStatement stmtFragment = epService.EPAdministrator.CreateEPL(eplFragment);
            var         listener     = new SupportUpdateListener();

            stmtFragment.Events += listener.Update;
            LambdaAssertionUtil.AssertTypes(stmtFragment.EventType, fields, new Type[] {
                typeof(long?), typeof(DateTimeOffset?), typeof(long?),
                typeof(long?), typeof(DateTimeOffset?), typeof(long?)
            });

            epService.EPRuntime.SendEvent(SupportDateTime.Make(startTime));
            object[] expectedPlus  = SupportDateTime.GetArrayCoerced("2002-05-30T010:00:10.020", "long", "util", "long");
            object[] expectedMinus = SupportDateTime.GetArrayCoerced("2002-05-30T07:59:49.980", "long", "util", "long");
            EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), fields, EPAssertionUtil.ConcatenateArray(expectedPlus, expectedMinus));

            epService.EPRuntime.SendEvent(SupportDateTime.Make(null));
            expectedPlus  = SupportDateTime.GetArrayCoerced("2002-05-30T010:00:10.020", "long", "null", "null");
            expectedMinus = SupportDateTime.GetArrayCoerced("2002-05-30T07:59:49.980", "long", "null", "null");
            EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), fields, EPAssertionUtil.ConcatenateArray(expectedPlus, expectedMinus));

            stmtFragment.Dispose();
        }
Example #10
0
        public void TestDateTimeMergedParser()
        {
            TestPreValidation();

            var referenceDateTime = TestSpec.GetReferenceDateTime();

            var extractResults = Extractor.Extract(TestSpec.Input, referenceDateTime);
            var actualResults  = extractResults.Select(o => DateTimeParser.Parse(o, referenceDateTime)).ToArray();

            var expectedResults = TestSpec.CastResults <DateTimeParseResult>();

            Assert.AreEqual(expectedResults.Count(), actualResults.Count(), GetMessage(TestSpec));

            foreach (var tuple in Enumerable.Zip(expectedResults, actualResults, Tuple.Create))
            {
                var expected = tuple.Item1;
                var actual   = tuple.Item2;

                Assert.AreEqual(expected.Text, actual.Text, GetMessage(TestSpec));
                Assert.AreEqual(expected.Type, actual.Type, GetMessage(TestSpec));

                var values = actual.Value as IDictionary <string, object>;
                if (values != null)
                {
                    var actualValues = values[ResolutionKey.ValueSet] as IList <Dictionary <string, string> >;

                    var expectedObj    = JsonConvert.DeserializeObject <IDictionary <string, IList <Dictionary <string, string> > > >(expected.Value.ToString());
                    var expectedValues = expectedObj[ResolutionKey.ValueSet];

                    foreach (var results in Enumerable.Zip(expectedValues, actualValues, Tuple.Create))
                    {
                        CollectionAssert.AreEqual(results.Item1, results.Item2, GetMessage(TestSpec));
                    }
                }
            }
        }
        private ProcessDuplicateResult ProcessDuplicateReport(DicomFile dupFile, DicomFile baseFile, WorkQueueUid uid, StudyXml studyXml)
        {
            var result = new ProcessDuplicateResult();

            DateTime?dupTime = DateTimeParser.ParseDateAndTime(dupFile.DataSet, 0, DicomTags.InstanceCreationDate,
                                                               DicomTags.InstanceCreationTime);

            DateTime?baseTime = DateTimeParser.ParseDateAndTime(baseFile.DataSet, 0, DicomTags.InstanceCreationDate,
                                                                DicomTags.InstanceCreationTime);

            if (dupTime.HasValue && baseTime.HasValue)
            {
                if (dupTime.Value <= baseTime.Value)
                {
                    RemoveWorkQueueUid(uid, dupFile.Filename);
                    result.ActionTaken = DuplicateProcessResultAction.Delete;
                    return(result);
                }
            }

            result.ActionTaken = DuplicateProcessResultAction.Accept;
            SaveDuplicateReport(uid, dupFile.Filename, baseFile.Filename, dupFile, studyXml);
            return(result);
        }
        internal DateTimeOffset DateFromString(string dateTimeString, XmlReader reader)
        {
            try
            {
                DateTimeOffset dateTimeOffset       = default;
                var            elementQualifiedName = new XmlQualifiedName(reader.LocalName, reader.NamespaceURI);
                var            xmlDateTimeData      = new XmlDateTimeData(dateTimeString, elementQualifiedName);
                object[]       args = new object[] { xmlDateTimeData, dateTimeOffset };
                foreach (Delegate dateTimeParser in DateTimeParser.GetInvocationList())
                {
                    if ((bool)dateTimeParser.Method.Invoke(dateTimeParser.Target, args))
                    {
                        dateTimeOffset = (DateTimeOffset)args[args.Length - 1];
                        return(dateTimeOffset);
                    }
                }
            }
            catch (Exception e)
            {
                throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDateTime), e);
            }

            throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDateTime));
        }
Example #13
0
        public CalendarMap()
        {
            Map(e => e.ServiceId).Name("service_id");
            Map(e => e.Monday).Name("monday");
            Map(e => e.Tuesday).Name("tuesday");
            Map(e => e.Wednesday).Name("wednesday");
            Map(e => e.Thursday).Name("thursday");
            Map(e => e.Friday).Name("friday");
            Map(e => e.Saturday).Name("saturday");
            Map(e => e.Sunday).Name("sunday");

            DateTimeParser dateTimeParser = new DateTimeParser();

            Map(e => e.StartDate).Name("start_date").ConvertUsing(row =>
            {
                string dateTimeText = row.GetField <string>("start_date");
                return(dateTimeParser.Parse(dateTimeText));
            });
            Map(e => e.EndDate).Name("end_date").ConvertUsing(row =>
            {
                string dateTimeText = row.GetField <string>("end_date");
                return(dateTimeParser.Parse(dateTimeText));
            });
        }
Example #14
0
        public void TestFormat()
        {
            String startTime = "2002-05-30 9:00:00.000";

            _epService.EPRuntime.SendEvent(new CurrentTimeEvent(DateTimeParser.ParseDefaultMSec(startTime)));

            String[] fields      = "val0,val1,val2".Split(',');
            String   eplFragment = "select " +
                                   "current_timestamp.Format() as val0," +
                                   "utildate.Format() as val1," +
                                   "msecdate.Format() as val2" +
                                   " from SupportDateTime";
            EPStatement stmtFragment = _epService.EPAdministrator.CreateEPL(eplFragment);

            stmtFragment.Events += _listener.Update;
            LambdaAssertionUtil.AssertTypes(stmtFragment.EventType, fields, new Type[] { typeof(string), typeof(string), typeof(string) });

            _epService.EPRuntime.SendEvent(SupportDateTime.Make(startTime));
            Object[] expected = SupportDateTime.GetArrayCoerced(startTime, "sdf", "sdf", "sdf");
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, expected);

            _epService.EPRuntime.SendEvent(SupportDateTime.Make(null));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new Object[] { SupportDateTime.GetValueCoerced(startTime, "sdf"), null, null });
        }
Example #15
0
            public static MyEvent MakeTime(String id, String mytime)
            {
                long msec = DateTimeParser.ParseDefaultMSec("2002-05-1T" + mytime);

                return(new MyEvent(id, msec));
            }
 private void SendTimeEvent(String time)
 {
     _epService.EPRuntime.SendEvent(new CurrentTimeEvent(DateTimeParser.ParseDefaultMSec(time)));
 }
        public GeneralImageAnnotationItemProvider()
            : base("AnnotationItemProviders.Dicom.GeneralImage", new AnnotationResourceResolver(typeof(GeneralImageAnnotationItemProvider).Assembly))
        {
            _annotationItems = new List <IAnnotationItem>();

            AnnotationResourceResolver resolver = new AnnotationResourceResolver(this);

            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.AcquisitionDate",
                    resolver,
                    delegate(Frame frame) { return(frame.AcquisitionDate); },
                    DicomDataFormatHelper.DateFormat
                )
            );


            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.AcquisitionTime",
                    resolver,
                    delegate(Frame frame) { return(frame.AcquisitionTime); },
                    delegate(string input)
            {
                if (String.IsNullOrEmpty(input))
                {
                    return(String.Empty);
                }

                DateTime time;
                if (!TimeParser.Parse(input, out time))
                {
                    return(input);
                }

                return(time.ToString("HH:mm:ss.FFFFFF"));
            }
                )
            );


            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.AcquisitionDateTime",
                    resolver,
                    delegate(Frame frame) { return(frame.AcquisitionDateTime); },
                    delegate(string input)
            {
                if (String.IsNullOrEmpty(input))
                {
                    return(String.Empty);
                }

                DateTime dateTime;
                if (!DateTimeParser.Parse(input, out dateTime))
                {
                    return(input);
                }

                return(String.Format("{0} {1}",
                                     dateTime.Date.ToString(Format.DateFormat),
                                     dateTime.ToString("HH:mm:ss.FFFFFF")));
            }
                )
            );

            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.AcquisitionNumber",
                    resolver,
                    delegate(Frame frame) { return(frame.AcquisitionNumber.ToString()); },
                    DicomDataFormatHelper.RawStringFormat
                )
            );

            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.ContentDate",
                    resolver,
                    FrameDataRetrieverFactory.GetStringRetriever(DicomTags.ContentDate),
                    DicomDataFormatHelper.DateFormat
                )
            );

            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.ContentTime",
                    resolver,
                    FrameDataRetrieverFactory.GetStringRetriever(DicomTags.ContentTime),
                    DicomDataFormatHelper.TimeFormat
                )
            );

            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.DerivationDescription",
                    resolver,
                    FrameDataRetrieverFactory.GetStringRetriever(DicomTags.DerivationDescription),
                    DicomDataFormatHelper.RawStringFormat
                )
            );

            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.ImageComments",
                    resolver,
                    delegate(Frame frame) { return(frame.ImageComments); },
                    DicomDataFormatHelper.RawStringFormat
                )
            );

            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.ImagesInAcquisition",
                    resolver,
                    delegate(Frame frame) { return(frame.ImagesInAcquisition.ToString()); },
                    DicomDataFormatHelper.RawStringFormat
                )
            );

            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.ImageType",
                    resolver,
                    delegate(Frame frame) { return(frame.ImageType); },
                    DicomDataFormatHelper.RawStringFormat
                )
            );

            _annotationItems.Add(new InstanceNumberAnnotationItem());

            _annotationItems.Add
            (
                new LossyImagePresentationAnnotationItem
                (
                    "Dicom.GeneralImage.LossyImageCompression",
                    resolver
                )
            );

            _annotationItems.Add
            (
                new DicomAnnotationItem <string>
                (
                    "Dicom.GeneralImage.QualityControlImage",
                    resolver,
                    FrameDataRetrieverFactory.GetStringRetriever(DicomTags.QualityControlImage),
                    DicomDataFormatHelper.BooleanFormatter
                )
            );

            _annotationItems.Add
            (
                new LateralityViewPositionAnnotationItem
                (
                    "Dicom.GeneralImage.ViewPosition",
                    false, true
                )
            );

            _annotationItems.Add
            (
                new LateralityViewPositionAnnotationItem
                (
                    "Dicom.GeneralImage.ImageLaterality",
                    true, false
                )
            );

            _annotationItems.Add
            (
                new LateralityViewPositionAnnotationItem
                (
                    "Dicom.GeneralImage.Composite.LateralityViewPosition",
                    true, true
                )
            );
        }
Example #18
0
        public void TestIncludeEndpoints()
        {
            String startTime = "2002-05-30 09:00:00.000";

            _epService.EPRuntime.SendEvent(new CurrentTimeEvent(DateTimeParser.ParseDefaultMSec(startTime)));

            String[] fieldsCurrentTs = "val0,val1,val2,val3,val4,val5,val6".Split(',');
            String   eplCurrentTS    = "select " +
                                       "current_timestamp.After(msecdateStart) as val0, " +
                                       "current_timestamp.Between(msecdateStart, msecdateEnd) as val1, " +
                                       "current_timestamp.Between(utildateStart, caldateEnd) as val2, " +
                                       "current_timestamp.Between(caldateStart, utildateEnd) as val3, " +
                                       "current_timestamp.Between(utildateStart, utildateEnd) as val4, " +
                                       "current_timestamp.Between(caldateStart, caldateEnd) as val5, " +
                                       "current_timestamp.Between(caldateEnd, caldateStart) as val6 " +
                                       "from SupportTimeStartEndA";
            EPStatement stmtCurrentTs = _epService.EPAdministrator.CreateEPL(eplCurrentTS);

            stmtCurrentTs.Events += _listener.Update;
            LambdaAssertionUtil.AssertTypesAllSame(stmtCurrentTs.EventType, fieldsCurrentTs, typeof(bool?));

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E1", "2002-05-30 08:59:59.999", 0));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fieldsCurrentTs, new Object[] { true, false, false, false, false, false, false });

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E1", "2002-05-30 08:59:59.999", 1));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fieldsCurrentTs, new Object[] { true, true, true, true, true, true, true });

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E1", "2002-05-30 08:59:59.999", 100));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fieldsCurrentTs, new Object[] { true, true, true, true, true, true, true });

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E1", "2002-05-30 09:00:00.000", 0));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fieldsCurrentTs, new Object[] { false, true, true, true, true, true, true });

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E1", "2002-05-30 09:00:00.000", 100));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fieldsCurrentTs, new Object[] { false, true, true, true, true, true, true });

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E1", "2002-05-30 09:00:00.001", 100));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fieldsCurrentTs, new Object[] { false, false, false, false, false, false, false });
            stmtCurrentTs.Dispose();

            // test calendar field and constants
            _epService.EPAdministrator.Configuration.AddImport(typeof(DateTimeParser));
            String[] fieldsConstants = "val0,val1,val2,val3".Split(',');
            String   eplConstants    = "select " +
                                       "msecdateStart.between(DateTimeParser.ParseDefault('2002-05-30 09:00:00.000'), DateTimeParser.ParseDefault('2002-05-30 09:01:00.000')) as val0, " +
                                       "utildateStart.between(DateTimeParser.ParseDefault('2002-05-30 09:00:00.000'), DateTimeParser.ParseDefault('2002-05-30 09:01:00.000')) as val1, " +
                                       "caldateStart.between(DateTimeParser.ParseDefault('2002-05-30 09:00:00.000'), DateTimeParser.ParseDefault('2002-05-30 09:01:00.000')) as val2, " +
                                       "msecdateStart.between(DateTimeParser.ParseDefault('2002-05-30 09:01:00.000'), DateTimeParser.ParseDefault('2002-05-30 09:00:00.000')) as val3 " +
                                       "from SupportTimeStartEndA";
            EPStatement stmtConstants = _epService.EPAdministrator.CreateEPL(eplConstants);

            stmtConstants.Events += _listener.Update;
            LambdaAssertionUtil.AssertTypesAllSame(stmtConstants.EventType, fieldsConstants, typeof(bool?));

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E1", "2002-05-30 8:59:59.999", 0));
            EPAssertionUtil.AssertPropsAllValuesSame(_listener.AssertOneGetNewAndReset(), fieldsConstants, false);

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E2", "2002-05-30 9:00:00.000", 0));
            EPAssertionUtil.AssertPropsAllValuesSame(_listener.AssertOneGetNewAndReset(), fieldsConstants, true);

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E2", "2002-05-30 9:00:05.000", 0));
            EPAssertionUtil.AssertPropsAllValuesSame(_listener.AssertOneGetNewAndReset(), fieldsConstants, true);

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E2", "2002-05-30 9:00:59.999", 0));
            EPAssertionUtil.AssertPropsAllValuesSame(_listener.AssertOneGetNewAndReset(), fieldsConstants, true);

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E2", "2002-05-30 9:01:00.000", 0));
            EPAssertionUtil.AssertPropsAllValuesSame(_listener.AssertOneGetNewAndReset(), fieldsConstants, true);

            _epService.EPRuntime.SendEvent(SupportTimeStartEndA.Make("E2", "2002-05-30 9:01:00.001", 0));
            EPAssertionUtil.AssertPropsAllValuesSame(_listener.AssertOneGetNewAndReset(), fieldsConstants, false);

            stmtConstants.Dispose();
        }
        private DateTime ConvertDateTime(string dateTimeForParsing)
        {
            DateTimeParser dateParser = new DateTimeParser();

            return(dateParser.ConvertStringToDateTime(dateTimeForParsing));
        }
Example #20
0
 public void TestParseDatetimeWithTimezone()
 {
     Assert.AreEqual(DateTime.Parse("2008-10-25 03:09:06 +8"), DateTimeParser.Parse("24-oct-08 21:09:06 CEST"));
     Assert.AreEqual(DateTime.Parse("2012-04-20 16:10:00 +8"), DateTimeParser.Parse("2012 -04-20 10:10:00+0200"));
     Assert.AreEqual(DateTime.Parse("2014-12-12 12:13:30 +8"), DateTimeParser.Parse("Fri, 12 Dec 2014 12:13:30 +0800 (CST)"));
 }
Example #21
0
        public static Object GetValueCoerced(string expectedTime, string format)
        {
            long msec = DateTimeParser.ParseDefaultMSec(expectedTime);

            return(Coerce(msec, format));
        }
Example #22
0
 public void TestParseDatetimeWithTimezone()
 {
     Assert.AreEqual(new DateTime(2008, 10, 25, 3, 9, 6), DateTimeParser.Parse("24-oct-08 21:09:06 CEST"));
     Assert.AreEqual(new DateTime(2012, 4, 20, 16, 10, 0), DateTimeParser.Parse("2012-04-20 10:10:00+0200"));
     Assert.AreEqual(new DateTime(2014, 12, 12, 12, 13, 30), DateTimeParser.Parse("Fri, 12 Dec 2014 12:13:30 +0800 (CST)"));
 }
Example #23
0
 private void SendCurrentTime(EPServiceProvider epService, string time)
 {
     epService.EPRuntime.SendEvent(new CurrentTimeEvent(DateTimeParser.ParseDefaultMSec(time)));
 }
Example #24
0
        /// <summary>
        /// 日期节点Pattern的评估函数(考虑时差和数量,可以理解为0-1之间的可能性数值,越大越好)
        /// </summary>
        /// <param name="Nodes"></param>
        /// <param name="Pattern"></param>
        /// <param name="Strategy"></param>
        /// <param name="BaseItemCount"></param>
        /// <returns></returns>
        internal static double DateNodeRelPatternScore(IEnumerable <HtmlNode> Nodes, ListStrategy Strategy, int BaseItemCount, int PathLevel, bool PathUsingName)
        {
            //直接用DateTimeParser.Parser了,所以不用考察字符密度了
            double SumDiff    = 0;
            int    ParseCount = 0;

            //所有日期和Now的差距综合
            foreach (HtmlNode Node in Nodes)
            {
                string Text = TextCleaner.FullClean(XPathUtility.InnerTextNonDescendants(Node), true, true, true);
                if (Text.Length > Strategy.MaxLenDate)
                {
                    continue;
                }

                DateTime?Val = DateTimeParser.Parser(Text);
                if (Val != null)
                {
                    ParseCount++;
                    DateTime d = (DateTime)Val;

                    //根据class和id是否有特殊字样加权
                    bool   IDClassNameMatched;
                    double IDClassScore = IDClassNameScore(Node, DateClassNames_Must, DateClassNames_MustNot, out IDClassNameMatched);

                    if (d.Hour == 0 && d.Minute == 0 && d.Second == 0)
                    {
                        //只有日期,得分为距离Now的时差
                        SumDiff += Math.Abs((DateTime.Now - d).TotalDays / (IDClassNameMatched ? IDClassScore : 1));
                    }
                    else
                    {
                        //有精确时间,则只计入一半的时差
                        SumDiff += Math.Abs((DateTime.Now - d).TotalDays / 2 / (IDClassNameMatched ? IDClassScore : 1));
                    }
                }
            }

            double Possibility = 0;

            //先计算数量的可能性,在1/3-3倍之间都可以,可能性等比递减
            if (ParseCount * 3 < BaseItemCount || BaseItemCount * 3 < ParseCount)
            {
                return(0);
            }
            if (ParseCount >= BaseItemCount)
            {
                Possibility = 1 / (ParseCount / BaseItemCount); //倍数的倒数
            }
            else
            {
                Possibility = 1 / (BaseItemCount / ParseCount);
            }

            //根据平均时差来计算可能性
            double AvgDiff = SumDiff / ParseCount;

            if (AvgDiff > 180) //180以后统一为30%
            {
                Possibility *= 0.3;
            }
            else if (AvgDiff > 7) //1周以后为30%-100%,等比递减
            {
                Possibility *= (0.3 + 0.004046 * (180 - AvgDiff));
            }
            else if (AvgDiff > 1) //1周以内100%-150%
            {
                Possibility *= (1 + 0.08333 * (7 - AvgDiff));
            }
            else //1天以内的,150%-200%,便于区分原帖和评论的时间
            {
                Possibility *= (1.5 + 0.5 * (1 - AvgDiff));
            }

            //微调1:级别约小的越好,2级以上每多一个级别扣20%可能性
            if (PathLevel > 1)
            {
                Possibility *= (1 - 0.2 * (PathLevel - 1));
            }

            //微调2:用ID和class的好于用序号的,增加20%可能性
            if (PathUsingName)
            {
                Possibility *= 1.2;
            }

            return(Possibility);
        }
Example #25
0
        /// <summary>
        /// Evaluates an expression in the specified context and converts it to the specified type.
        /// </summary>
        /// <typeparam name="T">Expected returne type</typeparam>
        /// <param name="expression">The expression to be evaluated</param>
        /// <param name="context">The context to evaluate the expression</param>
        /// <returns></returns>
        /// <exception cref="TypeConversionException"> thrown if the value of the expression cannot be converted into specified type</exception>
        protected static T Evaluate <T>(Expression expression, TActionContext context)
        {
            object value = Evaluate(expression, context);

            if (value is T)
            {
                // if the expression was evaluated to the same type then just return it
                return((T)value);
            }


            if (typeof(T) == typeof(string))
            {
                return((T)(object)value.ToString());
            }
            if (typeof(T) == typeof(int))
            {
                int result = int.Parse(value.ToString(), CultureInfo.InvariantCulture);
                return((T)(object)result);
            }
            if (typeof(T) == typeof(uint))
            {
                uint result = uint.Parse(value.ToString(), CultureInfo.InvariantCulture);
                return((T)(object)result);
            }
            if (typeof(T) == typeof(long))
            {
                long result = long.Parse(value.ToString(), CultureInfo.InvariantCulture);
                return((T)(object)result);
            }
            if (typeof(T) == typeof(ulong))
            {
                ulong result = ulong.Parse(value.ToString(), CultureInfo.InvariantCulture);
                return((T)(object)result);
            }
            if (typeof(T) == typeof(float))
            {
                float result = float.Parse(value.ToString(), CultureInfo.InvariantCulture);
                return((T)(object)result);
            }
            if (typeof(T) == typeof(double))
            {
                double result = double.Parse(value.ToString(), CultureInfo.InvariantCulture);
                return((T)(object)result);
            }
            if (typeof(T) == typeof(DateTime))
            {
                if (value == null || String.IsNullOrEmpty(value.ToString()))
                {
                    throw new TypeConversionException(String.Format("Unable to convert value for expression {0} (value={1}) to {2}", expression.Text,
                                                                    value, typeof(T)));
                }

                DateTime?result = DateTimeParser.Parse(value.ToString());
                if (result == null)
                {
                    throw new TypeConversionException(String.Format("Unable to convert value for expression {0} (value={1}) to {2}", expression.Text,
                                                                    value, typeof(T)));
                }
                return((T)(object)result.Value);
            }
            throw new TypeConversionException(String.Format("Unable to retrieve value for expression {0} as {1}: Unsupported conversion.",
                                                            expression.Text, typeof(T)));
        }
Example #26
0
    public void WithinTestUnconstrained(bool expected, string valueS)
    {
        var value = valueS == null ? (DateTime?)null : DateTimeParser.Parse(valueS);

        Assert.Equal(expected, DateHelper.Within(value, DateFilter.Unconstrained));
    }
Example #27
0
    public void WithinTestNullOnly(bool expected, string valueS)
    {
        var value = valueS == null ? (DateTime?)null : DateTimeParser.Parse(valueS);

        Assert.Equal(expected, DateHelper.Within(value, DateFilter.TheNullOnly));
    }
Example #28
0
        private async void FillEntryItemFromXmlRss(FeedEntryItem entItem, XmlNode entryNode, XmlNamespaceManager NsMgr)
        {
            XmlNode entryTitle = entryNode.SelectSingleNode("title");

            entItem.Name = (entryTitle != null) ? entryTitle.InnerText : "";

            XmlNode entryId = entryNode.SelectSingleNode("guid");

            entItem.EntryId = (entryId != null) ? entryId.InnerText : "";

            XmlNode entryLinkUri = entryNode.SelectSingleNode("link");

            try
            {
                if (entryLinkUri != null)
                {
                    if (!string.IsNullOrEmpty(entryLinkUri.InnerText))
                    {
                        entItem.AltHtmlUri = new Uri(entryLinkUri.InnerText);
                    }
                }
            }
            catch (Exception e)
            {
                ToDebugWindow(">> Exception @FeedClient@FillEntryItemFromXmlRss:new Uri()"
                              + Environment.NewLine +
                              "RSS feed entry (" + entItem.Name + ") contain invalid entry Uri: " + e.Message +
                              Environment.NewLine);
            }

            if (string.IsNullOrEmpty(entItem.EntryId))
            {
                if (entItem.AltHtmlUri != null)
                {
                    entItem.EntryId = entItem.AltHtmlUri.AbsoluteUri;
                }
            }

            XmlNode entryPudDate = entryNode.SelectSingleNode("pubDate");

            if (entryPudDate != null)
            {
                string s = entryPudDate.InnerText;
                if (!string.IsNullOrEmpty(s))
                {
                    try
                    {
                        DateTimeOffset dtf = DateTimeParser.ParseDateTimeRFC822(s);

                        entItem.Published = dtf.ToUniversalTime().DateTime;
                    }
                    catch (Exception e)
                    {
                        // Debug.WriteLine("Exception @ParseDateTimeRFC822 in the RSS 2.0 feed " + "("+ entItem.Name  + ")" + " : " + e.Message);

                        ToDebugWindow(">> Exception @FeedClient@FillEntryItemFromXmlRss:ParseDateTimeRFC822()"
                                      + Environment.NewLine +
                                      "RSS feed entry(" + entItem.Name + ") contain invalid entry pubDate (DateTimeRFC822 expected): " + e.Message +
                                      Environment.NewLine);

                        // TODO: really shouldn't to cover these invalid format, but...for the usability stand point...
                        try
                        {
                            DateTime tmp;
                            if (DateTime.TryParse(s, out tmp))
                            {
                                entItem.Published = tmp.ToUniversalTime();
                            }
                        }
                        catch { }
                    }
                }
            }

            string      entryAuthor  = "";
            XmlNodeList entryAuthors = entryNode.SelectNodes("dc:creator", NsMgr);

            if (entryAuthors != null)
            {
                foreach (XmlNode auth in entryAuthors)
                {
                    if (string.IsNullOrEmpty(entryAuthor))
                    {
                        entryAuthor = auth.InnerText;
                    }
                    else
                    {
                        entryAuthor += "/" + auth.InnerText;
                    }
                }
            }

            if (string.IsNullOrEmpty(entryAuthor))
            {
                if (entItem.AltHtmlUri != null)
                {
                    entryAuthor = entItem.AltHtmlUri.Host;
                }
            }

            entItem.Author = entryAuthor;

            // gets imageUri from enclosure
            XmlNode enclosure = entryNode.SelectSingleNode("enclosure");

            if (enclosure != null)
            {
                if (enclosure.Attributes["url"] != null)
                {
                    string urlImage = enclosure.Attributes["url"].Value;

                    if (enclosure.Attributes["type"] != null)
                    {
                        string imageType = enclosure.Attributes["type"].Value;

                        if ((imageType == "image/jpg") || (imageType == "image/jpeg") || (imageType == "image/png") || (imageType == "image/gif"))
                        {
                            try
                            {
                                entItem.ImageUri = new Uri(urlImage);
                            }
                            catch (Exception e)
                            {
                                ToDebugWindow(">> Exception @FeedClient@FillEntryItemFromXmlRss:new Uri()"
                                              + Environment.NewLine +
                                              "RSS feed entry (" + entItem.Name + ") contain invalid entry > enclosure@link Uri: " + e.Message +
                                              Environment.NewLine);
                            }
                        }
                    }
                }
            }

            // Force textHtml for RSS feed. Even though description was missing. (needs this for browser)
            entItem.ContentType = EntryItem.ContentTypes.textHtml;

            XmlNode sum = entryNode.SelectSingleNode("description");

            if (sum != null)
            {
                // Content
                entItem.Content = await StripStyleAttributes(sum.InnerText);

                if (!string.IsNullOrEmpty(entItem.Content))
                {
                    // Summary
                    entItem.Summary = await StripHtmlTags(entItem.Content);

                    //entItem.Summary = Truncate(entItem.Summary, 230);

                    //entItem.SummaryPlainText = Truncate(entItem.Summary, 78);

                    // gets image Uri
                    if (entItem.ImageUri == null)
                    {
                        entItem.ImageUri = await GetImageUriFromHtml(entItem.Content);
                    }
                }
            }

            entItem.Status = FeedEntryItem.ReadStatus.rsNew;
        }
Example #29
0
 public void TestParseDatetimeWithoutTimezone()
 {
     Assert.AreEqual(new DateTime(2014, 12, 12, 12, 13, 30), DateTimeParser.Parse("Fri, 12 Dec 2014 12:13:30"));
 }
Example #30
0
        public static ReservationForm ReadFromWit(WitResult witResult)
        {
            var form = new ReservationForm();

            if (witResult.TryFindEntity("restaurantname", out var restaurantNameEntity))
            {
                form.RestaurantName = restaurantNameEntity.Value;
            }

            if (witResult.TryFindEntity("people_count", out var countEntity))
            {
                form.PeopleCount = int.Parse(countEntity.Value);
            }

            if (witResult.TryFindEntity(WitBuiltinEntities.DateTime, out var dateTimeEntity) && DateTimeParser.TryParse(dateTimeEntity, out var range))
            {
                form.ReservationDate = range.StartDate.DateTime;
            }

            return(form);
        }
Example #31
0
 private void SendCurrentTimeWithMinus(EPServiceProvider epService, string time, long minus)
 {
     epService.EPRuntime.SendEvent(new CurrentTimeEvent(DateTimeParser.ParseDefaultMSec(time) - minus));
 }
        public void TestDateTimeParser_ParseDateAndTime()
        {
            DateTime dateTime;
            DateTime testDateTime;
            bool     returnValue;

            returnValue = DateTimeParser.ParseDateAndTime(null, "2006", null, out dateTime);
            Assert.IsFalse(returnValue);

            returnValue = DateTimeParser.ParseDateAndTime(null, "200606", null, out dateTime);
            Assert.IsFalse(returnValue);

            returnValue = DateTimeParser.ParseDateAndTime(null, "20060607", null, out dateTime);
            Assert.IsTrue(returnValue);
            testDateTime = new DateTime(2006, 06, 07, 0, 0, 0);
            Assert.AreEqual(dateTime, testDateTime);

            returnValue = DateTimeParser.ParseDateAndTime(null, "20060607", "22", out dateTime);
            Assert.IsTrue(returnValue);
            testDateTime = new DateTime(2006, 06, 07, 22, 0, 0);
            Assert.AreEqual(dateTime, testDateTime);

            returnValue = DateTimeParser.ParseDateAndTime(null, "20060607", "2217", out dateTime);
            Assert.IsTrue(returnValue);
            testDateTime = new DateTime(2006, 06, 07, 22, 17, 0);
            Assert.AreEqual(dateTime, testDateTime);

            returnValue = DateTimeParser.ParseDateAndTime(null, "20060607", "221721", out dateTime);
            Assert.IsTrue(returnValue);
            testDateTime = new DateTime(2006, 06, 07, 22, 17, 21);
            Assert.AreEqual(dateTime, testDateTime);

            //zero fraction
            returnValue = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.000000", out dateTime);
            Assert.IsTrue(returnValue);
            testDateTime = new DateTime(2006, 06, 07, 22, 17, 21);
            Assert.AreEqual(dateTime, testDateTime);

            //maximum fraction defined by Dicom
            returnValue  = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.999999", out dateTime);
            testDateTime = new DateTime(2006, 06, 07, 22, 17, 21);
            testDateTime = testDateTime.AddTicks(9999990); //ticks are in units of 100 nano-seconds (1e9 * 100 = 1e7)
            Assert.IsTrue(returnValue);
            Assert.AreEqual(dateTime, testDateTime);

            //arbitrary length fractions
            returnValue  = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.1", out dateTime);
            testDateTime = new DateTime(2006, 06, 07, 22, 17, 21);
            testDateTime = testDateTime.AddTicks(1000000); //ticks are in units of 100 nano-seconds (1e9 * 100 = 1e7)
            Assert.IsTrue(returnValue);
            Assert.AreEqual(dateTime, testDateTime);

            returnValue  = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.12", out dateTime);
            testDateTime = new DateTime(2006, 06, 07, 22, 17, 21);
            testDateTime = testDateTime.AddTicks(1200000); //ticks are in units of 100 nano-seconds (1e9 * 100 = 1e7)
            Assert.IsTrue(returnValue);
            Assert.AreEqual(dateTime, testDateTime);

            returnValue  = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.123", out dateTime);
            testDateTime = new DateTime(2006, 06, 07, 22, 17, 21);
            testDateTime = testDateTime.AddTicks(1230000); //ticks are in units of 100 nano-seconds (1e9 * 100 = 1e7)
            Assert.IsTrue(returnValue);
            Assert.AreEqual(dateTime, testDateTime);

            returnValue  = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.1234", out dateTime);
            testDateTime = new DateTime(2006, 06, 07, 22, 17, 21);
            testDateTime = testDateTime.AddTicks(1234000); //ticks are in units of 100 nano-seconds (1e9 * 100 = 1e7)
            Assert.IsTrue(returnValue);
            Assert.AreEqual(dateTime, testDateTime);

            returnValue  = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.12345", out dateTime);
            testDateTime = new DateTime(2006, 06, 07, 22, 17, 21);
            testDateTime = testDateTime.AddTicks(1234500); //ticks are in units of 100 nano-seconds (1e9 * 100 = 1e7)
            Assert.IsTrue(returnValue);
            Assert.AreEqual(dateTime, testDateTime);

            returnValue  = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.123456", out dateTime);
            testDateTime = new DateTime(2006, 06, 07, 22, 17, 21);
            testDateTime = testDateTime.AddTicks(1234560); //ticks are in units of 100 nano-seconds (1e9 * 100 = 1e7)
            Assert.IsTrue(returnValue);
            Assert.AreEqual(dateTime, testDateTime);

            returnValue = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.123456+05", out dateTime);
            Assert.IsFalse(returnValue);

            returnValue = DateTimeParser.ParseDateAndTime(null, "a0060607", "221721.12345", out dateTime);
            Assert.IsFalse(returnValue);

            returnValue = DateTimeParser.ParseDateAndTime(null, "20060607", "a21721.12345", out dateTime);
            Assert.IsFalse(returnValue);

            returnValue = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.a2345", out dateTime);
            Assert.IsFalse(returnValue);

            returnValue = DateTimeParser.ParseDateAndTime(null, "20060607", "221721.12345r0517", out dateTime);
            Assert.IsFalse(returnValue);

            returnValue = DateTimeParser.Parse(String.Empty, out dateTime);
            Assert.IsFalse(returnValue);

            returnValue = DateTimeParser.Parse(null, out dateTime);
            Assert.IsFalse(returnValue);
        }