Exemplo n.º 1
0
        public async Task <string> Get(string login, DateTime?startDate, DateTime?endDate, InvoiceDateQuery dateToQuery, string[] code = null, string[] ids = null, string[] fields = null, int limit = 50,
                                       int offset = 0)
        {
            var request = _sierraRestClient.Execute(Branch.invoices, "/", Method.GET);

            if (startDate.HasValue && endDate.HasValue)
            {
                request.AddQueryParameter(dateToQuery.ToString(), DateHelpers.FormatSierraDateRange(startDate.Value, endDate.Value));
            }
            request.AddQueryParameter("login", login.Trim());

            if (fields != null)
            {
                request.AddQueryParameter("fields", string.Join(",", fields));
            }

            if (code != null)
            {
                request.AddQueryParameter("code", string.Join(",", code));
            }

            if (ids != null)
            {
                request.AddQueryParameter("id", string.Join(",", ids));
            }

            request.AddQueryParameter("limit", limit.ToString());

            request.AddQueryParameter("offset", offset.ToString());

            // execute the request
            var result = await _sierraRestClient.Client.ExecuteAsync(request);

            return(result.Content);
        }
Exemplo n.º 2
0
        public string Serialize()
        {
            var result = new StringBuilder(128);

            result.AppendFormat(
                "symbol={0}&side={1}&type={2}&timeInForce={3}&quantity={4}&price={5}&timestamp={6}",
                Symbol.ToUpper(),
                Side == OrderSide.Buy ? "BUY" : "SELL",
                Type == OrderType.Limit ? "LIMIT" : (Side == OrderSide.Buy ? "TAKE_PROFIT_LIMIT" : "STOP_LOSS_LIMIT"),
                TimeInForce,
                Quantity.ToString("N8", CultureInfo.InvariantCulture),
                Price.ToString("N8", CultureInfo.InvariantCulture),
                DateHelpers.ToBinanceDate(Date)
                );

            if (!string.IsNullOrEmpty(OrderId))
            {
                result.Append("&newClientOrderId=").Append(OrderId);
            }

            if (StopPrice.HasValue)
            {
                result.Append("&stopPrice=").Append(StopPrice.Value.ToString("N2", CultureInfo.InvariantCulture));
            }

            if (ReceiveWindow.HasValue)
            {
                result.Append("&recvWindow=").Append(ReceiveWindow.Value);
            }

            return(result.ToString());
        }
        private bool ValidateBooking(Booking booking)
        {
            bool isValid = true;

            // Check if from date is after To date
            if (booking.From > booking.To)
            {
                ModelState.AddModelError("Booking.From", "Start date cannot be after end date");
                var createBookingViewModel = new CreateBookingViewModel()
                {
                    Tracks = DbContext.Tracks, Booking = booking
                };
                isValid = false;
            }

            //1. Hämta ut alla bokning som har samma roomId som den nya bokningen
            List <Booking> bookingsFromDb = DbContext.Bookings.Where(b => b.TrackId == booking.TrackId).ToList();

            //2. Kolla om något av dessa bokningar har överlappande datum
            foreach (var oldBooking in bookingsFromDb)
            {
                if (DateHelpers.HasSharedDateIntervals(booking.From, booking.To, oldBooking.From, oldBooking.To))
                {
                    ModelState.AddModelError("Booking.From", "Date already occupied.");
                    var createBookingViewModel = new CreateBookingViewModel()
                    {
                        Tracks = DbContext.Tracks, Booking = booking
                    };
                    isValid = false;
                }
            }

            return(isValid);
        }
