Ejemplo n.º 1
0
        public List <Attendance> GetAttendances()
        {
            JArray            arr         = JObject.Parse(Request("/Attendances"))["Attendances"].ToObject <JArray>();
            List <Attendance> Attendances = new List <Attendance>();

            try
            {
                for (int i = 0; i < arr.Count; i++)
                {
                    JObject attendanceObject = arr[i].ToObject <JObject>();

                    string id       = attendanceObject.GetValue("Id").ToString();
                    string lessonId = attendanceObject.SelectToken("Lesson").ToObject <JObject>().GetValue("Id").ToString();
                    // trip
                    LocalDate     date           = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(attendanceObject.GetValue("Date").ToString()).Value;
                    LocalDateTime addDate        = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(attendanceObject.GetValue("AddDate").ToString()).Value;
                    int           lessonNumber   = int.Parse(attendanceObject.GetValue("LessonNo").ToString());
                    int           semesterNumber = int.Parse(attendanceObject.GetValue("Semester").ToString());
                    string        typeId         = attendanceObject.SelectToken("Type").ToObject <JObject>().GetValue("Id").ToString();
                    string        authorId       = attendanceObject.SelectToken("AddedBy").ToObject <JObject>().GetValue("Id").ToString();

                    Attendance attendance = new Attendance(id, lessonId, date, addDate, lessonNumber, semesterNumber, typeId, authorId);
                    Attendances.Add(attendance);
                }
                attendances = Attendances;
                return(Attendances);
            }
            catch (Exception ex)
            {
                Log("failed to parse response (attendances)");
                Log(ex.Message);
                throw ex;
            }
        }
        public Option <IEnumerable <FoodItem> > Fetch(LocalDate forDate)
        {
            var urlForDate  = UrlForDate(forDate);
            var reportsPage = _context.OpenAsync(urlForDate).Result;

            reportsPage.WaitForReadyAsync().Wait(TimeSpan.FromSeconds(5));

            _logger.LogDebug($"fetching data from {urlForDate}");
            _logger.LogTrace(reportsPage.ToHtml());
            var datePattern = LocalDatePattern.CreateWithInvariantCulture("MMMM d, yyyy");
            var dateRaw     = reportsPage.QuerySelector <IHtmlHeadingElement>(Selectors.DateHeader).TextContent;

            var parsed = datePattern.Parse(dateRaw);

            if (parsed.Success)
            {
                var foodTable = reportsPage.QuerySelector <IHtmlTableElement>(Selectors.FoodTable);

                if (foodTable == null)
                {
                    _logger.LogWarning($"skipping {forDate}. No food table found (table: {Selectors.FoodTable})");
                    return(None);
                }

                return(Some(FoodTableParser.ParseTable(foodTable, parsed.Value, _loggerFactory.CreateLogger(nameof(FoodTableParser)))));
            }

            _logger.LogWarning($"skipping {forDate}. couldn't parse date text: {dateRaw}");
            return(None);
        }
Ejemplo n.º 3
0
        public List <Event> GetEvents()
        {
            JArray       arr    = JObject.Parse(Request("/HomeWorks"))["HomeWorks"].ToObject <JArray>();
            List <Event> Events = new List <Event>();

            try
            {
                for (int i = 0; i < arr.Count; i++)
                {
                    JObject eventObject = arr[i].ToObject <JObject>();

                    string        id              = eventObject.GetValue("Id").ToString();
                    string        description     = eventObject.GetValue("Content").ToString();
                    LocalDate     date            = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(eventObject.GetValue("Date").ToString()).Value;
                    string        eventCategoryId = eventObject.SelectToken("Category").ToObject <JObject>().GetValue("Id").ToString();
                    int           lessonNumber    = int.Parse(eventObject.GetValue("LessonNo").ToString());
                    string        authorId        = eventObject.SelectToken("CreatedBy").ToObject <JObject>().GetValue("Id").ToString();
                    LocalDateTime addDate         = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(eventObject.GetValue("AddDate").ToString()).Value;

                    Event e = new Event(id, description, date, eventCategoryId, lessonNumber, authorId, addDate);
                    Events.Add(e);
                }
                this.events = Events;
                return(Events);
            }
            catch (Exception ex)
            {
                Log("failed to parse response (events)");
                Log(ex.Message);
                throw ex;
            }
        }
