System.DateTime.AddYears(int)

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

695 Examples 7

19 Source : CalendarMonth.razor.cs
with MIT License
from BlazorFluentUI

protected Task OnSelectYear(int selectedYear)
        {
            focusOnUpdate = true;
            int navYear = NavigatedDate.Year;
            if (navYear != selectedYear)
            {
                DateTime newNavDate = new(NavigatedDate.Year, NavigatedDate.Month, NavigatedDate.Day);
                newNavDate = newNavDate.AddYears(selectedYear - newNavDate.Year);
                if (newNavDate > MaxDate)
                {
                    newNavDate = newNavDate.AddMonths(MaxDate.Month - newNavDate.Month);
                }
                else if (newNavDate < MinDate)
                {
                    newNavDate = newNavDate.AddMonths(MinDate.Month - newNavDate.Month);
                }
                OnNavigateDate.InvokeAsync(new NavigatedDateResult { Date = newNavDate, FocusOnNavigatedDay = true });
            }
            IsYearPickerVisible = false;
            return Task.CompletedTask;
        }

19 Source : CalendarMonth.razor.cs
with MIT License
from BlazorFluentUI

protected Task OnSelectPrevYear()
        {
            return OnNavigateDate.InvokeAsync(new NavigatedDateResult { Date = NavigatedDate.AddYears(-1), FocusOnNavigatedDay = false });
        }

19 Source : CalendarMonth.razor.cs
with MIT License
from BlazorFluentUI

protected Task OnSelectNextYear()
        {
            return OnNavigateDate.InvokeAsync(new NavigatedDateResult { Date = NavigatedDate.AddYears(+1), FocusOnNavigatedDay = false });
        }

19 Source : CSky_DateTime.cs
with MIT License
from bmjoy

private System.DateTime GetDateTime()
        {

            if (!m_SyncWithSystem)
            {
                // Create new DateTime.
                System.DateTime dateTime = new System.DateTime(0, System.DateTimeKind.Utc);

                // Add date and time in DateTime.
                dateTime = dateTime.AddYears(m_Year - 1).AddMonths(m_Month - 1).AddDays(m_Day - 1).AddHours(m_Timeline);

                // Set date.
                m_Year  = dateTime.Year;
                m_Month = dateTime.Month;
                m_Day   = dateTime.Day;

                // Set timeline.
                m_Timeline = CSky_DateTimeHelper.TimeToFloat(dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);

                return dateTime;
            }

            return System.DateTime.Now; // System date time.
        }

19 Source : StrictEntityToType.cs
with MIT License
from BotBuilderCommunity

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 : SimpleHttpServer.cs
with MIT License
from bp2008

public static X509Certificate2 GetSelfSignedCertificate()
		{
			lock (certCreateLock)
			{
				X509Certificate2 ssl_certificate;
				string exePath = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
				FileInfo fiExe = new FileInfo(exePath);
				FileInfo fiCert = new FileInfo(fiExe.Directory.FullName + "\\SimpleHttpServer-SslCert.pfx");
				if (fiCert.Exists)
					ssl_certificate = new X509Certificate2(fiCert.FullName, "N0t_V3ry-S3cure#lol");
				else
				{
					using (Pluralsight.Crypto.CryptContext ctx = new Pluralsight.Crypto.CryptContext())
					{
						ctx.Open();

						ssl_certificate = ctx.CreateSelfSignedCertificate(
							new Pluralsight.Crypto.SelfSignedCertProperties
							{
								IsPrivateKeyExportable = true,
								KeyBitLength = 4096,
								Name = new X500DistinguishedName("cn=localhost"),
								ValidFrom = DateTime.Today.AddDays(-1),
								ValidTo = DateTime.Today.AddYears(100),
							});

						byte[] certData = ssl_certificate.Export(X509ContentType.Pfx, "N0t_V3ry-S3cure#lol");
						File.WriteAllBytes(fiCert.FullName, certData);
					}
				}
				return ssl_certificate;
			}
		}

19 Source : AppService.cs
with MIT License
from btcpayserver