Exemplo n.º 4
0
        private bool ValidateBooking(Booking booking)
        {
            bool isValid = true;

            //Check if From date is after To date
            if (booking.From > booking.To)
            {
                ModelState.AddModelError("Booking.From", "Start date cannot be after end date");
                var CreateBookingViewModel = new CreateBookingViewModel()
                {
                    Giraffes = DbContext.Giraffes, Booking = booking
                };
                isValid = false;
            }
            //1. Fetch all bookings with the same GiraffeID as the new one

            List <Booking> oldBookings = DbContext.Bookings.Where(b => b.GiraffeId == booking.GiraffeId).ToList();

            //2. Check if any of the dates in the bookings overlap
            foreach (var oldBooking in oldBookings)
            {
                if (DateHelpers.HasSharedDateInterval(booking.From, booking.To, oldBooking.From, oldBooking.To))
                {
                    ModelState.AddModelError("Booking.From", "Date already occupied.");
                    var createBookingViewModel = new CreateBookingViewModel()
                    {
                        Giraffes = DbContext.Giraffes, Booking = booking
                    };
                    isValid = false;
                }
            }
            return(isValid);
        }
Exemplo n.º 5
0
        public async Task <IActionResult> MonthStatistics(int projectId)
        {
            var project = await _projects.GetProjectAsync(projectId);

            if (project == null)
            {
                return(NotFound());
            }

            if (!await _authorizationService.AuthorizeAsync(User, project, "IsOwner"))
            {
                return(NotFound());
            }

            TimeZoneInfo timeZone = _projects.GetTimeZone(project);
            CultureInfo  _culture = _projects.GetCulture(project);

            var now          = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Utc, timeZone);
            var startOfMonth = DateHelpers.GetStartOfMonth(now);
            var endOfMonth   = DateHelpers.GetEndOfMonth(now);

            var timers  = _timers.GetTimersInInterval(project, startOfMonth, endOfMonth);
            var grouped = timers.GroupBy(x => x.Started.Date).Select(g => new { Day = g.Key, Timers = g.ToList() });

            return(new OkObjectResult(grouped));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> WeekStatistics(int projectId)
        {
            var project = await _projects.GetProjectAsync(projectId);

            if (project == null)
            {
                return(NotFound());
            }

            if (!await _authorizationService.AuthorizeAsync(User, project, "IsOwner"))
            {
                return(NotFound());
            }

            TimeZoneInfo timeZone = _projects.GetTimeZone(project);
            CultureInfo  _culture = _projects.GetCulture(project);

            var now         = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Utc, timeZone);
            var startOfWeek = DateHelpers.GetStartOfWeek(now, _culture);
            var endOfWeek   = DateHelpers.GetEndOfWeek(now, _culture);

            var timers  = _timers.GetTimersInInterval(project, startOfWeek, endOfWeek);
            var grouped = _timers.GroupTimers(timers, TimersGroupFlags.day);

            return(new OkObjectResult(grouped));
        }
Exemplo n.º 7
0
        // Calc and return progress
        public async Task <NormProgress> GetProgressAsync(Project project, DateTime date)
        {
            Norm norm = await GetNormAsync(project);

            switch (norm.Type)
            {
            case NormType.Day:
                var duration = _timers.GetDuration(_timers.GetTimersInInterval(project, date.Date, date.Date.AddDays(1)));
                return(new NormProgress(norm, norm.Goal, duration));

            case NormType.Week:
                var startOfWeek = DateHelpers.GetStartOfWeek(date, _projects.GetCulture(project));
                // Get [(start of week)..date] duration
                var curWeekDuration = _timers.GetDuration(_timers.GetTimersInInterval(project, startOfWeek, date));
                return(new NormProgress(norm, norm.Goal, curWeekDuration));

            case NormType.Month:
                var startOfMonth = DateHelpers.GetStartOfMonth(date);
                // Get [(start of month)..date] duration
                var curMonthDuration = _timers.GetDuration(_timers.GetTimersInInterval(project, startOfMonth, date));
                return(new NormProgress(norm, norm.Goal, curMonthDuration));

            case NormType.Project:
                var timers = _timers.GetDuration(_timers.GetTimersInInterval(project, null, date));
                return(new NormProgress(norm, norm.Goal, timers));

            case NormType.None:
                return(new NormProgress(norm, new TimeSpan(0), new TimeSpan(0)));
            }
            throw new ArgumentException();
        }
 private bool IntervalsIntersectWithInterval()
 {
     return(DateHelpers.IntervalsIntersect(
                _intervalStart,
                _intervalEnd
                ));
 }