Ejemplo n.º 4
0
        public static void AddCustomSerialisationSettings(this JsonSerializerSettings jsonSerializerSettings)
        {
            var nodaTimeLocalDatePatternConverter = LocalDatePattern.CreateWithInvariantCulture("dd-MM-yyyy");

            jsonSerializerSettings.Converters.Add(new NodaPatternConverter <LocalDate>(nodaTimeLocalDatePatternConverter));
            jsonSerializerSettings.DateParseHandling = DateParseHandling.None;
        }
Ejemplo n.º 5
0
 public static bool ParseProperty(Type type, string value, [NotNullWhen(returnValue: true)] out object?parsedValue)
 {
     if (type == typeof(DateTime) || type == typeof(DateTime?))
     {
         parsedValue = DateTime.Parse(value);
         return(true);
     }
     if (type == typeof(ZonedDateTime) || type == typeof(ZonedDateTime?))
     {
         parsedValue = LocalDateTimePattern.CreateWithInvariantCulture(DATETIME_PATTERN).Parse(value).GetValueOrThrow().InUtc();
         return(true);
     }
     if (type == typeof(LocalDateTime) || type == typeof(LocalDateTime?))
     {
         parsedValue = LocalDateTimePattern.CreateWithInvariantCulture(DATETIME_PATTERN).Parse(value).GetValueOrThrow();
         return(true);
     }
     if (type == typeof(LocalDate) || type == typeof(LocalDate?))
     {
         parsedValue = LocalDatePattern.CreateWithInvariantCulture(DATE_PATTERN).Parse(value).GetValueOrThrow();
         return(true);
     }
     if (type == typeof(LocalTime) || type == typeof(LocalTime?))
     {
         parsedValue = LocalTimePattern.CreateWithInvariantCulture(TIME_PATTERN).Parse(value).GetValueOrThrow();
         return(true);
     }
     parsedValue = null;
     return(false);
 }
Ejemplo n.º 6
0
        public List <Announcement> GetAnnouncements()
        {
            JArray arr = JObject.Parse(Request("/SchoolNotices"))["SchoolNotices"].ToObject <JArray>();
            List <Announcement> res = new List <Announcement>();

            try
            {
                for (int i = 0; i < arr.Count; i++)
                {
                    JObject announcementObject = arr[i].ToObject <JObject>();

                    string    id       = announcementObject.GetValue("Id").ToString();
                    LocalDate start    = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(announcementObject.GetValue("StartDate").ToString()).Value;
                    LocalDate end      = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(announcementObject.GetValue("EndDate").ToString()).Value;
                    string    subject  = announcementObject.GetValue("Subject").ToString();
                    string    content  = announcementObject.GetValue("Content").ToString();
                    string    authorId = announcementObject.SelectToken("AddedBy").ToObject <JObject>().GetValue("Id").ToString();

                    Announcement a = new Announcement(id, start, end, subject, content, authorId);
                    res.Add(a);
                }
                announcements = res;
                return(res);
            }
            catch (Exception ex)
            {
                Log("failed to parse response (announcements)");
                Log(ex.Message);
                throw ex;
            }
        }
Ejemplo n.º 7
0
 public DateFormatSpecification(string format)
 {
     if (format == null)
     {
         throw new ArgumentNullException(nameof(format));
     }
     _pattern = LocalDatePattern.CreateWithInvariantCulture(format);
 }
        public void Format_NoValidPattern()
        {
            var pattern = new CompositePatternBuilder <LocalDate>
            {
                { LocalDatePattern.Iso, _ => false },
                { LocalDatePattern.CreateWithInvariantCulture("yyyy"), _ => false },
            }.Build();

            Assert.Throws <FormatException>(() => pattern.Format(new LocalDate(2017, 1, 1)));
        }
