System.DateTime.AddMonths(int)

Here are the examples of the csharp api System.DateTime.AddMonths(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

765 Examples 7

19 Source : FuturesOptionsUnderlyingMapper.cs
with Apache License 2.0
from Capnode

private static DateTime GetFutureContractMonthNoRulesApplied(Symbol canonicalFutureSymbol, DateTime futureOptionExpirationDate)
        {
            var baseOptionExpiryMonthDate = new DateTime(futureOptionExpirationDate.Year, futureOptionExpirationDate.Month, 1);
            if (!_futuresOptionsExpiryDelta.ContainsKey(canonicalFutureSymbol.ID.Symbol))
            {
                // For contracts like CL, they have no expiry delta between the Futures and FOPs, so we hit this path.
                // However, it does have a delta between its expiry and contract month, which we adjust here before
                // claiming that `baseOptionExpiryMonthDate` is the future's contract month.
                var futuresExpiry = FuturesExpiryFunctions.FuturesExpiryFunction(canonicalFutureSymbol)(baseOptionExpiryMonthDate);
                var futuresDelta = FuturesExpiryUtilityFunctions.GetDeltaBetweenContractMonthAndContractExpiry(canonicalFutureSymbol.ID.Symbol, futuresExpiry);

                return baseOptionExpiryMonthDate.AddMonths(futuresDelta);
            }

            return baseOptionExpiryMonthDate.AddMonths(_futuresOptionsExpiryDelta[canonicalFutureSymbol.ID.Symbol]);
        }

19 Source : StatisticsBuilder.cs
with Apache License 2.0
from Capnode

private static IEnumerable<PeriodRange> GetPeriodRanges(int periodMonths, DateTime firstDate, DateTime lastDate)
        {
            // get end dates
            var date = lastDate.Date;
            var endDates = new List<DateTime>();
            do
            {
                endDates.Add(date);
                date = new DateTime(date.Year, date.Month, 1).AddDays(-1);
            } while (date >= firstDate);

            // build period ranges
            var ranges = new List<PeriodRange> { new PeriodRange { StartDate = firstDate, EndDate = endDates[endDates.Count - 1] } };
            for (var i = endDates.Count - 2; i >= 0; i--)
            {
                var startDate = ranges[ranges.Count - 1].EndDate.AddDays(1).AddMonths(1 - periodMonths);
                if (startDate < firstDate) startDate = firstDate;

                ranges.Add(new PeriodRange
                {
                    StartDate = startDate,
                    EndDate = endDates[i]
                });
            }

            return ranges;
        }

19 Source : FuturesOptionsExpiryFunctions.cs
with Apache License 2.0
from Capnode

public static DateTime GetFutureOptionExpiryFromFutureExpiry(Symbol futureSymbol, Symbol canonicalFutureOption = null)
        {
            var futureContractMonthDelta = FuturesExpiryUtilityFunctions.GetDeltaBetweenContractMonthAndContractExpiry(futureSymbol.ID.Symbol, futureSymbol.ID.Date);
            var futureContractMonth = new DateTime(
                    futureSymbol.ID.Date.Year,
                    futureSymbol.ID.Date.Month,
                    1)
                .AddMonths(futureContractMonthDelta);

            if (canonicalFutureOption == null)
            {
                canonicalFutureOption = Symbol.CreateOption(
                    Symbol.Create(futureSymbol.ID.Symbol, SecurityType.Future, futureSymbol.ID.Market),
                    futureSymbol.ID.Market,
                    default(OptionStyle),
                    default(OptionRight),
                    default(decimal),
                    SecurityIdentifier.DefaultDate);
            }

            return FuturesOptionExpiry(canonicalFutureOption, futureContractMonth);
        }

19 Source : FuturesOptionsExpiryFunctions.cs
with Apache License 2.0
from Capnode

private static DateTime FridayBeforeTwoBusinessDaysBeforeEndOfMonth(Symbol underlyingFuture, DateTime expiryMonth)
        {
            var holidays = _mhdb.GetEntry(underlyingFuture.ID.Market, underlyingFuture, SecurityType.Future)
                .ExchangeHours
                .Holidays;

            var expiryMonthPreceding = expiryMonth.AddMonths(-1).AddDays(-(expiryMonth.Day - 1));
            var fridayBeforeSecondLastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(
                expiryMonthPreceding,
                2,
                holidays).AddDays(-1);

            while (fridayBeforeSecondLastBusinessDay.DayOfWeek != DayOfWeek.Friday)
            {
                fridayBeforeSecondLastBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(fridayBeforeSecondLastBusinessDay, -1, false, holidays);
            }

            return fridayBeforeSecondLastBusinessDay;
        }

19 Source : FuturesOptionsExpiryFunctions.cs
with Apache License 2.0
from Capnode

private static DateTime FourthLastBusinessDayInPrecedingMonthFromContractMonth(Symbol underlyingFuture, DateTime expiryMonth, int hour, int minutes, bool noFridays = true)
        {
            var holidays = _mhdb.GetEntry(underlyingFuture.ID.Market, underlyingFuture, SecurityType.Future)
                .ExchangeHours
                .Holidays;

            var expiryMonthPreceding = expiryMonth.AddMonths(-1);
            var fourthLastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(expiryMonthPreceding, 4, holidays);

            if (noFridays)
            {
                while (fourthLastBusinessDay.DayOfWeek == DayOfWeek.Friday || holidays.Contains(fourthLastBusinessDay.AddDays(1)))
                {
                    fourthLastBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(fourthLastBusinessDay, -1, false, holidays);
                }
            }

            return fourthLastBusinessDay.AddHours(hour).AddMinutes(minutes);
        }

19 Source : FuturesExpiryUtilityFunctions.cs
with Apache License 2.0
from Capnode

public static DateTime DairyLastTradeDate(DateTime time, TimeSpan? lastTradeTime = null)
        {
            // Trading shall terminate on the business day immediately preceding the day on which the USDA announces the <DAIRY_PRODUCT> price for that contract month. (LTD 12:10 p.m.)
            var contractMonth = new DateTime(time.Year, time.Month, 1);
            var lastTradeTs = lastTradeTime ?? new TimeSpan(17, 10, 0);

            DateTime publicationDate;
            if (FuturesExpiryFunctions.DairyReportDates.TryGetValue(contractMonth, out publicationDate))
            {
                do
                {
                    publicationDate = publicationDate.AddDays(-1);
                }
                while (USHoliday.Dates.Contains(publicationDate) || publicationDate.DayOfWeek == DayOfWeek.Saturday);
            }
            else
            {
                publicationDate = contractMonth.AddMonths(1);
            }

            // The USDA price announcements are erratic in their publication date. You can view the calendar the USDA announces prices here: https://www.ers.usda.gov/calendar/
            // More specifically, the report you should be looking for has the name "National Dairy Products Sales Report".
            // To get the report dates found in FuturesExpiryFunctions.DairyReportDates, visit this website: https://mpr.datamart.ams.usda.gov/menu.do?path=Products\Dairy\All%20Dairy\(DY_CL102)%20National%20Dairy%20Products%20Prices%20-%20Monthly

            return publicationDate.Add(lastTradeTs);
        }

19 Source : SymbolRepresentation.cs
with Apache License 2.0
from Capnode

public static string GenerateFutureTicker(string underlying, DateTime expiration, bool doubleDigitsYear = true)
        {
            var year = doubleDigitsYear ? expiration.Year % 100 : expiration.Year % 10;
            var month = expiration.Month;

            var contractMonthDelta = FuturesExpiryUtilityFunctions.GetDeltaBetweenContractMonthAndContractExpiry(underlying, expiration.Date);
            if (contractMonthDelta < 0)
            {
                // For futures that have an expiry after the contract month.
                // This is for dairy contracts, which can and do expire after the contract month.
                var expirationMonth = expiration.AddDays(-(expiration.Day - 1))
                    .AddMonths(contractMonthDelta);

                month = expirationMonth.Month;
                year = doubleDigitsYear ? expirationMonth.Year % 100 : expirationMonth.Year % 10;
            }
            else {
                // These futures expire in the month before or in the contract month
                month += contractMonthDelta;

                // Get the month back into the allowable range, allowing for a wrap
                // Below is a little algorithm for wrapping numbers with a certain bounds.
                // In this case, were dealing with months, wrapping to years once we get to January
                // As modulo works for [0, x), it's best to subtract 1 (as months are [1, 12] to convert to [0, 11]),
                // do the modulo/integer division, then add 1 back on to get into the correct range again
                month--;
                year += month / 12;
                month %= 12;
                month++;
            }

            return $"{underlying}{expiration.Day:00}{_futuresMonthLookup[month]}{year}";
        }

19 Source : unixtime.cs
with MIT License
from ccxt-net

public static DateTime GetLastDayOfMonth(DateTime day_of_target)
        {
            // set return value to the last day of the month
            // for any date preplaceded in to the method

            // create a datetime variable set to the preplaceded in date
            DateTime _lastDay = day_of_target;

            // overshoot the date by a month
            _lastDay = _lastDay.AddMonths(1);

            // remove all of the days in the next month
            // to get bumped down to the last day of the
            // previous month
            _lastDay = _lastDay.AddDays(-(_lastDay.Day));

            // return the last day of the month
            return _lastDay;
        }

19 Source : unixtime.cs
with MIT License
from ccxt-net

public static DateTime GetLastDayOfMonth(int month_of_target)
        {
            // set return value to the last day of the month
            // for any date preplaceded in to the method

            // create a datetime variable set to the preplaceded in date
            var _lastDay = new DateTime(UtcNow.Year, month_of_target, 1).ToUniversalTime();

            // overshoot the date by a month
            _lastDay = _lastDay.AddMonths(1);

            // remove all of the days in the next month
            // to get bumped down to the last day of the
            // previous month
            _lastDay = _lastDay.AddDays(-(_lastDay.Day));

            // return the last day of the month
            return _lastDay;
        }

19 Source : YearTimeFile.cs
with Apache License 2.0
from cdy816

public List<DataFileInfo4> GetDataFiles(DateTime startTime,TimeSpan span)
        {
            List<DataFileInfo4> re = new List<DataFileInfo4>();
            var nxtMonth = startTime.AddMonths(1);
            nxtMonth = new DateTime(nxtMonth.Year, nxtMonth.Month,1);
            if(nxtMonth>startTime+span)
            {
                int mon = startTime.Month;
                if(this.ContainsKey(mon))
                {
                    re.AddRange((this[mon] as MonthTimeFile).GetDataFiles(startTime, span));
                }
            }
            else
            {
                int mon = startTime.Month;
                if (this.ContainsKey(mon))
                {
                    re.AddRange((this[mon] as MonthTimeFile).GetDataFiles(startTime, nxtMonth - startTime));
                }
                re.AddRange(GetDataFiles(nxtMonth, startTime+span - nxtMonth));
            }
            return re;
        }

19 Source : PriceHistoryPeriodHelperTests.cs
with MIT License
from centaurus-project

[Test]
        public void TrimTest()
        {
            var r = new Random();
            var periods = Enum.GetValues(typeof(PriceHistoryPeriod)).Cast<PriceHistoryPeriod>();
            foreach (var p in periods)
            {
                var minDate = GetMinDateForPeriod(p);
                for (var i = 0; i < 5; i++)
                {
                    var dateTime = minDate
                        .AddDays(r.Next(0, 1000))
                        .AddHours(r.Next(0, 24))
                        .AddMinutes(r.Next(0, 60))
                        .AddSeconds(r.Next(0, 60))
                        .AddMilliseconds(r.Next(0, 1000));
                    var trimmedDate = dateTime.Trim(p);
                    if (p == PriceHistoryPeriod.Month)
                    {
                        var date = default(DateTime);
                        while (date < trimmedDate)
                        {
                            date = date.AddMonths(1);
                        }
                        if (date == trimmedDate
                            && date.Day == 1
                            && date.Hour == 0
                            && date.Minute == 0
                            && date.Second == 0
                            && date.Millisecond == 0)
                            continue;
                    }
                    else
                    {
                        var date = minDate.Ticks;
                        while (date < trimmedDate.Ticks)
                            date += PriceHistoryPeriodHelper.TicksPerPeriod(p);
                        if (date == trimmedDate.Ticks)
                            continue;
                    }
                    replacedert.Fail($"Unable to trim {dateTime.Ticks} to {p} period.");
                }
            }
        }

19 Source : PriceHistoryPeriodHelper.cs
with MIT License
from centaurus-project

public static DateTime GetNextFrameDate(this DateTime dateTime, PriceHistoryPeriod period)
        {
            switch (period)
            {
                case PriceHistoryPeriod.Month:
                    return dateTime.AddMonths(1);
                default:
                    return dateTime.AddTicks(TicksPerPeriod(period));
            }
        }

19 Source : PriceHistoryPeriodHelper.cs
with MIT License
from centaurus-project

public static int GetDiff(this DateTime dateFrom, DateTime dateTo, PriceHistoryPeriod period)
        {
            if (dateFrom > dateTo)
            {
                throw new InvalidOperationException("Date from is greater than date to.");
            }

            switch (period)
            {
                case PriceHistoryPeriod.Month:
                    var totalDiff = 0;
                    while ((dateTo - dateFrom).TotalDays > 0)
                    {
                        dateFrom = dateFrom.AddMonths(1);
                        totalDiff++;
                    }
                    return totalDiff;
                default:
                    return (int)Math.Floor(decimal.Divide(dateTo.Ticks - dateFrom.Ticks, TicksPerPeriod(period)));
            }
        }

19 Source : Import.cs
with MIT License
from charlessolar

public static async Task Seed(IMessageHandlerContext ctx)
        {
            var addressFaker = new Faker<Types.Address>()
                .StrictMode(false)
                .Rules((f, o) =>
                {
                    o.AddressId = Guid.NewGuid();
                    o.Street = f.Address.StreetAddress();
                    o.City = f.Address.City();
                    o.State = f.Address.StateAbbr();
                    o.ZipCode = f.Address.ZipCode();
                    o.Country = "US";
                    o.Alias = o.City;
                });
            var paymentFaker = new Faker<Types.PaymentMethod>()
                .StrictMode(false)
                .Rules((f, o) =>
                {
                    o.PaymentMethodId = Guid.NewGuid();
                    o.CardholderName = f.Name.FindName(withPrefix: false, withSuffix: false);
                    o.CardNumber = f.Finance.CreditCardNumber();
                    o.Expiration = DateTime.UtcNow.AddMonths(2);
                    o.SecurityNumber = f.Finance.CreditCardCvv();
                    o.CardType = eShop.Ordering.Buyer.Enreplacedies.PaymentMethod.CardType.GetAll().RandomPick();
                    o.Alias = o.CardType.DisplayName;
                });

            // create buyers for all users
            Buyers = Idenreplacedy.Import.Users.Select(user =>
            {
                var address = addressFaker.Generate();
                var method = paymentFaker.Generate();

                return new Types.Buyer
                {
                    UserName = user.UserName,
                    GivenName = user.GivenName,
                    Address = address,
                    PaymentMethod = method
                };
            }).ToArray();

            var saga = ctx.Saga(Guid.NewGuid());

            foreach (var buyer in Buyers)
            {
                saga.Command(new eShop.Ordering.Buyer.Commands.Initiate
                {
                    GivenName = buyer.GivenName,
                    UserName = buyer.UserName
                }).Command(new eShop.Ordering.Buyer.Enreplacedies.Address.Commands.Add
                {
                    AddressId = buyer.Address.AddressId,
                    Street = buyer.Address.Street,
                    City = buyer.Address.City,
                    State = buyer.Address.State,
                    ZipCode = buyer.Address.ZipCode,
                    Country = buyer.Address.Country,
                    Alias = buyer.Address.Alias,
                    UserName = buyer.UserName
                }).Command(new eShop.Ordering.Buyer.Enreplacedies.PaymentMethod.Commands.Add
                {
                    PaymentMethodId = buyer.PaymentMethod.PaymentMethodId,
                    CardholderName = buyer.PaymentMethod.CardholderName,
                    CardNumber = buyer.PaymentMethod.CardNumber,
                    CardType = buyer.PaymentMethod.CardType,
                    Expiration = buyer.PaymentMethod.Expiration,
                    SecurityNumber = buyer.PaymentMethod.SecurityNumber,
                    Alias = buyer.PaymentMethod.Alias,
                    UserName = buyer.UserName
                }).Command(new eShop.Ordering.Buyer.Commands.SetPreferredAddress
                {
                    UserName = buyer.UserName,
                    AddressId = buyer.Address.AddressId
                }).Command(new eShop.Ordering.Buyer.Commands.SetPreferredPaymentMethod
                {
                    UserName = buyer.UserName,
                    PaymentMethodId = buyer.PaymentMethod.PaymentMethodId
                });
            }
            await saga.Start().ConfigureAwait(false);


            var saga2 = ctx.Saga(Guid.NewGuid());
            var random = new Random();
            // create orders out of all baskets
            foreach (var basket in Basket.Import.Baskets)
            {
                var buyer = Buyers.Single(x => x.UserName == basket.UserName);

                var orderid = Guid.NewGuid();
                saga2.Command(new eShop.Ordering.Order.Commands.Draft
                {
                    BasketId = basket.Id,
                    OrderId = orderid,
                    UserName = basket.UserName,
                    BillingAddressId = buyer.Address.AddressId,
                    ShippingAddressId = buyer.Address.AddressId,
                    PaymentMethodId = buyer.PaymentMethod.PaymentMethodId,
                    Stamp = DateTime.UtcNow.RandomDateTimeBackward(TimeSpan.FromDays(1), TimeSpan.FromDays(14)).ToUnix()
                });

                // Use random below to vary the status of generated orders
                if (random.Next(3) == 0)
                {
                    saga2.Command(new eShop.Ordering.Order.Commands.Cancel
                    {
                        OrderId = orderid
                    });
                    continue;
                }

                if (random.Next(2) != 0)
                    continue;

                saga2.Command(new eShop.Ordering.Order.Commands.Confirm
                {
                    OrderId = orderid
                });

                if (random.Next(2) != 0)
                    continue;

                saga2.Command(new eShop.Ordering.Order.Commands.Pay
                {
                    OrderId = orderid
                });

                if (random.Next(2) != 0)
                    continue;

                saga2.Command(new eShop.Ordering.Order.Commands.Ship
                {
                    OrderId = orderid
                });
            }
            await saga2.Start().ConfigureAwait(false);
        }

19 Source : Session.cs
with GNU General Public License v3.0
from ClusterM

private string FormatDirList(FileSystemEntry[] list)
        {
            int maxSizeChars = 0;
            foreach (FileSystemEntry entry in list)
            {
                maxSizeChars = Math.Max(maxSizeChars, entry.Size.ToString().Length);
            }

            DateTime sixMonthsAgo = EnsureUnixTime(DateTime.Now.ToUniversalTime().AddMonths(-6));

            StringBuilder result = new StringBuilder();
            foreach (FileSystemEntry entry in list)
            {
                char dirflag = (entry.IsDirectory ? 'd' : '-');
                string size = entry.Size.ToString().PadLeft(maxSizeChars);
                DateTime time = EnsureUnixTime(entry.LastModifiedTimeUtc);
                string timestr = MONTHS[time.Month - 1];
                if (time < sixMonthsAgo)
                    timestr += time.ToString(" dd  yyyy");
                else
                    timestr += time.ToString(" dd hh:mm");
                string mode = entry.Mode;

                if (string.IsNullOrEmpty(mode))
                    mode = dirflag + "rwxr--r--";

                result.AppendFormat("{0} 1 owner group {1} {2} {3}\r\n",
                                    mode, size, timestr, entry.Name);
            }

            return result.ToString();
        }

19 Source : DateTimeUtil.cs
with MIT License
from cocosip

public static DateTime GetLastDayOfMonth(DateTime time)
        {
            return new DateTime(time.Year, time.Month, 1).AddMonths(1).AddDays(-1);
        }

19 Source : ExpirationManagerFacts.cs
with MIT License
from codeyu

[Fact, CleanDatabase]
        public void Execute_Processes_JobTable()
        {
            var connection = ConnectionUtils.CreateConnection();
            connection.Job.Insert(new LiteJob
            {
                InvocationData = "",
                Arguments = "",
                CreatedAt = DateTime.UtcNow,
                ExpireAt = DateTime.UtcNow.AddMonths(-1),
            });
            var manager = CreateManager();
            manager.Execute(_token);
            var count = connection.Job.Count();
            replacedert.Equal(0, count);
        }

19 Source : ExpirationManagerFacts.cs
with MIT License
from codeyu

[Fact, CleanDatabase]
        public void Execute_Processes_ListTable()
        {
            var connection = ConnectionUtils.CreateConnection();
            connection.StateDataList.Insert(new LiteList
            {
                Id = ObjectId.NewObjectId(),
                Key = "key",
                ExpireAt = DateTime.UtcNow.AddMonths(-1)
            });
            var manager = CreateManager();
            manager.Execute(_token);
            var count = connection
                .StateDataList
                .Count();
            replacedert.Equal(0, count);
        }

19 Source : ExpirationManagerFacts.cs
with MIT License
from codeyu

[Fact, CleanDatabase]
        public void Execute_Processes_HashTable()
        {
            var connection = ConnectionUtils.CreateConnection();
            connection.StateDataHash.Insert(new LiteHash
            {
                Id = ObjectId.NewObjectId(),
                Key = "key",
                Field = "field",
                Value = "",
                ExpireAt = DateTime.UtcNow.AddMonths(-1)
            });
            var manager = CreateManager();
            manager.Execute(_token);
            var count = connection
                .StateDataHash
                .Count();
            replacedert.Equal(0, count);
        }

19 Source : ExpirationManagerFacts.cs
with MIT License
from codeyu

[Fact, CleanDatabase]
        public void Execute_RemovesOutdatedRecords()
        {
            var connection = ConnectionUtils.CreateConnection();
            CreateExpirationEntries(connection, DateTime.UtcNow.AddMonths(-1));
            var manager = CreateManager();
            manager.Execute(_token);
            replacedert.True(IsEntryExpired(connection));
        }

19 Source : ExpirationManagerFacts.cs
with MIT License
from codeyu

[Fact, CleanDatabase]
        public void Execute_DoesNotRemoveEntries_WithFreshExpirationTime()
        {
            var connection = ConnectionUtils.CreateConnection();
            CreateExpirationEntries(connection, DateTime.UtcNow.AddMonths(1));
            var manager = CreateManager();
            manager.Execute(_token);
            replacedert.False(IsEntryExpired(connection));
        }

19 Source : ExpirationManagerFacts.cs
with MIT License
from codeyu

[Fact, CleanDatabase]
        public void Execute_Processes_CounterTable()
        {
            var connection = ConnectionUtils.CreateConnection();
            connection.StateDataCounter.Insert(new Counter
            {
                Id = ObjectId.NewObjectId(),
                Key = "key",
                Value = 1L,
                ExpireAt = DateTime.UtcNow.AddMonths(-1)
            });
            var manager = CreateManager();
            manager.Execute(_token);
            var count = connection.StateDataCounter.Count();
            replacedert.Equal(0, count);
        }

19 Source : ExpirationManagerFacts.cs
with MIT License
from codeyu

[Fact, CleanDatabase]
        public void Execute_Processes_SetTable()
        {
            var connection = ConnectionUtils.CreateConnection();
            connection.StateDataSet.Insert(new LiteSet
            {
                Id = ObjectId.NewObjectId(),
                Key = "key",
                Score = 0,
                Value = "",
                ExpireAt = DateTime.UtcNow.AddMonths(-1)
            });
            var manager = CreateManager();
            manager.Execute(_token);
            var count = connection
                .StateDataSet
                .Count();
            replacedert.Equal(0, count);
        }

19 Source : ExpirationManagerFacts.cs
with MIT License
from codeyu

[Fact, CleanDatabase]
        public void Execute_Processes_AggregatedCounterTable()
        {
            var connection = ConnectionUtils.CreateConnection();
            connection.StateDataAggregatedCounter.Insert(new AggregatedCounter
            {
                Key = "key",
                Value = 1,
                ExpireAt = DateTime.UtcNow.AddMonths(-1)
            });
            var manager = CreateManager();
            manager.Execute(_token);
            replacedert.Equal(0, connection
                .StateDataCounter
                .Count());
        }

19 Source : AccountController.cs
with MIT License
from CoFlows

[HttpGet, HttpPost]
        public async Task<IActionResult> Logout()
        {
            string key = Request.Cookies["coflows"]; 
            if(key != null)
            {
                var outk = "";
                if(sessionKeys.ContainsKey(key))
                    sessionKeys.Remove(key, out outk);

                var _outk = "";
                if(revSessionKeys.ContainsKey(outk))
                    revSessionKeys.Remove(outk, out _outk);
            }

            Response.Cookies.Delete("coflows");  
            Response.Cookies.Append("coflows", "", new CookieOptions() { Expires = DateTime.Now.AddMonths(-24) });  

            try
            {
                string userName = this.User.QID();
                if (userName != null)
                {
                    QuantApp.Kernel.User quser = QuantApp.Kernel.User.FindUser(userName);
                    quser.SetSecure(false);
                }
            }
            finally
            {
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }

            

            return Ok();
        }

19 Source : ProductDiscountsIntegrationTests.cs
with Apache License 2.0
from commercetools

[Fact]
        public async Task UpdateProductDiscountSetValidUntil()
        {
            await WithUpdateableProductDiscount(client,
                DefaultProductDiscountDraft,
                async productDiscount =>
                {
                    var validUntil = DateTime.Today.AddMonths(5).ToUniversalTime();
                    var action = new SetValidUntilUpdateAction
                    {
                        ValidUntil = validUntil
                    };

                    var updatedProductDiscount = await client
                        .ExecuteAsync(productDiscount.UpdateById(actions => actions.AddUpdate(action)));

                    replacedert.Equal(validUntil, updatedProductDiscount.ValidUntil);
                    return updatedProductDiscount;
                });
        }

19 Source : ProductDiscountsIntegrationTests.cs
with Apache License 2.0
from commercetools

[Fact]
        public async Task UpdateProductDiscountSetValidFromAndUntil()
        {
            await WithUpdateableProductDiscount(client,
                DefaultProductDiscountDraft,
                async productDiscount =>
                {
                    var validFrom = DateTime.Today.AddDays(5).ToUniversalTime();
                    var validUntil = DateTime.Today.AddMonths(2).ToUniversalTime();
                    var action = new SetValidFromAndUntilUpdateAction
                    {
                        ValidFrom = validFrom,
                        ValidUntil = validUntil
                    };

                    var updatedProductDiscount = await client
                        .ExecuteAsync(productDiscount.UpdateById(actions => actions.AddUpdate(action)));

                    replacedert.Equal(validFrom, updatedProductDiscount.ValidFrom);
                    replacedert.Equal(validUntil, updatedProductDiscount.ValidUntil);
                    return updatedProductDiscount;
                });
        }

19 Source : TestingUtility.cs
with Apache License 2.0
from commercetools

public static PriceDraft GetRandomPriceDraft()
        {
            var randomAmount = RandomInt(1000, 10000);
            var priceDraft = GetPriceDraft(randomAmount, DateTime.Now, DateTime.Now.AddMonths(1));
            return priceDraft;
        }

19 Source : TestingUtility.cs
with Apache License 2.0
from commercetools

public static List<PriceDraft> GetRandomListOfPriceDraft(int count = 2)
        {
            var prices = new List<PriceDraft>();

            //first Add valid price for now
            prices.Add(GetPriceDraft(RandomInt(1000, 10000)));
            //then add future prices
            for (int i = 2; i <= count; i++)
            {
                prices.Add(GetPriceDraft(RandomInt(1000, 10000), DateTime.Now.AddMonths(i), DateTime.Now.AddMonths(i+1)));
            }

            return prices;
        }

19 Source : QueryPredicateTests.cs
with Apache License 2.0
from commercetools

[Fact]
        public void ExpressionWithDateTimeFilters()
        {
            
            DateTime startDate = DateTime.Parse("2020-11-21T15:27:55.123+02:00", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
            DateTime endDate = startDate.AddMonths(1);

            Expression<Func<Order, bool>> expression = x => x.CreatedAt >= startDate && x.CreatedAt <= endDate;
            IQueryPredicateExpressionVisitor queryPredicateExpressionVisitor = this.linqFixture.GetService<IQueryPredicateExpressionVisitor>();
            string result = queryPredicateExpressionVisitor.Render(expression);
            replacedert.Equal("createdAt >= \"2020-11-21T13:27:55.123Z\" and createdAt <= \"2020-12-21T13:27:55.123Z\"", result);
            
            Expression<Func<Order, bool>> expression2 = x => x.CreatedAt >= DateTime.Parse("2020-11-21T15:27:55.123+02:00", CultureInfo.GetCultureInfo("de-DE"), DateTimeStyles.AdjustToUniversal);
            string result2 = queryPredicateExpressionVisitor.Render(expression2);
            replacedert.Equal("createdAt >= \"2020-11-21T13:27:55.123Z\"", result2);
        }

19 Source : frmAttendanceStatistics.cs
with MIT License
from comsmobiler

private void Bind()
        {
            try
            {
                string[] Year = this.btnYear.Text.Split('��');           //���
                string[] Month = this.btnMonth.Text.Split('��');         //�·�             
                DataTable table = new DataTable();
                switch (btnMode)
                {
                    case 1:
                        //  this.gridATdata.TemplateControlName = "frmAttendanceStatisticsLayout";
                        gridATdata.Rows.Clear();    //�������ͳ���б�����
                        //��ȡij�¿����û�����
                        List<string> Users = AutofacConfig.attendanceService.GetUserNameByPeriod(Convert.ToDateTime(Year[0] + Month[0]).AddDays(-DateTime.Now.Day + 1), Convert.ToDateTime(Year[0] + Month[0]).AddDays(1 - DateTime.Now.Day).AddMonths(1));
                    if (Users.Count > 0)
                    {
                        table.Columns.Add("ID");                //�û�ID
                        table.Columns.Add("Pict");              //�û�ͷ��
                        table.Columns.Add("Name");              //�û�����
                        table.Columns.Add("Total");             //Ӧǩ������
                        table.Columns.Add("Al");                //׼ʱǩ������
                        table.Columns.Add("Late");              //�ٵ�����
                        table.Columns.Add("Early");             //���˴���
                        table.Columns.Add("No");                //δǩ����
                        foreach (string Row in Users)
                        {
                            MonthlyStatisticsDto Stat = AutofacConfig.attendanceService.GetUserMonthlyStatistics(Row, Convert.ToDateTime(Year[0] + Month[0]));
                            UserDetails UserDetail = new UserDetails();
                            UserDetailDto User = UserDetail.getUser(Row);
                                if (User != null)
                                {
                                    table.Rows.Add(User.U_ID, User.U_Portrait, User.U_Name, Stat.MS_AllCount, Stat.MS_InTimeCount, Stat.MS_ComeLateCount, Stat.MS_LeaveEarlyCount, Stat.MS_NoSignInCount + Stat.MS_NoSignOutCount);
                                }

                            }
                       
                        this.gridATdata.DataSource = table;
                        this.gridATdata.DataBind();
                    }
                      
                    break;
                    case 2:

                        //  this.gridATdata.TemplateControlName = "frmAttendanceStatDayLayout";
                        gridATdata1.Rows.Clear();    //�������ͳ���б�����
                        //��ȡij�¿�������
                        List<DateTime> listDate = AutofacConfig.attendanceService.GetDayOfMonthlyStatistics(UserID, Convert.ToDateTime(Year[0] + Month[0]));
                        if (listDate.Count > 0)
                        {
                            table.Columns.Add("Day");         //��Ҫǩ��������
                            foreach (DateTime Row in listDate)
                            {
                                string Time = Row.ToString("yyyy��M��d��    dddd", new System.Globalization.CultureInfo("zh-CN"));
                                table.Rows.Add(Time);
                            }
                           
                            this.gridATdata1.DataSource = table;
                            this.gridATdata1.DataBind();
                            
                        }
                        break;
                }
                
            }
            catch (Exception ex)
            {
                Toast(ex.Message);
            }
        }

19 Source : AssProcessRecordRepository.cs
with MIT License
from comsmobiler

public IQueryable<replacedProcessRecord> GetUserData(string Mode)
        {
            var q = _enreplacedies.Where(x => x.PROCESSMODE == 1 || x.PROCESSMODE == 3);
            DateTime StartDate = new DateTime();
            DateTime FinishDate = new DateTime();
            switch (Mode)
            {
                case "OM":
                    StartDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(-1);
                    FinishDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01")).AddDays(-1);
                    break;
                case "TM":
                    StartDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(-3);
                    FinishDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01")).AddDays(-1);
                    break;
                case "OY":
                    StartDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01")).AddYears(-1);
                    FinishDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01")).AddDays(-1);
                    break;
            }
            q = q.Where(x => x.CREATEDATE > StartDate && x.CREATEDATE < FinishDate);
            return q;
        }

19 Source : CoreCmsReportsController.cs
with Apache License 2.0
from CoreUnion

[HttpPost]
        [Description("换算前台时间按钮")]
        public JsonResult GetDateType([FromBody] FMIntId enreplacedy)
        {
            var jm = new AdminUiCallBack();

            if (enreplacedy.id <= 0)
            {
                jm.msg = "请选择合法的时间段";
                return Json(jm);
            }

            DateTime dt = DateTime.Now;  //当前时间  
            var start = "";
            var end = "";
            switch (enreplacedy.id)
            {
                case 1: //当天
                    start = dt.ToString("yyyy-MM-dd");
                    end = start;
                    break;
                case 2: //昨天
                    start = dt.AddDays(-1).ToString("yyyy-MM-dd");
                    end = start;
                    break;
                case 3: //本周
                    var startWeek = dt.AddDays(1 - Convert.ToInt32(dt.DayOfWeek.ToString("d")));  //本周周一  
                    var endWeek = startWeek.AddDays(6);  //本周周日  
                    start = startWeek.ToString("yyyy-MM-dd");
                    end = endWeek.ToString("yyyy-MM-dd");
                    break;
                case 4: //上周
                    var lastWeekStart = dt.AddDays(Convert.ToInt32(1 - Convert.ToInt32(dt.DayOfWeek)) - 7);
                    var lastWeekEnd = dt.AddDays(Convert.ToInt32(1 - Convert.ToInt32(dt.DayOfWeek)) - 7).AddDays(6);     //上周末(星期日) 
                    start = lastWeekStart.ToString("yyyy-MM-dd");
                    end = lastWeekEnd.ToString("yyyy-MM-dd");
                    break;
                case 5:  //本月
                    var startMonth = dt.AddDays(1 - dt.Day);  //本月月初  
                    var endMonth = startMonth.AddMonths(1).AddDays(-1);  //本月月末  
                    start = startMonth.ToString("yyyy-MM-dd");
                    end = endMonth.ToString("yyyy-MM-dd");
                    break;
                case 6:  //上月
                    start = DateTime.Parse(dt.ToString("yyyy-MM-01")).AddMonths(-1).ToString("yyyy-MM-dd");
                    end = DateTime.Parse(dt.ToString("yyyy-MM-01")).AddDays(-1).ToString("yyyy-MM-dd");
                    break;
                case 7: //最近7天
                    start = dt.AddDays(-7).ToString("yyyy-MM-dd");
                    end = dt.Date.ToString("yyyy-MM-dd");
                    break;
                case 8: //最近一月
                    start = dt.AddMonths(-1).AddDays(1).ToString("yyyy-MM-dd");
                    end = dt.Date.ToString("yyyy-MM-dd");
                    break;
                case 9: //最近3月
                    start = dt.AddMonths(-3).AddDays(1).ToString("yyyy-MM-dd");
                    end = dt.Date.ToString("yyyy-MM-dd");
                    break;
                case 10: //最近6个月
                    start = dt.AddMonths(-6).AddDays(1).ToString("yyyy-MM-dd");
                    end = dt.Date.ToString("yyyy-MM-dd");
                    break;
                case 11: //最近一年
                    start = dt.AddMonths(-12).AddDays(1).ToString("yyyy-MM-dd");
                    end = dt.Date.ToString("yyyy-MM-dd");
                    break;
                case 12: //本年度
                    start = DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).ToString("yyyy-MM-dd");
                    end = DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).AddYears(1).AddDays(-1).ToString("yyyy-MM-dd");
                    break;
                case 13: //上年度
                    start = DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).AddYears(-1).ToString("yyyy-MM-dd");
                    end = DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).AddDays(-1).ToString("yyyy-MM-dd");
                    break;
                default:
                    jm.msg = "没有此时间维度";
                    break;
            }

            jm.code = 0;
            jm.data = new
            {
                start,
                end
            };
            return Json(jm);

        }