Exemplo n.º 9
0
        public IEnumerable <Schedule> GenerateSchedule(int weeks = 4)
        {
            var lastScheduledWeek = scheduleRepository.GetLastScheduledWeek().ToList();

            var lastScheduledDate = lastScheduledWeek.LastOrDefault()?.Date;

            var engineerIds = engineerRepository.GetAllActive().Select(x => x.Id).ToList();

            var engineerRotation = new List <Schedule>();

            for (var i = 0; i < weeks; i++)
            {
                var startingDate = DateHelpers.NextWeekday(lastScheduledDate);

                var shifts = ScheduleHelper.AssignShift(engineerIds, lastScheduledWeek);

                (lastScheduledWeek, lastScheduledDate) = ScheduleHelper.ScheduleWeekRotation(startingDate, shifts);

                engineerRotation.AddRange(lastScheduledWeek);
            }

            scheduleRepository.Save(engineerRotation);

            return(engineerRotation);
        }
Exemplo n.º 10
0
        private bool ValidateBooking(Rental rental)
        {
            bool isValid = true;


            if (rental.From > rental.To)
            {
                ModelState.AddModelError("Booking.From", "Start date cannot be after end date");
                var newRentalViewModel = new NewRentalViewModel()
                {
                    Cars = DbContext.Cars, Rental = rental
                };
                isValid = false;
            }


            List <Rental> rentalFromDb = DbContext.Rentals.Where(r => r.CarId == rental.CarId).ToList();


            foreach (var currentRentals in rentalFromDb)
            {
                if (DateHelpers.HasSharedDateIntervals(rental.From, rental.To, currentRentals.From, currentRentals.To))
                {
                    ModelState.AddModelError("Booking.From", "Date already occupied.");
                    var newRentalViewModel = new NewRentalViewModel()
                    {
                        Cars = DbContext.Cars, Rental = rental
                    };
                    isValid = false;
                }
            }

            return(isValid);
        }
Exemplo n.º 11
0
 public ScheduleMappingProfile()
 {
     CreateMap <Schedule, ScheduleReadDto>()
     .ForMember(x => x.Date, x => x.MapFrom(x => DateHelpers.DateTimeToISOString(x.Date)));
     CreateMap <Schedule, ScheduleListViewModel>()
     .ForMember(x => x.Date, x => x.MapFrom(x => DateHelpers.DateTimeToISOString(x.Date)));
     CreateMap <ScheduleWriteDto, Schedule>();
 }
Exemplo n.º 12
0
 /// <summary>
 /// Converts to local time (so adjusted from school time if living in a different time zone).
 /// </summary>
 /// <param name="rawDateTime"></param>
 /// <returns></returns>
 protected DateTime ToViewItemTime(DateTime rawDateTime)
 {
     if (!_usingLocalTimes)
     {
         _usingLocalTimes = true;
         Account.OnSchoolTimeZoneChanged += new WeakEventHandler(Account_OnSchoolTimeZoneChanged).Handler;
     }
     return(DateHelpers.ToViewItemTime(Account, rawDateTime));
 }
Exemplo n.º 13
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is DateTime)
            {
                return(DateHelpers.ToFriendlyShortDate((DateTime)value));
            }

            return(value);
        }
Exemplo n.º 14
0
        public void SetStartingDate(DateTime startingDate)
        {
            if (startingDate == default)
            {
                throw new BusinessException("Budget starting date is required");
            }

            StartingDate = DateHelpers.FirstDayOfMonth(startingDate);
        }
 private bool IntervalsIntersect()
 {
     return(DateHelpers.IntervalsIntersect(
                _aIntervalStart,
                _aIntervalEnd,
                _bIntervalStart,
                _bIntervalEnd
                ));
 }