Ejemplo n.º 9
0
    static void Main()
    {
        var persianCalendar = CalendarSystem.GetPersianCalendar();
        var pattern         = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd")
                              .WithTemplateValue(new LocalDate(1393, 1, 1, persianCalendar));
        LocalDate result   = pattern.Parse("1393-02-29").Value;
        DateTime  dateTime = result.AtMidnight().ToDateTimeUnspecified();

        Console.WriteLine(dateTime);     // 19th May 2014 (Gregorian)
    }
Ejemplo n.º 10
0
        public void AddMonths_MonthsBetween(string startText, int months, string expectedEndText)
        {
            var civil   = CalendarSystem.HebrewCivil;
            var pattern = LocalDatePattern.CreateWithInvariantCulture("uuuu-MM-dd")
                          .WithTemplateValue(new LocalDate(5774, 1, 1, civil)); // Sample value in 2014 ISO

            var start       = pattern.Parse(startText).Value;
            var expectedEnd = pattern.Parse(expectedEndText).Value;

            Assert.AreEqual(expectedEnd, start.PlusMonths(months));
        }
Ejemplo n.º 11
0
        public void MonthsBetween(string startText, int expectedMonths, string endText)
        {
            var civil   = CalendarSystem.HebrewCivil;
            var pattern = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd")
                          .WithTemplateValue(new LocalDate(5774, 1, 1, civil)); // Sample value in 2014 ISO

            var start = pattern.Parse(startText).Value;
            var end   = pattern.Parse(endText).Value;

            Assert.AreEqual(expectedMonths, Period.Between(start, end, PeriodUnits.Months).Months);
        }
        public void Parse()
        {
            var pattern = new CompositePatternBuilder <LocalDate>
            {
                { LocalDatePattern.Iso, _ => true },
                { LocalDatePattern.CreateWithInvariantCulture("yyyy"), _ => false },
            }.Build();

            Assert.IsTrue(pattern.Parse("2017-03-20").Success);
            Assert.IsFalse(pattern.Parse("2017-03").Success);
            Assert.IsTrue(pattern.Parse("2017").Success);
        }
        public void Enumerators()
        {
            var pattern1 = LocalDatePattern.Iso;
            var pattern2 = LocalDatePattern.CreateWithInvariantCulture("yyyy");

            var builder = new CompositePatternBuilder <LocalDate>
            {
                { pattern1, _ => true },
                { pattern2, _ => false },
            };

            CollectionAssert.AreEqual(new[] { pattern1, pattern2 }, builder.ToList());
            CollectionAssert.AreEqual(new[] { pattern1, pattern2 }, builder.OfType <LocalDatePattern>().ToList());
        }
        public IActionResult OnPostSelectAll([FromQuery] int?year, [FromQuery] int?month, [FromQuery] int?day)
        {
            if (!year.HasValue || !month.HasValue || !day.HasValue)
            {
                return(RedirectToPage("Index", new { year, month, day }));
            }
            var pageResult = PageResult(year.Value, month.Value, day.Value);

            SelectedDates.Clear();
            foreach (var date in SelectedDate.ToYearMonth().ToDateInterval())
            {
                SelectedDates.Add(LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Format(date));
            }
            return(pageResult);
        }