private async Task<ViewCrowdfundViewModel> GetInfo(AppData appData)
        {
            var settings = appData.GetSettings<CrowdfundSettings>();
            var resetEvery = settings.StartDate.HasValue ? settings.ResetEvery : CrowdfundResetEvery.Never;
            DateTime? lastResetDate = null;
            DateTime? nextResetDate = null;
            if (resetEvery != CrowdfundResetEvery.Never)
            {
                lastResetDate = settings.StartDate.Value;

                nextResetDate = lastResetDate.Value;
                while (DateTime.Now >= nextResetDate)
                {
                    lastResetDate = nextResetDate;
                    switch (resetEvery)
                    {
                        case CrowdfundResetEvery.Hour:
                            nextResetDate = lastResetDate.Value.AddHours(settings.ResetEveryAmount);
                            break;
                        case CrowdfundResetEvery.Day:
                            nextResetDate = lastResetDate.Value.AddDays(settings.ResetEveryAmount);
                            break;
                        case CrowdfundResetEvery.Month:
                            nextResetDate = lastResetDate.Value.AddMonths(settings.ResetEveryAmount);
                            break;
                        case CrowdfundResetEvery.Year:
                            nextResetDate = lastResetDate.Value.AddYears(settings.ResetEveryAmount);
                            break;
                    }
                }
            }

            var invoices = await GetInvoicesForApp(appData, lastResetDate);
            var completeInvoices = invoices.Where(enreplacedy => enreplacedy.Status == InvoiceStatusLegacy.Complete || enreplacedy.Status == InvoiceStatusLegacy.Confirmed).ToArray();
            var pendingInvoices = invoices.Where(enreplacedy => !(enreplacedy.Status == InvoiceStatusLegacy.Complete || enreplacedy.Status == InvoiceStatusLegacy.Confirmed)).ToArray();
            var paidInvoices = invoices.Where(enreplacedy => enreplacedy.Status == InvoiceStatusLegacy.Complete || enreplacedy.Status == InvoiceStatusLegacy.Confirmed || enreplacedy.Status == InvoiceStatusLegacy.Paid).ToArray();

            var pendingPayments = GetContributionsByPaymentMethodId(settings.TargetCurrency, pendingInvoices, !settings.EnforceTargetAmount);
            var currentPayments = GetContributionsByPaymentMethodId(settings.TargetCurrency, completeInvoices, !settings.EnforceTargetAmount);

            var perkCount = paidInvoices
                .Where(enreplacedy => !string.IsNullOrEmpty(enreplacedy.Metadata.ItemCode))
                .GroupBy(enreplacedy => enreplacedy.Metadata.ItemCode)
                .ToDictionary(enreplacedies => enreplacedies.Key, enreplacedies => enreplacedies.Count());
            
            Dictionary<string, decimal> perkValue = new Dictionary<string, decimal>();
            if (settings.DisplayPerksValue)
            {
                perkValue = paidInvoices
                    .Where(enreplacedy => enreplacedy.Currency.Equals(settings.TargetCurrency, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(enreplacedy.Metadata.ItemCode))
                    .GroupBy(enreplacedy => enreplacedy.Metadata.ItemCode)
                    .ToDictionary(enreplacedies => enreplacedies.Key, enreplacedies => 
                        enreplacedies.Sum(enreplacedy => enreplacedy.GetPayments(true).Sum(pay =>
                        {
                            var paymentMethodId = pay.GetPaymentMethodId();
                            var value = pay.GetCryptoPaymentData().GetValue() - pay.NetworkFee;
                            var rate = enreplacedy.GetPaymentMethod(paymentMethodId).Rate;
                            return rate * value;
                        })));
            }
            var perks = Parse(settings.PerksTemplate, settings.TargetCurrency);
            if (settings.SortPerksByPopularity)
            {
                var ordered = perkCount.OrderByDescending(pair => pair.Value);
                var newPerksOrder = ordered
                    .Select(keyValuePair => perks.SingleOrDefault(item => item.Id == keyValuePair.Key))
                    .Where(matchingPerk => matchingPerk != null)
                    .ToList();
                var remainingPerks = perks.Where(item => !newPerksOrder.Contains(item));
                newPerksOrder.AddRange(remainingPerks);
                perks = newPerksOrder.ToArray();
            }

            return new ViewCrowdfundViewModel
            {
                replacedle = settings.replacedle,
                Tagline = settings.Tagline,
                Description = settings.Description,
                CustomCSSLink = settings.CustomCSSLink,
                MainImageUrl = settings.MainImageUrl,
                EmbeddedCSS = settings.EmbeddedCSS,
                StoreId = appData.StoreDataId,
                AppId = appData.Id,
                StartDate = settings.StartDate?.ToUniversalTime(),
                EndDate = settings.EndDate?.ToUniversalTime(),
                TargetAmount = settings.TargetAmount,
                TargetCurrency = settings.TargetCurrency,
                EnforceTargetAmount = settings.EnforceTargetAmount,
                Perks = perks,
                Enabled = settings.Enabled,
                DisqusEnabled = settings.DisqusEnabled,
                SoundsEnabled = settings.SoundsEnabled,
                DisqusShortname = settings.DisqusShortname,
                AnimationsEnabled = settings.AnimationsEnabled,
                ResetEveryAmount = settings.ResetEveryAmount,
                ResetEvery = Enum.GetName(typeof(CrowdfundResetEvery), settings.ResetEvery),
                DisplayPerksRanking = settings.DisplayPerksRanking,
                PerkCount = perkCount,
                PerkValue = perkValue,
                NeverReset = settings.ResetEvery == CrowdfundResetEvery.Never,
                Sounds = settings.Sounds,
                AnimationColors = settings.AnimationColors,
                CurrencyData = _Currencies.GetCurrencyData(settings.TargetCurrency, true),
                CurrencyDataPayments = currentPayments.Select(pair => pair.Key)
                    .Concat(pendingPayments.Select(pair => pair.Key))
                    .Select(id => _Currencies.GetCurrencyData(id.CryptoCode, true))
                    .DistinctBy(data => data.Code)
                    .ToDictionary(data => data.Code, data => data),
                Info = new CrowdfundInfo
                {
                    TotalContributors = paidInvoices.Length,
                    ProgressPercentage = (currentPayments.TotalCurrency / settings.TargetAmount) * 100,
                    PendingProgressPercentage = (pendingPayments.TotalCurrency / settings.TargetAmount) * 100,
                    LastUpdated = DateTime.Now,
                    PaymentStats = currentPayments.ToDictionary(c => c.Key.ToString(), c => c.Value.Value),
                    PendingPaymentStats = pendingPayments.ToDictionary(c => c.Key.ToString(), c => c.Value.Value),
                    LastResetDate = lastResetDate,
                    NextResetDate = nextResetDate,
                    CurrentPendingAmount = pendingPayments.TotalCurrency,
                    CurrentAmount = currentPayments.TotalCurrency
                }
            };
        }

19 Source : ArticleFactory.cs
with MIT License
from burki169

public ArticleViewModel CreateArticleViewModel(Article article)
        {
            var model = new ArticleViewModel();
            if (article != null)
            {
                model.Author = UserRepository.Get(article.Author);
                model.Category = new CategoryViewModel(article.Category);
                model.Content = article.Content;
                model.Created = article.Created ?? DateTime.Now;
                model.Edited = article.Edited ?? DateTime.Now;
                model.Id = article.Id;
                model.IsDraft = article.IsDraft == 1 ? true : false;
                model.Likes = article.Likes;
                model.PublishEndDate = article.PublishEndDate ?? DateTime.Now;
                model.PublishStartDate = article.PublishStartDate ?? DateTime.Now.AddYears(5);
                model.replacedle = article.replacedle;
                model.Tags = string.Join(",", article.ArticleTags.Select(at => at.Tag.Name).ToArray());
                model.Attachments = article.Attachments.Select(t => new AttachmentViewModel(t)).ToList();
                model.SefName = article.SefName;
            }

            return model;
        }

19 Source : ArticleFactory.cs
with MIT License
from burki169

public ArticleViewModel CreateArticleViewModelWithDefValues(Category cat)
        {
            var model = new ArticleViewModel
            {
                PublishStartDate = DateTime.Now.Date,
                PublishEndDate = DateTime.Now.AddYears(5).Date,
                Category = cat != null ? CategoryFactory.CreateCategoryViewModel(cat) : new CategoryViewModel()
            };

            return model;
        }

19 Source : DateTimeExt.cs
with MIT License
from bxjg1987

private static string CalculateAgeString(this DateTime p_FirstDateTime, System.DateTime p_SecondDateTime, string p_ReturnFormat)
        {
            //判断时间段是否为正。若为负,调换两个时间点的位置。
            if (System.DateTime.Compare(p_FirstDateTime, p_SecondDateTime) > 0)
            {
                System.DateTime stmpDateTime = p_FirstDateTime;
                p_FirstDateTime = p_SecondDateTime;
                p_SecondDateTime = stmpDateTime;
            }

            //判断返回字符串的格式。若为空,则给默认值:{0}岁{1}月{2}天
            if (string.IsNullOrEmpty(p_ReturnFormat)) p_ReturnFormat = "{0}岁{1}月{2}天";

            //定义:年、月、日
            int year, month, day;

            //计算:天
            day = p_SecondDateTime.Day - p_FirstDateTime.Day;
            if (day < 0)
            {
                day += System.DateTime.DaysInMonth(p_FirstDateTime.Year, p_FirstDateTime.Month);
                p_FirstDateTime = p_FirstDateTime.AddMonths(1);
            }
            //计算:月
            month = p_SecondDateTime.Month - p_FirstDateTime.Month;
            if (month < 0)
            {
                month += 12;
                p_FirstDateTime = p_FirstDateTime.AddYears(1);
            }
            //计算:年
            year = p_SecondDateTime.Year - p_FirstDateTime.Year;

            //返回格式化后的结果
            return string.Format(p_ReturnFormat, year, month, day);
        }

19 Source : ItAssetService.cs
with GNU General Public License v3.0
from Caijt

public List<Dictionary<string, object>> GetTimeStatistic(TimeStatisticQueryDto timeStatisticQueryDto, ItreplacedetQueryDto queryDto)
        {
            Expression<Func<Itreplacedet, dynamic>> groupExp = null;
            Func<DateTime, int, DateTime> dateFunc = null;
            Func<DateTime, DateTime> beginDateFunc = null;
            Func<DateTime, DateTime> endDateFunc = null;
            string format = "";
            switch (timeStatisticQueryDto.unit)
            {
                case "year":
                    format = "yyyy";
                    dateFunc = (datetime, i) => datetime.Date.AddYears(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, 1, 1);
                    endDateFunc = datetime => new DateTime(datetime.Year + 1, 1, 1);
                    groupExp = e => new
                    {
                        unit = e.inbound_date.Year.ToString()
                    };
                    break;
                case "day":
                    format = "yyyy-M-d";
                    dateFunc = (datetime, i) => datetime.AddDays(i);
                    beginDateFunc = datetime => datetime.Date;
                    endDateFunc = datetime => datetime.AddDays(1).Date;
                    groupExp = e => new
                    {
                        unit = e.inbound_date.Year.ToString() + "-" + e.inbound_date.Month + "-" + e.inbound_date.Day
                    };
                    break;
                case "month":
                default:
                    format = "yyyy-M";
                    dateFunc = (datetime, i) => datetime.AddMonths(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, datetime.Month, 1);
                    endDateFunc = datetime =>
                    {
                        datetime = datetime.AddMonths(1);
                        return new DateTime(datetime.Year, datetime.Month, 1);
                    };
                    groupExp = e => new
                    {
                        unit = e.inbound_date.Year.ToString() + "-" + e.inbound_date.Month.ToString()
                    };

                    break;
            }
            if (!timeStatisticQueryDto.time_end.HasValue)
            {
                timeStatisticQueryDto.time_end = DateTime.Today;
            }
            if (!timeStatisticQueryDto.time_begin.HasValue)
            {
                timeStatisticQueryDto.time_begin = dateFunc(timeStatisticQueryDto.time_end.Value, -8);
            }
            DateTime beginTime = beginDateFunc(timeStatisticQueryDto.time_begin.Value);
            DateTime endTime = endDateFunc(timeStatisticQueryDto.time_end.Value);
            List<Dictionary<string, object>> unitDataList = new List<Dictionary<string, object>>();
            DateTime timeTemp = beginTime;
            while (timeTemp < endTime)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("unit", timeTemp.ToString(format));
                dict.Add("price", 0);
                dict.Add("amount", 0);
                unitDataList.Add(dict);
                timeTemp = dateFunc(timeTemp, 1);
            }
            var query = buildWhere(this.dbQuery, queryDto);
            if (onWhere != null)
            {
                query = onWhere(query, queryDto);
            }
            var data = query.Where(e => e.inbound_date >= beginTime && e.inbound_date < endTime)
                .GroupBy(groupExp)
                .Select(g => new
                {
                    Key = g.Key,
                    price = g.Sum(e => e.price),
                    amount = g.Sum(e => e.amount)
                }).ToList();
            unitDataList.ForEach(i =>
            {
                data.ForEach(i2 =>
                {
                    if (string.Equals(i["unit"], i2.Key.unit))
                    {
                        i["price"] = i2.price;
                        i["amount"] = i2.amount;
                    }
                });
            });
            return unitDataList;
        }