Exemplo n.º 16
0
 private bool BookingInThePast(AddBookingRequest request, ref PdrValidationResult result)
 {
     if (request.StartTime < DateHelpers.CurrentDate())
     {
         result.PassedValidation = false;
         result.Errors.Add("Booking is in the past");
         return(true);
     }
     return(false);
 }
Exemplo n.º 17
0
        public void TestConvertToGregorianDate_Success()
        {
            int day   = 18;
            int month = 2;
            int year  = 1440;

            DateTime result = DateHelpers.ConvertToGregorianDate(year, month, day);

            Assert.IsTrue(result.Year == 2018 && result.Month == 10 && result.Day == 27);
        }
Exemplo n.º 18
0
        public void GenerateSchedule_ExistingSchedule()
        {
            var lastScheduledDate = DateTime.UtcNow.AddDays(-15).Date;

            mockEngineerRepository.Setup(x => x.GetAllActive()).Returns(Engineers);
            mockScheduleRepository.Setup(x => x.GetLastScheduledWeek()).Returns(new List <Schedule>
            {
                new Schedule {
                    Date = lastScheduledDate.AddDays(-4), Shift = Shift.Morning, EngineerId = 5
                },
                new Schedule {
                    Date = lastScheduledDate.AddDays(-4), Shift = Shift.Afternoon, EngineerId = 7
                },
                new Schedule {
                    Date = lastScheduledDate.AddDays(-3), Shift = Shift.Morning, EngineerId = 2
                },
                new Schedule {
                    Date = lastScheduledDate.AddDays(-3), Shift = Shift.Afternoon, EngineerId = 4
                },
                new Schedule {
                    Date = lastScheduledDate.AddDays(-2), Shift = Shift.Morning, EngineerId = 9
                },
                new Schedule {
                    Date = lastScheduledDate.AddDays(-2), Shift = Shift.Afternoon, EngineerId = 3
                },
                new Schedule {
                    Date = lastScheduledDate.AddDays(-1), Shift = Shift.Morning, EngineerId = 6
                },
                new Schedule {
                    Date = lastScheduledDate.AddDays(-1), Shift = Shift.Afternoon, EngineerId = 1
                },
                new Schedule {
                    Date = lastScheduledDate, Shift = Shift.Morning, EngineerId = 8
                },
                new Schedule {
                    Date = lastScheduledDate, Shift = Shift.Afternoon, EngineerId = 10
                }
            });

            var result = scheduleService.GenerateSchedule().ToList();

            result.Should()
            .NotBeNull()
            .And.NotBeEmpty()
            .And.HaveCount(40);                     // 2 shifts for 4 weeks

            result.First().Date.Should().Be(DateHelpers.NextWeekday(lastScheduledDate));

            mockScheduleRepository.Verify(x => x.GetLastScheduledWeek(), Times.Once);
            mockEngineerRepository.Verify(x => x.GetAllActive(), Times.Once);
            mockScheduleRepository.Verify(x => x.Save(It.IsAny <IEnumerable <Schedule> >()), Times.Once);
        }