Ejemplo n.º 15
0
        public List <Grade> GetGrades()
        {
            JArray       arr    = JObject.Parse(Request("/Grades"))["Grades"].ToObject <JArray>();
            List <Grade> Grades = new List <Grade>();

            try
            {
                for (int i = 0; i < arr.Count; i++)
                {
                    JObject gradeObject = arr[i].ToObject <JObject>();

                    string        id                    = gradeObject.GetValue("Id").ToString();
                    string        lessonId              = gradeObject.SelectToken("Lesson").ToObject <JObject>().GetValue("Id").ToString();
                    string        subjectId             = gradeObject.SelectToken("Subject").ToObject <JObject>().GetValue("Id").ToString();
                    string        categoryId            = gradeObject.SelectToken("Category").ToObject <JObject>().GetValue("Id").ToString();
                    string        authorId              = gradeObject.SelectToken("AddedBy").ToObject <JObject>().GetValue("Id").ToString();
                    string        grade                 = gradeObject.GetValue("Grade").ToString();
                    LocalDate     date                  = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(gradeObject.GetValue("Date").ToString()).Value;
                    LocalDateTime addDate               = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(gradeObject.GetValue("AddDate").ToString()).Value;
                    int           semesterNumber        = int.Parse(gradeObject.GetValue("Semester").ToString());
                    bool          isConstituent         = bool.Parse(gradeObject.GetValue("IsConstituent").ToString());
                    bool          isSemesterGrade       = bool.Parse(gradeObject.GetValue("IsSemester").ToString());
                    bool          isSemesterProposition = bool.Parse(gradeObject.GetValue("IsSemesterProposition").ToString());
                    bool          isFinalGrade          = bool.Parse(gradeObject.GetValue("IsFinal").ToString());
                    bool          isFinalProposition    = bool.Parse(gradeObject.GetValue("IsFinalProposition").ToString());
                    string        gradeCommentId;
                    if (gradeObject.Property("Comments") != null)
                    {
                        gradeCommentId = gradeObject.SelectToken("Comments").ToObject <JArray>()[0].ToObject <JObject>().GetValue("Id").ToString();
                    }
                    else
                    {
                        gradeCommentId = String.Empty;
                    }

                    Grade g = new Grade(id, lessonId, subjectId, categoryId, authorId, grade, date, addDate, semesterNumber, isConstituent, isSemesterGrade, isSemesterProposition, isFinalGrade, isFinalProposition, gradeCommentId);
                    Grades.Add(g);
                }
                grades = Grades;
                return(Grades);
            }
            catch (Exception ex)
            {
                Log("failed to parse response (grades)");
                Log(ex.Message);
                throw ex;
            }
        }
Ejemplo n.º 16
0
        public static IList <Transaction> ReadDataxCsv(string file)
        {
            var datePattern = LocalDatePattern.CreateWithInvariantCulture("dd.MM.yyyy");

            return(File
                   .ReadAllLines(file)
                   .Skip(1)
                   .Select(line => line.Split(';'))
                   .Select(elems =>
                           new Transaction
            {
                Description = elems[5].Replace("\"", ""),
                Amount = ParseAmount(elems[6]) - ParseAmount(elems[7]),
                TransactionDate = datePattern.Parse(elems[2].Replace("\"", "")).Value
            }).ToArray());
        }
Ejemplo n.º 17
0
        [TestCase("5400-09-30", 2, "5402-09-30")] // No truncation in Kislev (both 5503 and 5504 are long)
        public void SetYear(string startText, int years, string expectedEndText)
        {
            var civil      = CalendarSystem.HebrewCivil;
            var scriptural = CalendarSystem.HebrewScriptural;
            var pattern    = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd")
                             .WithTemplateValue(new LocalDate(5774, 1, 1, scriptural)); // Sample value in 2014 ISO

            var start       = pattern.Parse(startText).Value;
            var expectedEnd = pattern.Parse(expectedEndText).Value;

            Assert.AreEqual(expectedEnd, start.PlusYears(years));

            // Check civil as well... the date should be the same (year, month, day) even though
            // the numbering is different.
            Assert.AreEqual(expectedEnd.WithCalendar(civil), start.WithCalendar(civil).PlusYears(years));
        }