19 Source : RollingIntervalExtensions.cs
with Apache License 2.0
from cosmos-loops

public static DateTime? GetNextCheckpoint(this RollingInterval interval, DateTime instant) {
            var current = GetCurrentCheckpoint(interval, instant);
            if (current == null)
                return null;

            switch (interval) {
                case RollingInterval.Year:
                    return current.Value.AddYears(1);
                case RollingInterval.Month:
                    return current.Value.AddMonths(1);
                case RollingInterval.Day:
                    return current.Value.AddDays(1);
                case RollingInterval.Hour:
                    return current.Value.AddHours(1);
                case RollingInterval.Minute:
                    return current.Value.AddMinutes(1);
                default:
                    throw new ArgumentException("Invalid rolling interval");
            }
        }

19 Source : PeriodMonthSplitter.cs
with BSD 2-Clause "Simplified" License
from countincognito

protected override DateTime Increase(DateTime dateTime, int value)
        {
            return dateTime.AddMonths(value);
        }

19 Source : LastDayValueGenerator.cs
with MIT License
from craigbridges

public override object GenerateValue()
        {
            var today = DateTime.Today;

            switch (_period)
            {
                case DatePeriod.Year:

                    return new DateTime
                    (
                        today.Year,
                        12,
                        31
                    );

                case DatePeriod.Month:

                    var startDate = new DateTime
                    (
                        today.Year,
                        today.Month,
                        1
                    );

                    var endDate = startDate.AddMonths(1).AddDays(-1);

                    return endDate;

                default:
                    return today.EndOfWeek
                    (
                        _firstDayOfWeek
                    );
            }
        }