19 Source : ItContractPayRecordService.cs
with GNU General Public License v3.0
from Caijt

public List<Dictionary<string, object>> GetTimeStatistic(TimeStatisticQueryDto timeStatisticQueryDto, ItContractPayRecordQueryDto queryDto)
        {
            Expression<Func<ItContractPayRecord, dynamic>> groupExp = null;
            Func<DateTime, int, DateTime> dateFunc = null;
            Func<DateTime, DateTime> beginDateFunc = null;
            Func<DateTime, DateTime> endDateFunc = null;
            string format = "";
            switch (timeStatisticQueryDto.unit)
            {
                case "year":
                    format = "yyyy";
                    dateFunc = (datetime, i) => datetime.Date.AddYears(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, 1, 1);
                    endDateFunc = datetime => new DateTime(datetime.Year + 1, 1, 1);
                    groupExp = e => new
                    {
                        unit = e.pay_date.Year.ToString()
                    };
                    break;
                case "day":
                    format = "yyyy-M-d";
                    dateFunc = (datetime, i) => datetime.AddDays(i);
                    beginDateFunc = datetime => datetime.Date;
                    endDateFunc = datetime => datetime.AddDays(1).Date;
                    groupExp = e => new
                    {
                        unit = e.pay_date.Year.ToString() + "-" + e.pay_date.Month + "-" + e.pay_date.Day
                    };
                    break;
                case "month":
                default:
                    format = "yyyy-M";
                    dateFunc = (datetime, i) => datetime.AddMonths(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, datetime.Month, 1);
                    endDateFunc = datetime =>
                    {
                        datetime = datetime.AddMonths(1);
                        return new DateTime(datetime.Year, datetime.Month, 1);
                    };
                    groupExp = e => new
                    {
                        unit = e.pay_date.Year.ToString() + "-" + e.pay_date.Month.ToString()
                    };

                    break;
            }
            if (!timeStatisticQueryDto.time_end.HasValue)
            {
                timeStatisticQueryDto.time_end = DateTime.Today;
            }
            if (!timeStatisticQueryDto.time_begin.HasValue)
            {
                timeStatisticQueryDto.time_begin = dateFunc(timeStatisticQueryDto.time_end.Value, -8);
            }
            DateTime beginTime = beginDateFunc(timeStatisticQueryDto.time_begin.Value);
            DateTime endTime = endDateFunc(timeStatisticQueryDto.time_end.Value);
            List<Dictionary<string, object>> unitDataList = new List<Dictionary<string, object>>();
            DateTime timeTemp = beginTime;
            while (timeTemp < endTime)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("unit", timeTemp.ToString(format));
                dict.Add("price", 0);
                dict.Add("amount", 0);
                unitDataList.Add(dict);
                timeTemp = dateFunc(timeTemp, 1);
            }
            var query = buildWhere(this.dbQuery, queryDto);
            if (onWhere != null)
            {
                query = onWhere(query, queryDto);
            }
            var data = query.Where(e => e.pay_date >= beginTime && e.pay_date < endTime)
                .GroupBy(groupExp)
                .Select(g => new
                {
                    Key = g.Key,
                    price = g.Sum(e => e.pay_price),
                    amount = g.Count()
                }).ToList();
            unitDataList.ForEach(i =>
            {
                data.ForEach(i2 =>
                {
                    if (string.Equals(i["unit"], i2.Key.unit))
                    {
                        i["price"] = i2.price;
                        i["amount"] = i2.amount;
                    }
                });
            });
            return unitDataList;
        }

19 Source : ItContractService.cs
with GNU General Public License v3.0
from Caijt

public List<Dictionary<string, object>> GetTimeStatistic(TimeStatisticQueryDto timeStatisticQueryDto, ItContractQueryDto queryDto)
        {
            Expression<Func<ItContractView, dynamic>> groupExp = null;
            Func<DateTime, int, DateTime> dateFunc = null;
            Func<DateTime, DateTime> beginDateFunc = null;
            Func<DateTime, DateTime> endDateFunc = null;
            string format = "";
            switch (timeStatisticQueryDto.unit)
            {
                case "year":
                    format = "yyyy";
                    dateFunc = (datetime, i) => datetime.Date.AddYears(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, 1, 1);
                    endDateFunc = datetime => new DateTime(datetime.Year + 1, 1, 1);
                    groupExp = e => new
                    {
                        unit = e.sign_date.Year.ToString()
                    };
                    break;
                case "day":
                    format = "yyyy-M-d";
                    dateFunc = (datetime, i) => datetime.AddDays(i);
                    beginDateFunc = datetime => datetime.Date;
                    endDateFunc = datetime => datetime.AddDays(1).Date;
                    groupExp = e => new
                    {
                        unit = e.sign_date.Year.ToString() + "-" + e.sign_date.Month + "-" + e.sign_date.Day
                    };
                    break;
                case "month":
                default:
                    format = "yyyy-M";
                    dateFunc = (datetime, i) => datetime.AddMonths(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, datetime.Month, 1);
                    endDateFunc = datetime =>
                    {
                        datetime = datetime.AddMonths(1);
                        return new DateTime(datetime.Year, datetime.Month, 1);
                    };
                    groupExp = e => new
                    {
                        unit = e.sign_date.Year.ToString() + "-" + e.sign_date.Month.ToString()
                    };

                    break;
            }
            if (!timeStatisticQueryDto.time_end.HasValue)
            {
                timeStatisticQueryDto.time_end = DateTime.Today;
            }
            if (!timeStatisticQueryDto.time_begin.HasValue)
            {
                timeStatisticQueryDto.time_begin = dateFunc(timeStatisticQueryDto.time_end.Value, -8);
            }
            DateTime beginTime = beginDateFunc(timeStatisticQueryDto.time_begin.Value);
            DateTime endTime = endDateFunc(timeStatisticQueryDto.time_end.Value);
            List<Dictionary<string, object>> unitDataList = new List<Dictionary<string, object>>();
            DateTime timeTemp = beginTime;
            while (timeTemp < endTime)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("unit", timeTemp.ToString(format));
                dict.Add("price", 0);
                dict.Add("amount", 0);
                unitDataList.Add(dict);
                timeTemp = dateFunc(timeTemp, 1);
            }
            var query = buildWhere(this.dbQuery, queryDto);
            if (onWhere != null)
            {
                query = onWhere(query, queryDto);
            }
            var data = query.Where(e => e.sign_date >= beginTime && e.sign_date < endTime)
                .GroupBy(groupExp)
                .Select(g => new
                {
                    Key = g.Key,
                    price = g.Sum(e => e.price),
                    amount = g.Count()
                }).ToList();
            unitDataList.ForEach(i =>
            {
                data.ForEach(i2 =>
                {
                    if (string.Equals(i["unit"], i2.Key.unit))
                    {
                        i["price"] = i2.price;
                        i["amount"] = i2.amount;
                    }
                });
            });
            return unitDataList;
        }

19 Source : BirthdayConverter.cs
with MIT License
from canbilgin

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			DateTime bday = (DateTime)value;
			DateTime today = DateTime.Today;
			int age = today.Year - bday.Year;
			return (bday > today.AddYears(-age)) ? age-1 : age;
		}

19 Source : GenderToIndexConverter.cs
with MIT License
from canbilgin

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
	{
		DateTime bday = (DateTime)value;
		DateTime today = DateTime.Today;
		int age = today.Year - bday.Year;
		return (bday > today.AddYears(-age)) ? age - 1 : age;
	}

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