Exemplo n.º 19
0
        public OutageReport Generate(ReportOptions options)
        {
            List <Specification <OutageEntity> > specs = new List <Specification <OutageEntity> >();

            if (options.ElementId.HasValue)
            {
                specs.Add(new OutageElementIdQuery(options.ElementId.Value));
            }

            if (options.StartDate.HasValue)
            {
                specs.Add(new OutageStartDateQuery(options.StartDate.Value));
            }

            if (options.EndDate.HasValue)
            {
                specs.Add(new OutageEndDateQuery(options.EndDate.Value));
            }

            IEnumerable <OutageEntity> outages;

            if (specs.Count > 1)
            {
                AndSpecification <OutageEntity> andQuery = new AndSpecification <OutageEntity>(specs);
                outages = _outageRepository.Find(andQuery.IsSatisfiedBy).ToList();
            }
            else if (specs.Count == 1)
            {
                outages = _outageRepository.Find(specs[0].IsSatisfiedBy).ToList();
            }
            else
            {
                outages = _outageRepository.GetAll().ToList();
            }

            var type = DateHelpers.GetType(options.StartDate, options.EndDate);

            var outageReportGrouping = outages.GroupBy(o => type == "Monthly" ? o.ReportTime.Month : o.ReportTime.Year).Select(o => o).ToList();

            var reportData = new Dictionary <string, float>();

            foreach (var outage in outageReportGrouping)
            {
                reportData.Add(type == "Monthly" ? DateHelpers.Months[outage.Key] : outage.Key.ToString(), outage.Count());
            }

            return(new OutageReport
            {
                Type = type,
                Data = reportData
            });
        }
Exemplo n.º 20
0
 public void FillCompareTable()
 {
     Data   = null;
     socket = new WebSocket(wsURL);
     socket.Connect();
     socket.OnMessage += Socket_OnMessage;
     socket.Send(sessionReq);
     while (!dataArrived)
     {
         Task.Delay(1000).ConfigureAwait(false);
     }
     foreach (var sport in Data["sport"].First)
     {
         if (!mappings.SportMappings.ContainsKey(sport["alias"].ToObject <string>()))
         {
             continue;
         }
         foreach (var region in sport["region"])
         {
             JObject regionObj  = (JObject)region.First;
             string  regionName = regionObj["alias"].ToObject <string>();
             foreach (var competition in regionObj["competition"])
             {
                 JObject league     = (JObject)competition.First;
                 string  leagueName = league["name"].ToObject <string>();
                 foreach (var game in league["game"])
                 {
                     try
                     {
                         Compare_Events ev      = new Compare_Events();
                         JObject        gameObj = (JObject)game.First;
                         ev.Home   = gameObj["team1_name"].ToObject <string>();
                         ev.Away   = gameObj["team2_name"].ToObject <string>();
                         ev.Region = regionName;
                         ev.League = leagueName;
                         ev.Start  = DateHelpers.TimeStampToDateTime(gameObj["start_ts"].ToObject <double>());
                         var a = gameObj["start_ts"];
                         ev.PrematchEnd = ev.Start;
                         ev.SportID     = mappings.SportMappings[sport["alias"].ToObject <string>()].ID;
                         ev.SiteID      = mappings.ID;
                         context.Compare_Events.Add(ev);
                     }
                     catch
                     {
                         continue;
                     }
                 }
             }
         }
     }
     int count = context.SaveChanges();
 }
        public Person Create(int seed)
        {
            var person = new Person
            {
                FirstName   = "First",
                LastName    = "Last",
                DateOfBirth = DateHelpers.RandomDate(1935, 2005, seed),
                ImageBase64 = "",
                Interests   = StaticData.RandomInterests(seed),
            };

            return(person);
        }
Exemplo n.º 22
0
 public CrewMappingProfile()
 {
     CreateMap <Crew, CrewListResource>()
     .ForMember(x => x.Birthdate, x => x.MapFrom(x => DateHelpers.DateTimeToISOString(x.Birthdate)));
     CreateMap <Crew, CrewReadResource>()
     .ForMember(x => x.Birthdate, x => x.MapFrom(x => DateHelpers.DateTimeToISOString(x.Birthdate)))
     .ForMember(x => x.Ship, x => x.MapFrom(x => new { x.Ship.Id, x.Ship.Description }))
     .ForMember(x => x.Nationality, x => x.MapFrom(x => new { x.Nationality.Id, x.Nationality.Description }))
     .ForMember(x => x.Gender, x => x.MapFrom(x => new { x.Gender.Id, x.Gender.Description }));
     CreateMap <Crew, SimpleResource>()
     .ForMember(x => x.Description, x => x.MapFrom(x => x.Lastname + " " + x.Firstname + " " + DateHelpers.DateTimeToISOString(x.Birthdate)));
     CreateMap <CrewWriteResource, Crew>()
     .ForMember(x => x.Birthdate, x => x.MapFrom(x => x.Birthdate));
 }