19 Source : DateTimeExtensions.cs
with Apache License 2.0
from crazyants

public static DateTime GetLastDayOfMonth(this DateTime date)
        {
            DateTime dtTo = date;
            dtTo = dtTo.AddMonths(1);
            dtTo = dtTo.AddDays(-(dtTo.Day));
            return dtTo;
        }

19 Source : DateExtensions.cs
with Apache License 2.0
from cs-util-com

public static int MonthDifference(this DateTime startDate, DateTime endDate)
        {
            // https://stackoverflow.com/a/1526116/3286260

            int compMonth = (endDate.Month + endDate.Year * 12) - (startDate.Month + startDate.Year * 12);
            double daysInEndMonth = (endDate - endDate.AddMonths(1)).Days;
            double months = compMonth + (startDate.Day - endDate.Day) / daysInEndMonth;

            return Convert.ToInt32(Math.Truncate(months));
        }

19 Source : DateScroller.cs
with MIT License
from cschladetsch

protected DateTime CopyTimePeriods(DateTime value, Precision precision)
		{
			switch (precision)
			{
				case Precision.Years:
					value = value.AddYears(Date.Year - value.Year);
					return value;
				case Precision.Months:
					value = value.AddYears(Date.Year - value.Year);
					value = value.AddMonths(Date.Month - value.Month);
					return value;
				case Precision.Days:
					value = value.AddYears(Date.Year - value.Year);
					value = value.AddMonths(Date.Month - value.Month);
					value = value.AddDays(Date.Day - value.Day);
					return value;
				case Precision.Hours:
					value = value.AddYears(Date.Year - value.Year);
					value = value.AddMonths(Date.Month - value.Month);
					value = value.AddDays(Date.Day - value.Day);

					value = value.AddHours(Date.Hour - value.Hour);
					return value;
				case Precision.Minutes:
					value = value.AddYears(Date.Year - value.Year);
					value = value.AddMonths(Date.Month - value.Month);
					value = value.AddDays(Date.Day - value.Day);

					value = value.AddHours(Date.Hour - value.Hour);
					value = value.AddMinutes(Date.Minute - value.Minute);
					return value;
				case Precision.Seconds:
					value = value.AddYears(Date.Year - value.Year);
					value = value.AddMonths(Date.Month - value.Month);
					value = value.AddDays(Date.Day - value.Day);

					value = value.AddHours(Date.Hour - value.Hour);
					value = value.AddMinutes(Date.Minute - value.Minute);
					value = value.AddSeconds(Date.Second - value.Second);
					return value;
				case Precision.Milliseconds:
					value = value.AddYears(Date.Year - value.Year);
					value = value.AddMonths(Date.Month - value.Month);
					value = value.AddDays(Date.Day - value.Day);

					value = value.AddHours(Date.Hour - value.Hour);
					value = value.AddMinutes(Date.Minute - value.Minute);
					value = value.AddSeconds(Date.Second - value.Second);

					value = value.AddMilliseconds(Date.Millisecond - value.Millisecond);
					return value;
				case Precision.Ticks:
					return Date;
			}

			return value;
		}