private static List<Symbol> MonthlyContractListings(
            Symbol canonicalFuture,
            DateTime time,
            int contractMonthForNewListings,
            params FuturesListingCycles[] futureListingCycles)
        {
            var listings = new List<Symbol>();
            var expiryFunc = FuturesExpiryFunctions.FuturesExpiryFunction(canonicalFuture);
            var yearDelta = 0;

            var contractMonthForNewListingCycle = new DateTime(time.Year, contractMonthForNewListings, 1);
            var contractMonthForNewListingCycleExpiry = expiryFunc(contractMonthForNewListingCycle);

            if (time <= contractMonthForNewListingCycleExpiry)
            {
                // Go back a year if we haven't yet crossed this year's contract renewal expiration date.
                contractMonthForNewListingCycleExpiry = expiryFunc(contractMonthForNewListingCycle.AddYears(-1));
                yearDelta = -1;
            }

            foreach (var listingCycle in futureListingCycles)
            {
                var year = yearDelta;
                var count = 0;
                var initialListings = true;

                while (count != listingCycle.Limit)
                {
                    var monthStartIndex = 0;
                    if (initialListings)
                    {
                        // For the initial listing, we want to start counting at some month that might not be the first
                        // index of the collection. The index is discovered here and used as the starting point for listed contracts.
                        monthStartIndex = listingCycle.Cycle.Length - listingCycle.Cycle.Count(c => c > contractMonthForNewListingCycleExpiry.Month);
                        initialListings = false;
                    }

                    for (var m = monthStartIndex; m < listingCycle.Cycle.Length; m++)
                    {
                        // Add the future's expiration to the listings
                        var currentContractMonth = new DateTime(time.Year + year, listingCycle.Cycle[m], 1);
                        var currentFutureExpiry = expiryFunc(currentContractMonth);
                        if (currentFutureExpiry >= time)
                        {
                            listings.Add(Symbol.CreateFuture(canonicalFuture.ID.Symbol, canonicalFuture.ID.Market, currentFutureExpiry));
                        }

                        if (++count == listingCycle.Limit)
                        {
                            break;
                        }
                    }

                    year++;
                }
            }

            return listings;
        }

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

private DateTime GetFramesNextUnitStart(DateTime dateTime, bool inverse = false)
        {
            var direction = inverse ? -1 : 1;
            switch (Period)
            {
                case PriceHistoryPeriod.Month:
                    return dateTime.AddYears(1 * direction);
                default:
                    return dateTime.AddTicks((TicksPerPeriod * FramesPerUnit) * direction);
            }
        }

19 Source : LineExpression.cs
with GNU General Public License v3.0
from cesarbmx

public static Expression<Func<Line, bool>> ObsoleteLine()
        {
            return x => x.Period == Period.ONE_MINUTE && x.Time < DateTime.UtcNow.AddHours(-3) ||
                            x.Period == Period.FIVE_MINUTES && x.Time < DateTime.UtcNow.AddDays(-1) ||
                            x.Period == Period.FIFTEEN_MINUTES && x.Time < DateTime.UtcNow.AddDays(-3) ||
                            x.Period == Period.ONE_HOUR && x.Time < DateTime.UtcNow.AddDays(-8) ||
                            x.Period == Period.ONE_DAY && x.Time < DateTime.UtcNow.AddYears(-1);
        }

19 Source : CustomerDiscountCalculator.cs
with MIT License
from changhuixu

private static LoyalYear GetLoyalYear(DateTime? dateOfFirstPurchase, DateTime now)
        {
            if (!dateOfFirstPurchase.HasValue)
            {
                return LoyalYear.None;
            }

            var purchaseYears = now.Year - dateOfFirstPurchase.Value.Year;
            if (now.AddYears(-purchaseYears) < dateOfFirstPurchase.Value) purchaseYears--;
            var loyalYear = Enum.GetValues(typeof(LoyalYear)).Cast<int>()
                .OrderByDescending(x => x)
                .First(x => x <= purchaseYears);
            return (LoyalYear)loyalYear;
        }

19 Source : CustomerDiscountCalculatorTests.cs
with MIT License
from changhuixu

[TestMethod]
        public void Return5PctForSenior()
        {
            var customer = new Customer
            {
                DateOfBirth = DateTime.Today.AddYears(-65).AddDays(-5),
                DateOfFirstPurchase = DateTime.Today.AddDays(-1)
            };
            var calculator = new CustomerDiscountCalculator(customer, DateTime.Now);
            var discount = calculator.CalculateDiscountPercentage();

            replacedert.AreEqual(0.05m, discount);
        }

19 Source : CustomerDiscountCalculatorTests.cs
with MIT License
from changhuixu

[TestMethod]
        public void Return12PctFor5YearLoyalCustomer()
        {
            var customer = new Customer
            {
                DateOfBirth = DateTime.Today.AddDays(-5),
                DateOfFirstPurchase = DateTime.Today.AddYears(-5)
            };
            var calculator = new CustomerDiscountCalculator(customer, DateTime.Now);
            var discount = calculator.CalculateDiscountPercentage();

            replacedert.AreEqual(0.12m, discount);
        }

19 Source : CustomerDiscountCalculatorTests.cs
with MIT License
from changhuixu

[TestMethod]
        public void Return22PctFor5YearLoyalCustomerOnBirthday()
        {
            var customer = new Customer
            {
                DateOfBirth = DateTime.Today,
                DateOfFirstPurchase = DateTime.Today.AddYears(-5)
            };
            var calculator = new CustomerDiscountCalculator(customer, DateTime.Now);
            var discount = calculator.CalculateDiscountPercentage();

            replacedert.AreEqual(0.22m, discount);
        }

19 Source : RulesPatternDiscountCalculatorTests.cs
with MIT License
from changhuixu

[TestMethod]
        public void Return5PctForSenior()
        {
            var customer = new Customer() { DateOfBirth = DateTime.Today.AddYears(-65).AddDays(-5), DateOfFirstPurchase = DateTime.Today.AddDays(-1) };

            decimal discount = _calculator.CalculateDiscountPercentage(customer);

            replacedert.AreEqual(0.05m, discount);
        }

19 Source : RulesPatternDiscountCalculatorTests.cs
with MIT License
from changhuixu

[TestMethod]
        public void Return12PctFor5YearLoyalCustomer()
        {
            var customer = new Customer() { DateOfBirth = DateTime.Today.AddDays(-5), DateOfFirstPurchase = DateTime.Today.AddYears(-5) };

            decimal discount = _calculator.CalculateDiscountPercentage(customer);

            replacedert.AreEqual(0.12m, discount);
        }

19 Source : RulesPatternDiscountCalculatorTests.cs
with MIT License
from changhuixu

[TestMethod]
        public void Return22PctFor5YearLoyalCustomerOnBirthday()
        {
            var customer = new Customer() { DateOfBirth = DateTime.Today, DateOfFirstPurchase = DateTime.Today.AddYears(-5) };

            decimal discount = _calculator.CalculateDiscountPercentage(customer);

            replacedert.AreEqual(0.22m, discount);
        }

19 Source : DtlsUtils.cs
with MIT License
from chatop2020

public static X509Certificate2 CreateSelfSignedCert(string subjectName, string issuerName, AsymmetricKeyParameter privateKey)
        {
            const int keyStrength = DEFAULT_KEY_SIZE;
            if (privateKey == null)
            {
                privateKey = CreatePrivateKeyResource(issuerName);
            }
            var issuerPrivKey = privateKey;

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivKey, random);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();
            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.DnsName, "localhost"), new GeneralName(GeneralName.DnsName, "127.0.0.1") }));
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List<DerObjectIdentifier>() { new DerObjectIdentifier("1.3.6.1.5.5.7.3.1") }));

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn = new X509Name(issuerName);
            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter = notBefore.AddYears(70);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // self sign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // Originally pre-processor defines were used to try and pick the supported way to get from a Bouncy Castle
            // certificate and private key to a .NET certificate. The problem is that setting the private key on a .NET
            // X509 certificate is possible in .NET Framework but NOT in .NET Core. To complicate matters even further
            // the workaround in the CovertBouncyCert method of saving a cert + pvt key to a .pfx stream and then
            // reloading does not work on macOS or Unity (and possibly elsewhere) due to .pfx serialisation not being
            // compatible. This is the exception from Unity:
            //
            // Mono.Security.ASN1..ctor (System.Byte[] data) (at <6a66fe237d4242c9924192d3c28dd540>:0)
            // Mono.Security.X509.X509Certificate.Parse(System.Byte[] data)(at < 6a66fe237d4242c9924192d3c28dd540 >:0)
            //
            // Summary:
            // .NET Framework (including Mono on Linux, macOS and WSL)
            //  - Set x509.PrivateKey works.
            // .NET Standard:
            //  - Set x509.PrivateKey for a .NET Framework application.
            //  - Set x509.PrivateKey for a .NET Core application FAILS.
            // .NET Core:
            //  - Set x509.PrivateKey for a .NET Core application FAILS.
            //  - PFX serialisation works on Windows.
            //  - PFX serialisation works on WSL and Linux.
            //  - PFX serialisation FAILS on macOS.
            //
            // For same issue see https://github.com/dotnet/runtime/issues/23635.
            // For fix in net5 see https://github.com/dotnet/corefx/pull/42226.
            try
            {
                // corresponding private key
                var info = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

                // merge into X509Certificate2
                var x509 = new X509Certificate2(certificate.GetEncoded());

                var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());
                if (seq.Count != 9)
                {
                    throw new Org.BouncyCastle.OpenSsl.PemException("malformed sequence in RSA private key");
                }

                var rsa = RsaPrivateKeyStructure.GetInstance(seq); //new RsaPrivateKeyStructure(seq);
                var rsaparams = new RsaPrivateCrtKeyParameters(
                    rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

                x509.PrivateKey = ToRSA(rsaparams);
                return x509;
            }
            catch
            {
                return ConvertBouncyCert(certificate, subjectKeyPair);
            }
        }