Exemplo n.º 23
0
        public static TreinoSemanaInsertDTO InsertTreinoSemanaEVR(int IDUsuario, TreinoSemanaAddDTO TreinoSemanaAdd, TreinosDAO TreinosDAO)
        {
            TreinoSemanaInsertDTO _TreinoSemanaInsert = new TreinoSemanaInsertDTO();

            SemanaDiasDTO _SemanaDias = TreinosDAO.SelectSemanaDiaPorIDSemana(TreinoSemanaAdd.IDSemanaDia);

            if (_SemanaDias == null)
            {
                _TreinoSemanaInsert.Status = false;
                _TreinoSemanaInsert.Msg    = "Dia da semana inválido!";
                return(_TreinoSemanaInsert);
            }

            DateHelpers _DateHelpers = new DateHelpers();

            DateTime DataInicio = _DateHelpers.GetNextDateForDay(TreinoSemanaAdd.IDSemanaDia);

            List <SemanaUsuariosDTO> _SemanaUsuarios = TreinosDAO.SelectSemanasUsuarioPorIDUsuario(IDUsuario);

            if (DataInicio < DateTime.Now)
            {
                _TreinoSemanaInsert.Status = false;
                _TreinoSemanaInsert.Msg    = "Data Inicio deve ser maior ou igual a data de hoje!";
                return(_TreinoSemanaInsert);
            }

            SemanaUsuariosDTO _SemanaUsuario = _SemanaUsuarios.Where((semana) => semana.IDUsuario == IDUsuario && semana.Ativo == true).FirstOrDefault();

            if (_SemanaUsuario != null)
            {
                if (_SemanaUsuario.DataFim > DateTime.Now)
                {
                    _TreinoSemanaInsert.Status = false;
                    _TreinoSemanaInsert.Msg    = "Voce só poderá solicitar um novo treino a partir de: " + _SemanaUsuario.DataFim;
                    return(_TreinoSemanaInsert);
                }
            }

            List <SemanasDTO>        _Semanas         = TreinosDAO.SelectSemanas();
            List <SemanaUsuariosDTO> _SemanasUsuarios = TreinosDAO.SelectSemanasUsuarioPorIDUsuario(IDUsuario);
            var Semanas   = _Semanas.Where(item => !_SemanasUsuarios.Any(item2 => item2.IDSemana == item.IDSemana));
            int _IDSemana = Semanas.Min((semana) => semana.IDSemana);
            int _IDTipo   = TreinosDAO.SelectTreinosPorIDSemana(_IDSemana).FirstOrDefault().IDTipo;

            _TreinoSemanaInsert.IDTipo     = _IDTipo;
            _TreinoSemanaInsert.DataInicio = DataInicio;
            _TreinoSemanaInsert.IDSemana   = _IDSemana;
            return(_TreinoSemanaInsert);
        }
Exemplo n.º 24
0
 public void Handle(IQueryResult message)
 {
     if (!message.Success)
     {
         return;
     }
     if (message.Duration.TotalMilliseconds > message.ThresholdMilliseconds && message.AlertIfAboveThreshold)
     {
         var    formattedSubject = string.Format(subject, message.Name);
         var    threshold        = new TimeSpan(0, 0, 0, 0, message.ThresholdMilliseconds);
         string body             = string.Format("Query Name: {0}\nQuery Run At: {1}\nThreshold: {2}\nTime Taken: {3}\n\nRegards,\n{4}", message.Name, message.StartDate,
                                                 DateHelpers.FormatTimespan(threshold), DateHelpers.FormatTimespan(message.Duration), fromName);
         smtpClient.Send(fromEmail, message.AlertEmailTo, formattedSubject, body);
     }
 }