19 Source : CalendarBase.cs
with MIT License
from cschladetsch

public virtual void PrevMonth()
		{
			if (!IsInteractable())
			{
				return;
			}

			DateDisplay = DateDisplay.AddMonths(-1);
		}

19 Source : CalendarBase.cs
with MIT License
from cschladetsch

public virtual void NextMonth()
		{
			if (!IsInteractable())
			{
				return;
			}

			DateDisplay = DateDisplay.AddMonths(1);
		}

19 Source : DateScroller.cs
with MIT License
from cschladetsch

protected virtual DateTime LoopedMonths(int steps)
		{
			var value = Date;
			var step = MonthsStep;
			var increase = steps > 0;
			if (!increase)
			{
				steps = -steps;
				step = -step;
			}

			if (!IndependentScroll)
			{
				return LoopedDate(value, steps, x => x.AddMonths(step));
			}

			for (int i = 0; i < steps; i++)
			{
				value = value.AddMonths(step);
				value = CopyTimePeriods(value, Precision.Years);

				var new_months = value.Month;
				if (DateTimeEquals(Date, DateMin, Precision.Years) && (new_months < DateMin.Month))
				{
					new_months = increase ? DateMax.Month : Mathf.Max(DateMin.Month, 12 - MonthsStep);
				}

				if (DateTimeEquals(Date, DateMax, Precision.Years) && (new_months > DateMax.Month))
				{
					new_months = increase ? DateMin.Month : Mathf.Min(DateMax.Month, 12 - MonthsStep);
				}

				if (value.Month != new_months)
				{
					value = value.AddMonths(new_months - value.Month);
				}
			}

			return value;
		}