19 Source : DtlsUtils.cs
with MIT License
from chatop2020

public static (Org.BouncyCastle.Crypto.Tls.Certificate crtificate, AsymmetricKeyParameter privateKey) CreateSelfSignedTlsCert(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivateKey)
        {
            const int keyStrength = DEFAULT_KEY_SIZE;
            if (issuerPrivateKey == null)
            {
                issuerPrivateKey = CreatePrivateKeyResource(issuerName);
            }

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivateKey, random);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();
            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.DnsName, "localhost"), new GeneralName(GeneralName.DnsName, "127.0.0.1") }));
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List<DerObjectIdentifier>() { new DerObjectIdentifier("1.3.6.1.5.5.7.3.1") }));

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn = new X509Name(issuerName);
            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter = notBefore.AddYears(70);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // self sign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            var chain = new Org.BouncyCastle.Asn1.X509.X509CertificateStructure[] { X509CertificateStructure.GetInstance(certificate.GetEncoded()) };
            var tlsCertificate = new Org.BouncyCastle.Crypto.Tls.Certificate(chain);

            return (tlsCertificate, subjectKeyPair.Private);
        }

19 Source : FaceCompareBLL.cs
with GNU General Public License v3.0
from chenyinxin

public static void AddUserFace(SysUser user)
        {
            DataContext dbContext = new DataContext();

            var faceFeature = FaceCompareHelper.ExtractFeature(HttpContextCore.MapPath(user.UserImage));
            if (string.IsNullOrEmpty(faceFeature))
                return;

            //保存人脸特征
            var feature = dbContext.Set<SysUserFaceFeature>().FirstOrDefault(x => x.UserId == user.UserId);
            if (feature == null)
            {
                feature = new SysUserFaceFeature
                {
                    UserId = user.UserId,
                    UserName = user.UserName,
                    UserType = "User",
                    FaceImage = user.UserImage,
                    FaceFeature = faceFeature,
                    FaceFeatureType = "",
                    FaceTimeOut = DateTime.Now.AddYears(100),
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };
                dbContext.Set<SysUserFaceFeature>().Add(feature);
            }
            else
            {
                feature.UserName = user.UserName;
                feature.FaceImage = user.UserImage;
                feature.FaceFeature = faceFeature;
                feature.UpdateTime = DateTime.Now;
            }

            //更新客户端队列(根据业务修改)
            var data = new Dictionary<string, string>
            {
                ["ActionName"] = "AddFace",
                ["Id"] = user.UserId.ToString(),
                ["Name"] = user.UserName,
                ["ImageUrl"] = user.UserImage,
                ["FaceFeature"] = faceFeature,
                ["TimeOut"] = DateTime.Now.AddYears(100).ToString()
            };

            SysQueue queue = new SysQueue
            {
                Id = Guid.NewGuid(),
                ClientId = user.DepartmentId.ToString(),
                ActionName = "AddFace",
                ActionObjectId = user.UserId.ToString(),
                ActionData = JsonConvert.SerializeObject(data),
                CreateTime = DateTime.Now
            };

            dbContext.Set<SysQueue>().Add(queue);
            dbContext.SaveChanges();
        }

19 Source : FaceCompareController.cs
with GNU General Public License v3.0
from chenyinxin

[HttpGet]
        public JsonResult DownLoadFeature(Guid siteId)
        {
            try
            {
                var list = dbContext.Set<SysUser>().Where(x => x.DepartmentId == siteId);
                List<Dictionary<string, string>> result = new List<Dictionary<string, string>>();

                foreach (var user in list)
                {
                    var face = dbContext.SysUserFaceFeature.FirstOrDefault(x => x.UserId == user.UserId);
                    if (face == null) continue;

                    var item = new Dictionary<string, string>
                    {
                        ["ActionName"] = "AddFace",
                        ["Id"] = user.UserId.ToString(),
                        ["Name"] = user.UserName,
                        ["ImageUrl"] = user.UserCode,
                        ["FaceFeature"] = face.FaceFeature,
                        ["TimeOut"] = DateTime.Now.AddYears(100).ToString()
                    };
                    result.Add(item);
                }

                return Json(new { Code = 0, Data = result });
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
                return Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" });
            }
        }

19 Source : CommonHelper.cs
with MIT License
from chinabeacon

public static int GetDifferenceInYears(DateTime startDate, DateTime endDate)
        {
            //source: http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c
            //this replacedumes you are looking for the western idea of age and not using East Asian reckoning.
            int age = endDate.Year - startDate.Year;
            if (startDate > endDate.AddYears(-age))
                age--;
            return age;
        }

19 Source : ComputedColumnTest.cs
with MIT License
from christiandelbianco

[TestInitialize]
        public void TestInitialize()
        {
            using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
            {
                sqlConnection.Open();
                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = $"DELETE FROM [{TableName}];";
                    sqlCommand.ExecuteNonQuery();
                }
            }

            CheckValues.Clear();
            CheckValuesOld.Clear();

            _counter = 0;

            CheckValues.Add(ChangeType.Insert.ToString(), new Tuple<ComputedColumnModel, ComputedColumnModel>(new ComputedColumnModel { Name = "Christian", BirthDate = DateTime.Now.AddYears(-46).Date, CalculatedAge = 46 }, new ComputedColumnModel()));
            CheckValues.Add(ChangeType.Update.ToString(), new Tuple<ComputedColumnModel, ComputedColumnModel>(new ComputedColumnModel { Name = "Nonna Velia", BirthDate = DateTime.Now.AddYears(-95).Date, CalculatedAge = 95 }, new ComputedColumnModel()));
            CheckValues.Add(ChangeType.Delete.ToString(), new Tuple<ComputedColumnModel, ComputedColumnModel>(new ComputedColumnModel { Name = "Nonna Velia", BirthDate = DateTime.Now.AddYears(-95).Date, CalculatedAge = 95 }, new ComputedColumnModel()));

            CheckValuesOld.Add(ChangeType.Insert.ToString(), new Tuple<ComputedColumnModel, ComputedColumnModel>(new ComputedColumnModel { Name = "Christian", BirthDate = DateTime.Now.AddYears(-46).Date, CalculatedAge = 46 }, new ComputedColumnModel()));
            CheckValuesOld.Add(ChangeType.Update.ToString(), new Tuple<ComputedColumnModel, ComputedColumnModel>(new ComputedColumnModel { Name = "Nonna Velia", BirthDate = DateTime.Now.AddYears(-95).Date, CalculatedAge = 95 }, new ComputedColumnModel()));
            CheckValuesOld.Add(ChangeType.Delete.ToString(), new Tuple<ComputedColumnModel, ComputedColumnModel>(new ComputedColumnModel { Name = "Nonna Velia", BirthDate = DateTime.Now.AddYears(-95).Date, CalculatedAge = 95 }, new ComputedColumnModel()));
        }

19 Source : RandomData.cs
with MIT License
from chsakell

public static ShipmentDetails GenerateShipmentDetails(string locale = "en")
        {
            var shipmentDetails = new Faker<ShipmentDetails>(locale)
                .RuleFor(u => u.ContactName, (f, u) => f.Name.FullName())
                .RuleFor(u => u.ContactPhone, (f, u) => f.Phone.PhoneNumber().OrNull(f, .3f))
                .RuleFor(u => u.City, (f, u) => f.Address.City())
                .RuleFor(u => u.ShipAddress, (f, u) => f.Address.FullAddress())
                .RuleFor(u => u.Country, f => f.Address.Country())
                .RuleFor(u => u.ShippedDate, (f, u) =>
                    f.Date.Between(DateTime.UtcNow.AddYears(-1), DateTime.UtcNow).OrNull(f, .8f));

            return shipmentDetails.Generate();
        }