Exemplo n.º 25
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var startDate = DateHelpers.ParseDateInput(context.RouteData.Values["startDate"].ToString());

            if (!startDate.HasValue)
            {
                context.Result = new BadRequestObjectResult(new ValidationError("Start date input is invalid"));
            }
            else
            {
                context.ActionArguments["startDate"] = startDate.Value;
            }

            base.OnActionExecuting(context);
        }
Exemplo n.º 26
0
        protected void AddNewMarkers()
        {
            var currentEvents = new List <Event>();

            foreach (var item in _events)
            {
                if (DateHelpers.DateIsWithinBounds(_totalMonths, item.Start, item.End))
                {
                    currentEvents.Add(item);
                }
            }

            JSRuntime.InvokeVoidAsync("removeAllMarkers");
            JSRuntime.InvokeVoidAsync("addCurrentEvents", currentEvents);
        }
Exemplo n.º 27
0
        public async Task <IActionResult> Summary(DateTime?start, DateTime?end)
        {
            if (start == null)
            {
                start = DateHelpers.MonthStart();
            }

            if (end == null)
            {
                end = DateHelpers.MonthEnd();
            }

            var result = await queries.RunAsync(new ListSourcesWithAmounts(start.Value, end.Value));

            return(Ok(result));
        }
Exemplo n.º 28
0
        public static void UpdateAge(this Person person, double age)
        {
            int count = person.Visits.Sum(v => v.ProfilePictures.Count);

            if (count == 0)
            {
                person.DateOfBirth = DateTime.UtcNow.AddYears(-(int)age);
            }
            else
            {
                int oldAge = DateHelpers.ConvertDateOfBirthToAge(person.DateOfBirth);

                var result = ((oldAge * count) + age) / (count + 1);

                person.DateOfBirth = DateTime.UtcNow.AddYears(-(int)result);
            }
        }
Exemplo n.º 29
0
        private async void DoWork(object?state)
        {
            this.logger.LogInformation("Work");

            DateTime utcLastCheckpoint = await this.GetLastProcessedDate();

            DateTime finalUtcEnd = DateTime.UtcNow.Subtract(this.appSettings.MailgunEventLagTime);

            while (utcLastCheckpoint < finalUtcEnd)
            {
                DateTime utcNextCheckpoint = DateHelpers.MinDate(utcLastCheckpoint.Add(this.appSettings.CheckpointPeriod), finalUtcEnd);

                await this.ProcessCheckpoint(utcLastCheckpoint : utcLastCheckpoint, utcNextCheckpoint : utcNextCheckpoint);

                utcLastCheckpoint = utcNextCheckpoint;
            }
        }
Exemplo n.º 30
0
        public void GetAccessToken(string verifier)
        {
            string timestamp = DateHelpers.DateTimeToUnitTimeStamp(DateTime.UtcNow).ToString();

            SimpleConnector connector = new SimpleConnector();

            connector.SetServerName(Constants.Urls.TOKEN_ACCESS);
            connector.AddParam("oauth_token", this.OAuthToken);
            connector.AddParam("oauth_consumer_key", Settings.Key);
            connector.AddParam("oauth_nonce", Settings.Nounce);
            connector.AddParam("oauth_timestamp", timestamp);
            connector.AddParam("oauth_verifier", verifier);
            connector.AddParam("oauth_signature_method", Settings.SignatireMethod);
            connector.AddParam("oauth_signature", this.generateSignature(this.CurrentSignatureType, "POST", Constants.Urls.TOKEN_ACCESS, connector.GetParams(), Settings.SecretKey + "&" + this.OAuthTokenSecret));
            connector.OnRequestComplete += parseAccessToken;
            connector.OnRequestComplete += this.onRequestComplete;
            connector.SendPost();
        }