19 Source : MethodsTests.cs
with MIT License
from CurlyBraceTT

[Fact]
        public async Task Orders()
        {
            var orders = await _client.GetCompletedOrders(new GetCompletedOrdersParameters
            {
                AppSignature = AppSignature,
                StartDate = DateTime.Now.AddMonths(-1),
                EndDate = DateTime.Now,
                LiveOrderStatus = "pay",
                PageNo = 1,
                PageSize = 15
            });

            if(orders.TotalResults > 0)
            {
                var statusOrders = await _client.GetOrderStatus(new GetOrderStatusParameters
                {
                    AppSignature = AppSignature,
                    OrderNumbers = string.Join(",", orders.Orders.Select(order => order.OrderNumber))
                });

                replacedert.True(statusOrders.TotalResults > 0);

                var status = await _client.GetOrderStatus(new GetOrderStatusParameters
                {
                    AppSignature = AppSignature,
                    OrderNumbers = string.Join(",", orders.Orders.Select(order => order.OrderNumber))
                });
                replacedert.True(status.TotalResults > 0);

                var items = await _client.GereplacedemByOrderNumbers(new GereplacedemByOrderNumbersParameters 
                {
                    AppSignature = AppSignature,
                    OrderNumbers = string.Join(",", orders.Orders.Select(order => order.OrderNumber))
                });
                replacedert.True(items.TotalResults > 0);
            }

            // replacedert if no exceptions
            replacedert.True(true);
        }