19 Source : UpdatingArrays.cs
with MIT License
from chsakell

private async Task UpdatingArraysDefinitions()
        {
            var database = Client.GetDatabase(Constants.SamplesDatabase);
            var travelersCollection = database.GetCollection<Traveler>(Constants.TravelersCollection);
            var bsonTravelersCollection = database.GetCollection<BsonDoreplacedent>(Constants.TravelersCollection);
            var storesCollection = database.GetCollection<StoreItem>(Constants.StoreCollection);
            var socialNetworkCollection = database.GetCollection<SocialAccount>(Constants.SocialNetworkCollection);
            var postsCollection = database.GetCollection<Post>(Constants.PostsCollection);
            var bsonPostsCollection = database.GetCollection<BsonDoreplacedent>(Constants.PostsCollection);

            #region Prepare data

            await travelersCollection.InsertManyAsync(RandomData.GenerateTravelers(2));

            #endregion

            #region Typed clreplacedes commands

            #region Adding array items

            var firstTraveler = Builders<Traveler>.Filter.Empty;
            var visitedCountry = RandomData.GenerateVisitedCountries(1).First();
            visitedCountry.Name = "South Korea";
            visitedCountry.TimesVisited = 5;
            visitedCountry.LastDateVisited = DateTime.UtcNow.AddYears(5);

            var pushCountryDefinition = Builders<Traveler>.Update.Push(t => t.VisitedCountries, visitedCountry);
            var addNewVisitedCountryResult = await travelersCollection.UpdateOneAsync(firstTraveler, pushCountryDefinition);
            Utils.Log("South Korea has been added to user's visited countries");

            var newVisitedCountries = RandomData.GenerateVisitedCountries(10);
            var pushCountriesDefinition = Builders<Traveler>.Update
                .PushEach(t => t.VisitedCountries, newVisitedCountries);

            var addNewVisitedCountriesResult = await travelersCollection
                .UpdateOneAsync(firstTraveler, pushCountriesDefinition);

            #endregion

            #region Queue

            var account = RandomData.GenerateSocialAccounts(1).First();

            await socialNetworkCollection.InsertOneAsync(account);

            var firstAccount = await socialNetworkCollection.Find(Builders<SocialAccount>.Filter.Empty)
                .FirstOrDefaultAsync();
            Utils.Log(firstAccount.ToBsonDoreplacedent());

            var newNotifications = new List<Notification>();
            for (int i = 0; i < 4; i++)
            {
                newNotifications.Add(new Notification()
                {
                    Link = $"link-{i}",
                    Text = $"text-{i}"
                });
            }

            var pushNotificationsDefinition = Builders<SocialAccount>.Update
                .PushEach(a => a.LastNotifications, newNotifications, slice: -2);

            var pushNotificationsResult = await socialNetworkCollection
                .UpdateOneAsync(Builders<SocialAccount>.Filter.Eq(a => a.Id, firstAccount.Id), pushNotificationsDefinition);

            firstAccount = await socialNetworkCollection.Find(Builders<SocialAccount>.Filter.Empty)
                .FirstOrDefaultAsync();
            Utils.Log(firstAccount.ToBsonDoreplacedent());
            #endregion

            #region remove array items

            // add two items
            var storeItems = new List<StoreItem>
            {
                new StoreItem()
                {
                    PcGames = new List<string>
                    {
                        "Football Manager", "DOOM Eternal",
                        "FIFA 20", "Grand Theft Auto", "NBA 2K17"
                    },
                    XboxGames = new List<string>
                    {
                        "Forza Horizon", "Call of Duty",
                        "Mortal Kombat", "Gears 5"
                    }
                },
                new StoreItem()
                {
                    PcGames = new List<string>
                    {
                        "replacedreplacedin's Creed", "Final Fantasy",
                        "The Sims", "Football Manager", "FIFA 20"
                    },
                    XboxGames = new List<string>
                    {
                        "Resident Evil", "Forza Motorsport",
                        "Battlefield", "Halo 5 Guardians", "Mortal Kombat"
                    }
                }
            };

            await storesCollection.InsertManyAsync(storeItems);

            var storeEmptyFilter = Builders<StoreItem>.Filter.Empty;
            var removePcGames = new List<string> { "FIFA 20", "NBA 2K17" };
            var removeXboxGames = new List<string> { "Mortal Kombat" };

            var pullPcGamesDefinition = Builders<StoreItem>.Update.PullFilter(s => s.PcGames,
                game => removePcGames.Contains(game));
            var pullXboxGamesDefinition = Builders<StoreItem>.Update.PullFilter(s => s.XboxGames,
                game => removeXboxGames.Contains(game));

            var pullCombined = Builders<StoreItem>.Update
                .Combine(pullPcGamesDefinition, pullXboxGamesDefinition);

            var simplePullResult = await storesCollection
                .UpdateManyAsync(storeEmptyFilter, pullPcGamesDefinition);

            // reset collection
            await database.DropCollectionAsync(Constants.StoreCollection);
            await storesCollection.InsertManyAsync(storeItems);

            var removeUpdateResult = await storesCollection
                .UpdateManyAsync(storeEmptyFilter, pullCombined);

            // remove embedded doreplacedent

            await travelersCollection.InsertManyAsync(RandomData.GenerateTravelers(10, 15));
            var visited8Times = Builders<Traveler>.Filter
                .ElemMatch(t => t.VisitedCountries, country => country.TimesVisited == 8);

            var totalDocVisited8Times = await travelersCollection
                    .Find(visited8Times).CountDoreplacedentsAsync();

            var pullVisited8TimesDefinition = Builders<Traveler>.Update
                .PullFilter(t => t.VisitedCountries,
                country => country.TimesVisited == 8);

            var visited8TimesResult = await travelersCollection
                .UpdateManyAsync(visited8Times, pullVisited8TimesDefinition);

            Utils.Log($"{totalDocVisited8Times} doreplacedent found with TimesVisited = 8 and {visited8TimesResult.ModifiedCount} removed");

            #endregion

            #region update matched array elements

            var visitedGreeceExactly3Times = Builders<Traveler>.Filter
                .ElemMatch(t => t.VisitedCountries,
                    country => country.Name == "Greece" && country.TimesVisited == 3);

            var updateDefinition = Builders<Traveler>.Update.Set(t => t.VisitedCountries[-1].Name, "Hellas");

            // this will update only the first matching array element! ($) refers to the first match
            var updateHellasResult = await travelersCollection.UpdateManyAsync(visitedGreeceExactly3Times, updateDefinition);
            Utils.Log($"{updateHellasResult.ModifiedCount} visited countries have been updated");

            #endregion

            #region update all matched array elements

            var visitedHellasExactly3Times = Builders<Traveler>.Filter
                .ElemMatch(t => t.VisitedCountries,
                    country => country.Name == "Greece" && country.TimesVisited == 3);

            // TODO : more with Aggregation Pipeline
            var updateGreeceDefinition = Builders<Traveler>.Update.Inc("visitedCountries.$[].timesVisited", 10);
            var updateGreeceResult = await travelersCollection.UpdateManyAsync(visitedHellasExactly3Times, updateGreeceDefinition);

            // TODO : more with Aggregation Pipeline

            var updateExactVisitedDefinition = Builders<Traveler>.Update.Inc("visitedCountries.$[el].timesVisited", 10);
            var updateExactVisitedResult = await travelersCollection.UpdateManyAsync(
                Builders<Traveler>.Filter
                    .ElemMatch(t => t.VisitedCountries, country => country.Name == "Hellas")
                , updateExactVisitedDefinition,
                new UpdateOptions()
                {
                    ArrayFilters = new List<ArrayFilterDefinition<VisitedCountry>>()
                    {
                        "{ $and: [{ 'el.timesVisited': 13 }, { 'el.name': 'Hellas'} ] }"
                    }
                });

            #endregion

            #region array filters

            var post = new Post
            {
                Author = "chsakell",
                Content = "hello world",
                Comments = new List<Comment>
                {
                    new Comment
                    {
                        Author = "author 1",
                        Text = "comment 1",
                        Votes = 1
                    },
                    new Comment
                    {
                        Author = "author 2",
                        Text = "comment 2",
                        Votes = 2
                    },
                    new Comment
                    {
                        Author = "author 3",
                        Text = "comment 3",
                        Votes = 3
                    },
                    new Comment
                    {
                        Author = "author 4",
                        Text = "comment 4",
                        Votes = 4
                    }
                }
            };
            await postsCollection.InsertOneAsync(post);

            var update = Builders<BsonDoreplacedent>.Update
                .Set("comments.$[elem].hidden", true);

            var updateResult = await bsonPostsCollection.UpdateOneAsync(
                Builders<BsonDoreplacedent>.Filter.Eq("_id", post.Id), update,
                new UpdateOptions()
                {
                    ArrayFilters = new List<ArrayFilterDefinition<BsonValue>>()
                    {
                            new BsonDoreplacedent("elem.votes", new BsonDoreplacedent("$gte", 3))
                    }
                });

            #endregion

            // TODO: pull/pop

            #endregion

            #region BsonDoreplacedent commands

            #region Adding array items

            var bsonFirstUser = Builders<BsonDoreplacedent>.Filter.Empty;
            var bsonVisitedCountry = RandomData.GenerateVisitedCountries(1).First();
            visitedCountry.Name = "North Korea";
            visitedCountry.TimesVisited = 5;
            visitedCountry.LastDateVisited = DateTime.UtcNow.AddYears(5);

            var bsonPushCountryDefinition = Builders<BsonDoreplacedent>.Update
                .Push("visitedCountries", visitedCountry.ToBsonDoreplacedent());

            var bsonAddNewVisitedCountryResult = await bsonTravelersCollection
                .UpdateOneAsync(bsonFirstUser, bsonPushCountryDefinition);

            var bsonNewVisitedCountries = RandomData.GenerateVisitedCountries(10);
            var bsonPushCountriesDefinition = Builders<BsonDoreplacedent>.Update
                .PushEach("visitedCountries", bsonNewVisitedCountries);

            var bsonAddNewVisitedCountries = await bsonTravelersCollection
                .UpdateOneAsync(bsonFirstUser, bsonPushCountriesDefinition);

            var bsonVisited9Times = Builders<BsonDoreplacedent>.Filter
                .ElemMatch<BsonValue>("visitedCountries", new BsonDoreplacedent { { "timesVisited", 9 } });

            var bsonTotalDocVisited9Times = await bsonTravelersCollection
                .Find(bsonVisited9Times).CountDoreplacedentsAsync();

            var bsonPullVisited9TimesDefinition = Builders<BsonDoreplacedent>.Update
                .PullFilter<BsonValue>("visitedCountries",
                    new BsonDoreplacedent { { "timesVisited", 9 } });

            var bsonVisited9TimesResult = await bsonTravelersCollection
                .UpdateManyAsync(bsonVisited9Times, bsonPullVisited9TimesDefinition);

            #endregion

            #region update matched array elements
            var bsonVisitedGreeceExactly3Times = Builders<BsonDoreplacedent>.Filter
                .ElemMatch<BsonValue>("visitedCountries", new BsonDoreplacedent { { "name", "Greece" }, { "timesVisited", 3 } });

            var bsonUpdateDefinition = Builders<BsonDoreplacedent>.Update.Set("visitedCountries.$.name", "Hellas");

            var bsonUpdateHellasResult = await bsonTravelersCollection
                .UpdateManyAsync(bsonVisitedGreeceExactly3Times, bsonUpdateDefinition);

            #endregion

            #region update all matched array elements

            var bsonVisitedHellasExactly3Times = Builders<BsonDoreplacedent>.Filter
                .ElemMatch<BsonValue>("visitedCountries", new BsonDoreplacedent { { "name", "Hellas" }, { "timesVisited", 3 } });

            // TODO : more with projection
            var bsonUpdateGreeceDefinition = Builders<BsonDoreplacedent>.Update.Inc("visitedCountries.$[].timesVisited", 10);
            var bsonUpdateGreeceResult = await bsonTravelersCollection
                .UpdateManyAsync(bsonVisitedHellasExactly3Times, bsonUpdateGreeceDefinition);

            #endregion

            #endregion

            #region Shell commands

#if false
            db.travelers.updateMany(
                {
                    "visitedCountries": {
                        "$elemMatch": {
                            "timesVisited": 8
                        }
                    },
                },
                {
                    "$pull": {
                        "visitedCountries": {
                            "timesVisited": 8
                        }
                    }
                }
            )

            db.travelers.updateMany(
                { visitedCountries: { $elemMatch: { name: "Hellas", timesVisited: 3 }}},
                { $set: { "visitedCountries.$.name": "Greece" } }
            )
            
            db.travelers.updateMany(
                { visitedCountries: { $elemMatch: { name: "Hellas", timesVisited: 10 }}},
                { $inc: { "visitedCountries.$[].timesVisited": 100 } }
            )


            db.travelers.updateOne( {}, { 
                $push: { visitedCountries: { name: "My Own Country", visitedTimes: 2, lastDateVisited: ISODate("2018-07-11T10:00:23.454Z") } }
            })

            db.travelers.updateOne({}, {
                $push: {
                    visitedCountries: {
                        $each: [
                            {
                                "name": "South Korea",
                                "timesVisited": 5,
                                "lastDateVisited": ISODate("2025-04-21T19:27:38.700+03:00"),
                                "coordinates": {
                                    "lareplacedude": 4.2429,
                                    "longitude": -148.3179
                                }
                            },
                            {
                                "name": "Mozambique",
                                "timesVisited": 6,
                                "lastDateVisited": ISODate("2017-01-20T14:42:27.786+02:00"),
                                "coordinates": {
                                    "lareplacedude": -45.9077,
                                    "longitude": -121.6868
                                }
                            }
                        ]
                    }
                }
            })

#endif

            #endregion
        }