Ejemplo n.º 18
0
    public static LocalDate?ParseDate(string str, bool allowNullYear = false)
    {
        // NodaTime can't parse constructs like "1st" and "2nd" so we quietly replace those away
        // Gotta make sure to do the regex otherwise we'll catch things like the "st" in "August" too
        str = Regex.Replace(str, "(\\d+)(st|nd|rd|th)", "$1");

        var patterns = new[]
        {
            "MMM d yyyy",   // Jan 1 2019
            "MMM d, yyyy",  // Jan 1, 2019
            "MMMM d yyyy",  // January 1 2019
            "MMMM d, yyyy", // January 1, 2019
            "yyyy-MM-dd",   // 2019-01-01
            "yyyy MM dd",   // 2019 01 01
            "yyyy/MM/dd"    // 2019/01/01
        }.ToList();

        if (allowNullYear)
        {
            patterns.AddRange(new[]
            {
                "MMM d",    // Jan 1
                "MMMM d",   // January 1
                "MM-dd",    // 01-01
                "MM dd",    // 01 01
                "MM/dd"     // 01/01
            });
        }

        // Giving a template value so year will be parsed as 0004 if not present
        // This means we can later disambiguate whether a null year was given
        // We use the basis year 0004 (rather than, say, 0001) because 0004 is a leap year in the Gregorian calendar
        // which means the date "Feb 29, 0004" is a valid date. 0001 is still accepted as a null year for legacy reasons.
        // TODO: should we be using invariant culture here?
        foreach (var pattern in patterns.Select(p =>
                                                LocalDatePattern.CreateWithInvariantCulture(p).WithTemplateValue(new LocalDate(0004, 1, 1))))
        {
            var result = pattern.Parse(str);
            if (result.Success)
            {
                return(result.Value);
            }
        }

        return(null);
    }
Ejemplo n.º 19
0
        private static void CalendarTest(IGTFSFeed feed)
        {
            LocalDatePattern ptn = LocalDatePattern.CreateWithInvariantCulture("ddd uuuu-MM-dd");

            foreach ((Calendar Cal, IEnumerable <CalendarDate> CalDates)cal in feed.Calendars)
            {
                Console.WriteLine($"Calendar: {cal.Cal.ID}");
                Console.WriteLine($"Provides service on: {DayMasks.Get(cal.Cal.Mask)}");
                Console.WriteLine($"Active {ptn.Format(cal.Cal.StartDate)} through {ptn.Format(cal.Cal.EndDate)}");
                Console.WriteLine("Exceptions:");
                foreach (CalendarDate date in cal.CalDates)
                {
                    Console.WriteLine($"  {ptn.Format(date.Date)}: {date.ExceptionType}");
                }
                Console.WriteLine();
            }
        }
        public IActionResult OnGet([FromQuery] int year, [FromQuery] int month, [FromQuery] int day)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToPage("Index", new { year, month, day }));
            }

            StartTime = "09:00";
            DurationMinutesForEachSlot = 30;
            CountOfSlotForEachSlot     = 1;
            CountOfSlotsToCreate       = 1;
            if (!SelectedDates.Any())
            {
                SelectedDates.Add(LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Format(SelectedDate));
            }

            return(PageResult(year, month, day));
        }