19 Source : EntityToType.cs
with MIT License
from CXuesong

public static IEnumerable<Range<DateTime>> Interpret(DateTimeResolution resolution, DateTime now, Calendar calendar, CalendarWeekRule rule, DayOfWeek firstDayOfWeek, Func<DayPart, int> HourFor)
        {
            // remove any millisecond components
            now = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Kind);

            switch (resolution.Reference)
            {
                case Reference.PAST_REF:
                    yield return Range.From(DateTime.MinValue, now);
                    yield break;
                case Reference.PRESENT_REF:
                    yield return Range.From(now, now);
                    yield break;
                case Reference.FUTURE_REF:
                    yield return Range.From(now, DateTime.MaxValue);
                    yield break;
                case null:
                    break;
                default:
                    throw new NotImplementedException();
            }

            var start = now;

            // TODO: maybe clamp to prevent divergence
            while (start < DateTime.MaxValue)
            {
                var after = start;

                while (true)
                {
                    // for each date component in decreasing order of significance:
                    // if it's not a variable (-1) or missing (null) component, then
                    //      add a unit of that component to "start"
                    //      round down to the component's granularity
                    //      calculate the "after" based on the size of that component

                    if (resolution.Year >= 0)
                    {
                        bool need = start.Year != resolution.Year;
                        if (need)
                        {
                            start = start.AddYears(1);
                            start = new DateTime(start.Year, 1, 1, 0, 0, 0, 0, start.Kind);
                        }

                        if (start.Year > resolution.Year)
                        {
                            yield break;
                        }

                        after = start.AddYears(1);

                        if (need)
                        {
                            continue;
                        }
                    }

                    if (resolution.Month >= 0)
                    {
                        bool need = start.Month != resolution.Month;
                        if (need)
                        {
                            start = start.AddMonths(1);
                            start = new DateTime(start.Year, start.Month, 1, 0, 0, 0, 0, start.Kind);
                        }

                        after = start.AddMonths(1);
                        if (need)
                        {
                            continue;
                        }
                    }

                    var week = calendar.GetWeekOfYear(start, rule, firstDayOfWeek);
                    if (resolution.Week >= 0)
                    {
                        bool need = week != resolution.Week;
                        if (need)
                        {
                            start = start.AddDays(7);
                            start = new DateTime(start.Year, start.Month, start.Day, 0, 0, 0, 0, start.Kind);

                            while (start.DayOfWeek != firstDayOfWeek)
                            {
                                start = start.AddDays(-1);
                            }
                        }

                        after = start.AddDays(7);
                        if (need)
                        {
                            continue;
                        }
                    }

                    if (resolution.DayOfWeek != null)
                    {
                        bool need = start.DayOfWeek != resolution.DayOfWeek;
                        if (need)
                        {
                            start = start.AddDays(1);
                            start = new DateTime(start.Year, start.Month, start.Day, 0, 0, 0, 0, start.Kind);
                        }

                        after = start.AddDays(1);
                        if (need)
                        {
                            continue;
                        }
                    }

                    if (resolution.Day >= 0)
                    {
                        bool need = start.Day != resolution.Day;
                        if (need)
                        {
                            start = start.AddDays(1);
                            start = new DateTime(start.Year, start.Month, start.Day, 0, 0, 0, 0, start.Kind);
                        }

                        after = start.AddDays(1);
                        if (need)
                        {
                            continue;
                        }
                    }

                    if (resolution.DayPart != null)
                    {
                        var hourStart = HourFor(resolution.DayPart.Value);
                        var hourAfter = HourFor(resolution.DayPart.Value.Next());
                        var hourDelta = hourAfter - hourStart;
                        if (hourDelta < 0)
                        {
                            hourDelta += 24;
                        }

                        bool need = start.Hour != hourStart;
                        if (need)
                        {
                            start = start.AddHours(1);
                            start = new DateTime(start.Year, start.Month, start.Day, start.Hour, 0, 0, 0, start.Kind);
                        }

                        after = start.AddHours(hourDelta);
                        if (need)
                        {
                            continue;
                        }
                    }

                    if (resolution.Hour >= 0)
                    {
                        bool need = start.Hour != resolution.Hour;
                        if (need)
                        {
                            start = start.AddHours(1);
                            start = new DateTime(start.Year, start.Month, start.Day, start.Hour, 0, 0, 0, start.Kind);
                        }

                        after = start.AddHours(1);
                        if (need)
                        {
                            continue;
                        }
                    }

                    if (resolution.Minute >= 0)
                    {
                        bool need = start.Minute != resolution.Minute;
                        if (need)
                        {
                            start = start.AddMinutes(1);
                            start = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, 0, 0, start.Kind);
                        }

                        after = start.AddMinutes(1);
                        if (need)
                        {
                            continue;
                        }
                    }

                    if (resolution.Second >= 0)
                    {
                        bool need = start.Second != resolution.Second;
                        if (need)
                        {
                            start = start.AddSeconds(1);
                            start = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, start.Second, 0, start.Kind);
                        }

                        after = start.AddSeconds(1);
                        if (need)
                        {
                            continue;
                        }
                    }

                    // if all of the components were variable or missing,
                    // then in order of increasing component granularity,
                    // if the component is variable rather than missing, then increment by that granularity
                    if (start == after)
                    {
                        if (resolution.Second < 0)
                        {
                            after = start.AddSeconds(1);
                        }
                        else if (resolution.Minute < 0)
                        {
                            after = start.AddMinutes(1);
                        }
                        else if (resolution.Hour < 0)
                        {
                            after = start.AddHours(1);
                        }
                        else if (resolution.Day < 0)
                        {
                            after = start.AddDays(1);
                        }
                        else if (resolution.Week < 0)
                        {
                            after = start.AddDays(7);
                        }
                        else if (resolution.Month < 0)
                        {
                            after = start.AddMonths(1);
                        }
                        else if (resolution.Year < 0)
                        {
                            after = start.AddYears(1);
                        }
                        else
                        {
                            // a second is our minimum granularity
                            after = start.AddSeconds(1);
                        }
                    }

                    if (start >= now)
                    {
                        yield return new Range<DateTime>(start, after);
                    }

                    start = after;
                }
            }
        }