19 Source : InsertDocuments.cs
with MIT License
from chsakell

private async Task InsertSamples()
        {
            var database = Client.GetDatabase(Constants.SamplesDatabase);

            #region Typed clreplacedes commands

            // Will create the users collection on the fly if it doesn't exists
            var personsCollection = database.GetCollection<User>(Constants.UsersCollection);

            User appPerson = RandomData.GenerateUsers(1).First();
            // Insert one doreplacedent
            await personsCollection.InsertOneAsync(appPerson);

            // Insert multiple doreplacedents
            var persons = RandomData.GenerateUsers(10);

            await personsCollection.InsertManyAsync(persons);

            #endregion

            #region BsonDoreplacedent commands

            var personsBsonCollection = database.GetCollection<BsonDoreplacedent>(Constants.UsersCollection);

            var bsonPerson = new BsonDoreplacedent
            {
                { "gender" , 1 },
                {"firstName" , "Johh" },
                { "lastName" , "Doe"},
                { "userName" , "Kimberly12"},
                { "avatar" , "https://s3.amazonaws.com/uifaces/faces/twitter/benefritz/128.jpg" },
                { "email" , "[email protected]"},
                { "dateOfBirth" , new BsonDateTime(DateTime.Now.AddYears(-25)) },
                { "address", new BsonDoreplacedent
                    {
                        {"street" , "113 Al Points" },
                        {"suite" , "Apt. 697" },
                        {"city" , "South Murrayshire" },
                        {"state" , "South Dakota" },
                        {"zipCode" , "35038" },
                        {
                            "geo", new BsonDoreplacedent()
                            {
                                { "lat", 87.333 },
                                { "lng", -116.99 }
                            }
                        }
                    }
                },
                { "phone" , "392-248-7338 x083" },
                { "website" , "terry.biz" },
                {
                    "company" , new BsonDoreplacedent()
                    {
                        {"name" , "Bode - Hills" },
                        {"catchPhrase" , "Total composite service-desk" },
                        {"bs" , "morph customized bandwidth"}
                    }
                },
                { "salary" , 1641 },
                { "monthlyExpenses" , 3009 },
                { "favoriteSports", new BsonArray{ "Basketball", "MMA" } },
                { "profession", "Doctor" }
            };

            await personsBsonCollection.InsertOneAsync(bsonPerson);

            var bsonUser = BsonDoreplacedent.Parse(@"{
	            'gender' : 1,
	            'firstName' : 'Kimberly',
	            'lastName' : 'Ernser',
	            'userName' : 'Kimberly12',
	            'avatar' : 'https://s3.amazonaws.com/uifaces/faces/twitter/benefritz/128.jpg',
	            'email' : '[email protected]',
	            'dateOfBirth' : ISODate('1996-06-10T23:55:56.029+03:00'),
	            'address' : {
		            'street' : '113 Al Points',
		            'suite' : 'Apt. 697',
		            'city' : 'South Murrayshire',
		            'state' : 'South Dakota',
		            'zipCode' : '35038',
		            'geo' : {
			            'lat' : 87.4034,
			            'lng' : -116.5628
		            }
	            },
	            'phone' : '392-248-7338 x083',
	            'website' : 'terry.biz',
	            'company' : {
		            'name' : 'Bode - Hills',
		            'catchPhrase' : 'Total composite service-desk',
		            'bs' : 'morph customized bandwidth'
	            },
	            'salary' : 1641,
	            'monthlyExpenses' : 3009,
	            'favoriteSports' : [
		            'Basketball',
		            'MMA',
		            'Volleyball',
		            'Ice Hockey',
		            'Water Polo',
		            'Moto GP',
		            'Beach Volleyball'
	            ],
	            'profession' : 'Photographer'
            }");

            await personsBsonCollection.InsertOneAsync(bsonUser);

            await personsBsonCollection.InsertOneAsync(appPerson.ToBsonDoreplacedent());

            #endregion

            #region Shell commands

            /*
            use Persons
            db.users.insertOne({
                'firstName': 'Lee',
                'lastName': 'Brown',
                'userName': 'Lee_Brown3',
                'avatar': 'https://s3.amazonaws.com/uifaces/faces/twitter/ccinojreplacedo1/128.jpg',
                'email': '[email protected]',
                'dateOfBirth': '1984-01-16T21:31:27.87666',
                'address': {
                    'street': '2552 Bernard Rapid',
                    'suite': 'Suite 199',
                    'city': 'New Haskell side',
                    'zipCode': '78425-0411',
                    'geo': {
                        'lat': -35.8154,
                        'lng': -140.2044
                    }
                },
                'phone': '1-500-790-8836 x5069',
                'website': 'javier.biz',
                'company': {
                    'name': 'Kuphal and Sons',
                    'catchPhrase': 'Organic even-keeled monitoring',
                    'ns': 'open-source brand e-business'
                },
                'salary': NumberDecimal(3000)
            })
            */

            #endregion
        }