Ejemplo n.º 21
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <IConverters, ConvertersMap>();
            services.AddSingleton(provider => provider.GetService <IConverters>().LocalTime);
            services.AddSingleton(provider => provider.GetService <IConverters>().LocalDate);

            services.AddSingleton <IAuthService, AuthService>();

            services.AddScoped <AuthenticationStateProvider, CognitoAuthStateProvider>();
            services.AddAuthorizationCore();

            var handler = Assembly.Load("WebAssembly.Net.Http")
                          .GetType("WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler");

            var jsonSerializerSettings = new JsonSerializerSettings
            {
                Formatting            = Formatting.Indented,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DateParseHandling     = DateParseHandling.None,
                ContractResolver      = new CamelCasePropertyNamesContractResolver()
            }
            .ConfigureForNodaTime(DateTimeZoneProviders.Tzdb)
            .ReplaceExistingConverters <LocalDate>(
                new NodaPatternConverter <LocalDate>(LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd")));

            services.AddSingleton(jsonSerializerSettings);
            services.AddTransient(provider => new GraphQLHttpClient(new GraphQLHttpClientOptions
            {
                EndPoint               = new Uri("https://localhost:8080/graphql"),
                HttpMessageHandler     = (HttpMessageHandler)Activator.CreateInstance(handler),
                JsonSerializerSettings = jsonSerializerSettings
            }));

            services.AddScoped <IFactoryAsync, HttpClientFactoryAsync>();
            services.AddSingleton <GraphQlExtensions>();

            services.AddSingleton <IGraphQlService <Light>, LightService>();
            services.AddSingleton <IGraphQlService <Heat>, HeatService>();
            services.AddSingleton <IGraphQlService <Court>, CourtService>();
            services.AddSingleton <IGraphQlService <Rate>, RateService>();
            services.AddSingleton <IGraphQlService <Profile>, ProfileService>();
            services.AddSingleton <IGraphQlService <Event>, EventService>();
        }
Ejemplo n.º 22
0
        public LuckyNumber GetLuckyNumber()
        {
            JObject luckyNumberObject = JObject.Parse(Request("/LuckyNumbers")).SelectToken("LuckyNumber").ToObject <JObject>();

            try
            {
                string    number         = luckyNumberObject.GetValue("LuckyNumber").ToString();
                LocalDate luckyNumberDay = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(luckyNumberObject.GetValue("LuckyNumberDay").ToString()).Value;

                LuckyNumber luckyNumber = new LuckyNumber(number, luckyNumberDay);
                this.lucky = luckyNumber;
                return(luckyNumber);
            }
            catch (Exception ex)
            {
                Log("failed to parse response (lucky numbers)");
                Log(ex.Message);
                throw ex;
            }
        }
        public static JsonSerializerOptions GetSerializerOptions()
        {
            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            };

            var localTimeConverter = new NodaPatternConverter <LocalTime>(
                LocalTimePattern.CreateWithInvariantCulture("HH:mm"));
            var localDateConverter = new NodaPatternConverter <LocalDate>(
                LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd"));

            options.Converters.Add(localTimeConverter);
            options.Converters.Add(localDateConverter);
            options.Converters.Add(new DecimalConverter());
            options.Converters.Add(new LongConverter());
            options.Converters.Add(new IntConverter());
            options.Converters.Add(new DateTimeConverter());
            options.Converters.Add(new JsonStringEnumConverter());

            return(options);
        }
        public async Task <IActionResult> OnPost([FromQuery] int year, [FromQuery] int month, [FromQuery] int day)
        {
            if (!ModelState.IsValid)
            {
                ErrorMessage = "入力に誤りがあります。";
                return(PageResult(year, month, day));
            }
            if (!SelectedDates.Any())
            {
                ErrorMessage = "対象の日を1日以上は設定してください。";
                return(PageResult(year, month, day));
            }
            var startTime = LocalTimePattern.Create("HH:mm", CultureInfo.CurrentCulture).Parse(StartTime !);

            if (!startTime.Success)
            {
                ErrorMessage = "入力に誤りがあります。";
                return(PageResult(year, month, day));
            }

            var dates = SelectedDates
                        .Select(str => LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(str))
                        .ToList();

            if (dates.Any(r => !r.Success))
            {
                ErrorMessage = "入力に誤りがあります。";
                return(PageResult(year, month, day));
            }
            var result = await _service.CreateMultipleAppointmentSlotsAsync(dates.Select(d => d.Value).OrderBy(d => d).ToList(), startTime.Value, Period.FromMinutes(DurationMinutesForEachSlot !.Value), CountOfSlotForEachSlot !.Value, CountOfSlotsToCreate !.Value);

            if (!result.Succeeded)
            {
                ErrorMessage = result.ErrorMessage;
                return(PageResult(year, month, day));
            }

            return(RedirectToPage("Index", new { year, month, day }));
        }
Ejemplo n.º 25
0
        public List <TextGrade> GetTextGrades()
        {
            JArray           arr    = JObject.Parse(Request("/TextGrades"))["Grades"].ToObject <JArray>();
            List <TextGrade> result = new List <TextGrade>();

            try
            {
                for (int i = 0; i < arr.Count; i++)
                {
                    JObject textGradeObject = arr[i].ToObject <JObject>();

                    string        id                    = textGradeObject.GetValue("Id").ToString();
                    string        lessonId              = textGradeObject.SelectToken("Lesson").ToObject <JObject>().GetValue("Id").ToString();
                    string        subjectId             = textGradeObject.SelectToken("Subject").ToObject <JObject>().GetValue("Id").ToString();
                    string        authorId              = textGradeObject.SelectToken("AddedBy").ToObject <JObject>().GetValue("Id").ToString();
                    string        categoryId            = textGradeObject.SelectToken("Category").ToObject <JObject>().GetValue("Id").ToString();
                    string        grade                 = textGradeObject.GetValue("Grade").ToString();
                    LocalDate     date                  = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(textGradeObject.GetValue("Date").ToString()).Value;
                    LocalDateTime addDate               = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(textGradeObject.GetValue("AddDate").ToString()).Value;
                    int           semesterNumber        = int.Parse(textGradeObject.GetValue("Semester").ToString());
                    bool          isSemester            = bool.Parse(textGradeObject.GetValue("IsSemester").ToString());
                    bool          isSemesterProposition = bool.Parse(textGradeObject.GetValue("IsSemesterProposition").ToString());
                    bool          isFinal               = bool.Parse(textGradeObject.GetValue("IsFinal").ToString());
                    bool          isFinalProposition    = bool.Parse(textGradeObject.GetValue("IsFinalProposition").ToString());

                    TextGrade tg = new TextGrade(id, lessonId, subjectId, authorId, categoryId, grade, date, addDate, semesterNumber, isSemester, isSemesterProposition, isFinal, isFinalProposition);
                    result.Add(tg);
                }
                textGrades = result;
                return(result);
            }
            catch (Exception ex)
            {
                Log("failed to parse response (text grades)");
                Log(ex.Message);
                throw ex;
            }
        }
Ejemplo n.º 26
0
 internal override IPattern <LocalDate> CreatePattern() =>
 LocalDatePattern.CreateWithInvariantCulture(Pattern)
 .WithTemplateValue(Template)
 .WithCulture(Culture);
 public LocalDateJsonConverter()
 {
     this.pattern = LocalDatePattern.CreateWithInvariantCulture("dd MMM yyyy");
 }
Ejemplo n.º 28
0
 public LocalDateConverter(IOptions <MyOptions> options)
 {
     _pattern = LocalDatePattern.CreateWithInvariantCulture(options.Value.Pattern);
 }
Ejemplo n.º 29
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <Message> Post([FromBody] Message message)
        {
            if (message.Type == "Message")
            {
                var userid = message?.From?.Id;
                if (string.IsNullOrEmpty(userid))
                {
                    return(message.CreateReplyMessage("Struggling to get a user id..."));
                }

                // Lookup the user id to see if we have a token already..
                var token = _creds.GetToken(userid);

                if (message.Text == "token")
                {
                    return(message.CreateReplyMessage($"Token is {token}"));
                }

                string prompt = "";
                if (string.IsNullOrEmpty(token))
                {
                    var loginUri = new Uri($"http://*****:*****@"%h")} hrs {sleepSpan.ToString(@"%m")} mins";
                                var totalSleepStr = $"{totalSpan.ToString(@"%d")} days {totalSpan.ToString(@"%h")} hrs {totalSpan.ToString(@"%m")} mins";

                                prompt = $"You have tracked {num} sleeps - average sleep per night {avSleepStr} for a total of {totalSleepStr}";
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                        break;
                    }

                    if (string.IsNullOrEmpty(prompt))
                    {
                        prompt = "Please ask a question to the MS Health Bot";
                    }
                }
                // return our reply to the user
                return(message.CreateReplyMessage(prompt));
            }
            else
            {
                return(HandleSystemMessage(message));
            }
        }