19 Source : Program.cs
with MIT License
from dahall

internal static void EditorTest(TaskService ts, TextWriter output, params string[] arg)
		{
			try
			{
				const string taskName = "Test";
				string Converter(DateTime dt) => dt == DateTime.MinValue || dt == DateTime.MaxValue ? "Never" : dt.ToString();

				var td = arg.Length > 0 && arg[0] != null ? ts.FindTask(arg[0])?.Definition : null;
				if (td == null)
				{
					// Create a new task definition and replacedign properties
					td = ts.NewTask();
					td.RegistrationInfo.Description = "Test for editor\r\n\r\nLine 2";
					//td.RegistrationInfo.Author = "incaunu";
					td.Triggers.Add(new TimeTrigger());
					td.Triggers.Add(new DailyTrigger { StartBoundary = DateTime.Now + TimeSpan.FromSeconds(5), EndBoundary = DateTime.Today.AddMonths(1) });
					/*EventTrigger eTrig = new EventTrigger("Security", "VSSAudit", 25);
					eTrig.ValueQueries.Add("Name", "Value");
					td.Triggers.Add(eTrig);*/
					td.Actions.PowerShellConversion = PowerShellActionPlatformOption.All;
					td.Actions.Add("cmd.exe", "/c \"date /t > c:\\cmd.txt\"");
					td.Actions.Add(new ShowMessageAction("x", "y"));
					//EmailAction ea = (EmailAction)td.Actions.Add(new EmailAction("Hi", "[email protected]", "[email protected]; [email protected]", "<p>How you been?</p>", "smtp.codeplex.com"));
					//ea.HeaderFields.Add("reply-to", "[email protected]");
					//ea.Attachments = new object[] { (string)new TemporaryScopedFile(), (string)new TemporaryScopedFile() };
					//WriteXml(td, taskName);
					//using (var op = new TaskOptionsEditor(t, true, false))
					//	if (op.ShowDialog() == DialogResult.OK) td = op.TaskDefinition;
					//Task t = ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, "system", null, TaskLogonType.ServiceAccount);
					//WriteXml(t);
				}

				/*using (var ad = new ActionEditDialog { AvailableActions = AvailableActions.Execute | AvailableActions.ComHandler | AvailableActions.ShowMessage })
				{
					// Test unavailable action
					try { ad.Action = new EmailAction(); } catch { output.Write("ActionEditDialog: Successfully caught expected exception."); }
					// Test available action
					ad.Action = new ComHandlerAction() { ClreplacedId = Guid.NewGuid() };
					ad.ShowDialog();
					// Add available and test
					ad.AvailableActions |= AvailableActions.SendEmail;
					ad.Action = new EmailAction();
					ad.ShowDialog();
					// Make current type unavailable and test
					ad.AvailableActions = AvailableActions.Execute | AvailableActions.ComHandler;
					ad.ShowDialog();
					return;
				}

				using (var tdlg = new TriggerEditDialog { AvailableTriggers = (AvailableTriggers.AllTriggers & ~AvailableTriggers.Boot) })
				{
					// Test unavailable trigger
					try { tdlg.Trigger = new BootTrigger(); } catch { output.Write("TriggerEditDialog: Successfully caught expected exception."); }
					// Test available trigger
					tdlg.Trigger = new MonthlyTrigger();
					tdlg.ShowDialog();
					// Add available and test
					tdlg.AvailableTriggers |= AvailableTriggers.Boot;
					tdlg.Trigger = new BootTrigger();
					tdlg.ShowDialog();
					// Make current type unavailable and test
					tdlg.AvailableTriggers = AvailableTriggers.Weekly | AvailableTriggers.Monthly | AvailableTriggers.SessionStateChange;
					tdlg.ShowDialog();
					return;
				}*/

				// Register then show task again
				//editorForm = new TaskEditDialog(ts, td, true, true)
				var task = ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
				if (editorForm == null)
				{
					editorForm = new TaskEditDialog(task, true, true)
					{
						AvailableTabs = AvailableTaskTabs.All,
						//AvailableActions = AvailableActions.ComHandler | AvailableActions.Execute,
						//AvailableTriggers = AvailableTriggers.Daily | AvailableTriggers.Weekly,
						TaskName = "Test",
						TaskNameIsEditable = false,
						ShowActionRunButton = true,
						ShowConvertActionsToPowerShellCheck = true
					};
				}
				else
					editorForm.Task = task;
				if (ts.HighestSupportedVersion >= new Version(1, 2)) editorForm.TaskFolder = @"\Microsoft";
				if (editorForm.ShowDialog() == DialogResult.OK)
				{
					var t = editorForm.Task;
					while (DisplayTask(t, true) != null)
					{
						t = editorForm.Task;
						output.Write($"***********************\r\nName: {t.Name}\r\nEnabled: {t.Enabled}\r\nLastRunTime: {Converter(t.LastRunTime)}\r\nState: {t.State}\r\nIsActive: {t.IsActive}\r\n" +
							$"Registered: {t.GetLastRegistrationTime()}\r\nNextRunTime: {Converter(t.NextRunTime)}\r\n");
						if (t.Definition.Triggers.Count > 0)
							output.Write($"TriggerStart: {Converter(t.Definition.Triggers[0].StartBoundary)}\r\nTriggerEnd: {Converter(t.Definition.Triggers[0].EndBoundary)}\r\n");
					}

					// Remove the task we just created
					t.Folder.DeleteTask(taskName, false);
				}
			}
			catch (Exception ex)
			{
				output.WriteLine(ex.ToString());
			}
		}