19 Source : RandomData.cs
with MIT License
from chsakell

public static List<VisitedCountry> GenerateVisitedCountries(int count, string locale = "en")
        {
            var visitedCountry = new Faker<VisitedCountry>(locale)
                .RuleFor(u => u.Name, f => f.Address.Country())
                .RuleFor(u => u.TimesVisited, f => f.Random.Number(1, 10))
                .RuleFor(c => c.Coordinates, f => GenerateGeolocations(1).First())
                .RuleFor(u => u.LastDateVisited, (f, u) =>
                    f.Date.Between(DateTime.UtcNow.AddYears(-5), DateTime.UtcNow));

            return visitedCountry.Generate(count);
        }

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

private DateTime EnsureUnixTime(DateTime time)
        {
            // the server claims to be UNIX, so there should be
            // no timestamps before 1970.
            // e.g. FileZilla does not handle them correctly.

            int yearDiff = time.Year - 1970;
            if (yearDiff < 0)
                return time.AddYears(-yearDiff);
            else
                return time;
        }

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

private ProductDiscount CreateOrRetrieveProductDiscountOfAbsoluteValue(string productId, int discountCentAmount)
        {
            var money = new Money() {CurrencyCode = "EUR", CentAmount = discountCentAmount};

            var productDiscountValue = new AbsoluteProductDiscountValue()
            {
                Money = new List<Money>() {money}
            };

            var productDiscount = CreateOrRetrieveByKey<ProductDiscount, ProductDiscountDraft>(client,
                KeyProductDiscount,
                new ProductDiscountDraft(),
                draft =>
                {
                    var productDiscountDraft = DefaultProductDiscountDraftWithKey(draft, KeyProductDiscount);

                    productDiscountDraft.Value = productDiscountValue;
                    productDiscountDraft.ValidFrom = DateTime.Today;
                    productDiscountDraft.ValidUntil = DateTime.Today.AddYears(2);
                    productDiscountDraft.IsActive = true;
                    productDiscountDraft.Description = new LocalizedString {{"en", DescriptionProductDiscount}};
                    productDiscountDraft.SetPredicate(product => product.ProductId() == productId);

                    return productDiscountDraft;
                });
            return productDiscount;
        }

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 : PeriodYearSplitter.cs
with BSD 2-Clause "Simplified" License
from countincognito

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

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

[HttpPost]
        public IActionResult SetLanguage(string culture, string returnUrl)
        {
            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
                new CookieOptions { Expires = DateTime.UtcNow.AddYears(1) }
            );

            return LocalRedirect(returnUrl);
        }

19 Source : DatabaseInitializer.cs
with MIT License
from crmorgan

internal static IEnumerable<RoomRate> GetOneYearOfRates(int roomTypeId)
		{
				// Build a collection of room rates containing one rate that is good for a year from now.
				// Rate amount is calcuated/faked off the room type ids (1-4)
				yield return new RoomRate
				{
					RoomTypeId = roomTypeId,
					Amount = roomTypeId * 20m + 100.99m,
					CurrencyCode = CurrencyCodes.USD,
					StartDate = DateTime.Today,
					EndDate = DateTime.Today.AddYears(1)
				};
		}

19 Source : CarRepository.cs
with MIT License
from crowz4k

public static IList<CarDTO> GetCars()
        {
            return new List<CarDTO>()
            {
                new CarDTO{NameOfCar="Audi Q7",FirstRegistration = DateTime.UtcNow.AddYears(-3),MaxSpeed = 200,NumberOfDoors = 4},
                new CarDTO{NameOfCar="Audi A5",FirstRegistration = DateTime.UtcNow,MaxSpeed = 180,NumberOfDoors = 4},
                new CarDTO{NameOfCar="Audi Q3",FirstRegistration = DateTime.UtcNow,MaxSpeed = 245,NumberOfDoors = 2},
                new CarDTO{NameOfCar="Mercedes SLI",FirstRegistration = DateTime.UtcNow,MaxSpeed = 150,NumberOfDoors = 4},
                new CarDTO{NameOfCar="Chevrolet",FirstRegistration = DateTime.UtcNow,MaxSpeed = 220,NumberOfDoors = 4},
                new CarDTO{NameOfCar="BMW",FirstRegistration = DateTime.UtcNow,MaxSpeed = 200,NumberOfDoors = 4},
        };
        }

19 Source : DateScroller.cs
with MIT License
from cschladetsch

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

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

			for (int i = 0; i < steps; i++)
			{
				value = value.AddYears(step);

				var new_years = value.Year;
				if (new_years < DateMin.Year)
				{
					new_years = increase ? DateMax.Year : Mathf.Max(DateMin.Year, DateTime.MaxValue.Year - YearsStep);
				}

				if (new_years > DateMax.Year)
				{
					new_years = increase ? DateMin.Year : Mathf.Min(DateMax.Year, DateTime.MaxValue.Year - YearsStep);
				}

				if (value.Year != new_years)
				{
					value = value.AddYears(new_years - value.Year);
				}
			}

			return value;
		}

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 PrevYear()
		{
			if (!IsInteractable())
			{
				return;
			}

			DateDisplay = DateDisplay.AddYears(-1);
		}

19 Source : CalendarBase.cs
with MIT License
from cschladetsch

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

			DateDisplay = DateDisplay.AddYears(1);
		}

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 : InstanceStoreFactory.cs
with MIT License
from daenetCorporation

public static IOrchestrationServiceInstanceStore CreateInstanceStore(string hubName, string storageConnectionString, bool purgeStore = false)
        {
            IOrchestrationServiceInstanceStore instanceStore;

            if (storageConnectionString.ToLower().Contains("server=") || storageConnectionString.ToLower().Contains("data source="))
            {
                instanceStore = new SqlInstanceStore(hubName, storageConnectionString);
            }
            else
            {
                instanceStore = new AzureTableInstanceStore(hubName, storageConnectionString);
            }

            if (purgeStore)
            {
                instanceStore.InitializeStoreAsync(false).Wait();
                instanceStore.PurgeOrchestrationHistoryEventsAsync(DateTime.Now.AddYears(-1), OrchestrationStateTimeRangeFilterType.OrchestrationCreatedTimeFilter).Wait();
            }

            return instanceStore;
        }

See More Examples