19 Source : ValidityPeriodClientServerAuthTests.cs
with MIT License
from damienbod

private (X509Certificate2 root, X509Certificate2 intermediate, X509Certificate2 server, X509Certificate2 client) SetupCerts()
        {
            var serviceProvider = new ServiceCollection()
                .AddCertificateManager()
                .BuildServiceProvider();

            var createClientServerAuthCerts = serviceProvider.GetService<CreateCertificatesClientServerAuth>();

            var rootCaL1 = createClientServerAuthCerts.NewRootCertificate(
                new DistinguishedName { CommonName = "root dev", Country = "IT" },
                new ValidityPeriod { ValidFrom = DateTime.UtcNow.AddMonths(3), ValidTo = DateTime.UtcNow.AddMonths(6) },
                3, "localhost");
            rootCaL1.FriendlyName = "developement root L1 certificate";

            // Intermediate L2 chained from root L1
            var intermediateCaL2 = createClientServerAuthCerts.NewIntermediateChainedCertificate(
                new DistinguishedName { CommonName = "intermediate dev", Country = "FR" },
                new ValidityPeriod { ValidFrom = DateTime.UtcNow.AddMonths(2), ValidTo = DateTime.UtcNow.AddYears(1) },
                2, "localhost", rootCaL1);
            intermediateCaL2.FriendlyName = "developement Intermediate L2 certificate";

            // Server, Client L3 chained from Intermediate L2
            var serverL3 = createClientServerAuthCerts.NewServerChainedCertificate(
                new DistinguishedName { CommonName = "server", Country = "DE" },
                new ValidityPeriod { ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10) },
                "localhost", intermediateCaL2);

            var clientL3 = createClientServerAuthCerts.NewClientChainedCertificate(
                new DistinguishedName { CommonName = "client", Country = "IE" },
                new ValidityPeriod { ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10) },
                "localhost", intermediateCaL2);
            serverL3.FriendlyName = "developement server L3 certificate";
            clientL3.FriendlyName = "developement client L3 certificate";

            return (rootCaL1, intermediateCaL2, serverL3, clientL3);
        }

19 Source : AuditTrailProvider.cs
with MIT License
from damienbod

private void CreateAliasForLastNIndices(int amount)
        {
            var responseCatIndices = _elasticClient.Cat.Indices(new CatIndicesRequest(Indices.Parse($"{_alias}-*")));
            var records = responseCatIndices.Records.ToList();
            List<string> indicesToAddToAlias = new List<string>();
            for(int i = amount;i>0;i--)
            {
                if (_options.Value.IndexPerMonth)
                {
                    var indexName = $"{_alias}-{DateTime.UtcNow.AddMonths(-i + 1).ToString("yyyy-MM")}";
                    if(records.Exists(t => t.Index == indexName))
                    {
                        indicesToAddToAlias.Add(indexName);
                    }
                }
                else
                {
                    var indexName = $"{_alias}-{DateTime.UtcNow.AddDays(-i + 1).ToString("yyyy-MM-dd")}";                   
                    if (records.Exists(t => t.Index == indexName))
                    {
                        indicesToAddToAlias.Add(indexName);
                    }
                }
            }

            var response = _elasticClient.Indices.AliasExists(new AliasExistsRequest(new Names(new List<string> { _alias })));
            //if (!response.IsValid)
            //{
            //    throw response.OriginalException;
            //}

            if (response.Exists)
            {
                _elasticClient.Indices.DeleteAlias(new DeleteAliasRequest(Indices.Parse($"{_alias}-*"), _alias));
            }

            Indices multipleIndicesFromStringArray = indicesToAddToAlias.ToArray();
            var responseCreateIndex = _elasticClient.Indices.PutAlias(new PutAliasRequest(multipleIndicesFromStringArray, _alias));
            if (!responseCreateIndex.IsValid)
            {
                throw responseCreateIndex.OriginalException;
            }
        }

19 Source : AuditTrailProvider.cs
with MIT License
from damienbod

private void EnsureAlias()
        {
            if (_options.Value.IndexPerMonth)
            {
                if (aliasUpdated.Date < DateTime.UtcNow.AddMonths(-1).Date)
                {
                    aliasUpdated = DateTime.UtcNow;
                    CreateAlias();
                }
            }
            else
            {
                if (aliasUpdated.Date < DateTime.UtcNow.AddDays(-1).Date)
                {
                    aliasUpdated = DateTime.UtcNow;
                    CreateAlias();
                }
            }           
        }

19 Source : Schedule.cs
with GNU General Public License v3.0
from darakeon

public virtual Int32 PreviewSumAt(Account account, Int16 dateYear, Int16 dateMonth)
		{
			var firstMonthDay = new DateTime(dateYear, dateMonth, 1);
			var firstNextMonthDay = firstMonthDay.AddMonths(1);
			var lastMonthDay = firstNextMonthDay.AddDays(-1);

			var begin = LastDateRun();
			if (begin > lastMonthDay)
				return 0;

			var end = Boundless ? firstNextMonthDay : add(Times - 1);
			if (end < firstMonthDay)
				return 0;

			switch (Frequency)
			{
				case ScheduleFrequency.Yearly:
					return Month == dateMonth ? ValueCents : 0;

				case ScheduleFrequency.Monthly:
					return ValueCents;

				case ScheduleFrequency.Daily:
					{
						if (begin < firstMonthDay)
							begin = firstMonthDay;

						if (end > lastMonthDay)
							end = lastMonthDay;

						return ValueCents * (end.Day - begin.Day + 1);
					}

				default:
					throw new ArgumentException("frequency");
			}
		}

19 Source : DateExtension.cs
with GNU General Public License v3.0
from darakeon

private static DateTime addByFrequency(this DateTime start, String frequency, Int32 qty)
		{
			switch (frequency)
			{
				case "day":
					return start.AddDays(qty);
				case "month":
					return start.AddMonths(qty);
				case "year":
					return start.AddYears(qty);
				default:
					throw new NotImplementedException();
			}
		}

See More Examples