System.DateTime.AddDays(double)

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

3989 Examples 7

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Main(string[] args)
        {
            var consolereplacedle = $"ACEmulator - v{ServerBuildInfo.FullVersion}";

            Console.replacedle = consolereplacedle;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);

            // Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not)
            // We do this because almost all of the client/user input/output code does not take culture into account, and replacedumes en-US formatting.
            // Without this, many commands that require special characters like , and . will break
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports.
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            // Look for the log4net.config first in the current environment directory, then in the Executingreplacedembly location
            var exeLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            var containerConfigDirectory = "/ace/Config";
            var log4netConfig = Path.Combine(exeLocation, "log4net.config");
            var log4netConfigExample = Path.Combine(exeLocation, "log4net.config.example");
            var log4netConfigContainer = Path.Combine(containerConfigDirectory, "log4net.config");

            if (IsRunningInContainer && File.Exists(log4netConfigContainer))
                File.Copy(log4netConfigContainer, log4netConfig, true);

            var log4netFileInfo = new FileInfo("log4net.config");
            if (!log4netFileInfo.Exists)
                log4netFileInfo = new FileInfo(log4netConfig);

            if (!log4netFileInfo.Exists)
            {
                var exampleFile = new FileInfo(log4netConfigExample);
                if (!exampleFile.Exists)
                {
                    Console.WriteLine("log4net Configuration file is missing.  Please copy the file log4net.config.example to log4net.config and edit it to match your needs before running ACE.");
                    throw new Exception("missing log4net configuration file");
                }
                else
                {
                    if (!IsRunningInContainer)
                    {
                        Console.WriteLine("log4net Configuration file is missing,  cloning from example file.");
                        File.Copy(log4netConfigExample, log4netConfig);
                    }
                    else
                    {                        
                        if (!File.Exists(log4netConfigContainer))
                        {
                            Console.WriteLine("log4net Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                            var log4netConfigDocker = Path.Combine(exeLocation, "log4net.config.docker");
                            File.Copy(log4netConfigDocker, log4netConfig);
                            File.Copy(log4netConfigDocker, log4netConfigContainer);
                        }
                        else
                        {
                            File.Copy(log4netConfigContainer, log4netConfig);
                        }

                    }
                }
            }

            var logRepository = LogManager.GetRepository(replacedembly.GetEntryreplacedembly());
            XmlConfigurator.ConfigureAndWatch(logRepository, log4netFileInfo);

            if (Environment.ProcessorCount < 2)
                log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server.");

            // Do system specific initializations here
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution
                    MM_BeginPeriod(1);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }

            log.Info("Starting ACEmulator...");

            if (IsRunningInContainer)
                log.Info("ACEmulator is running in a container...");
            
            var configFile = Path.Combine(exeLocation, "Config.js");
            var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js");

            if (IsRunningInContainer && File.Exists(configConfigContainer))
                File.Copy(configConfigContainer, configFile, true);

            if (!File.Exists(configFile))
            {
                if (!IsRunningInContainer)
                    DoOutOfBoxSetup(configFile);
                else
                {
                    if (!File.Exists(configConfigContainer))
                    {
                        DoOutOfBoxSetup(configFile);
                        File.Copy(configFile, configConfigContainer);
                    }
                    else
                        File.Copy(configConfigContainer, configFile);
                }
            }

            log.Info("Initializing ConfigManager...");
            ConfigManager.Initialize();

            if (ConfigManager.Config.Server.WorldName != "ACEmulator")
            {
                consolereplacedle = $"{ConfigManager.Config.Server.WorldName} | {consolereplacedle}";
                Console.replacedle = consolereplacedle;
            }

            if (ConfigManager.Config.Offline.PurgeDeletedCharacters)
            {
                log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})...");
                ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged);
                log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions.");
            }

            if (ConfigManager.Config.Offline.PurgeOrphanedBiotas)
            {
                log.Info($"Purging orphaned biotas...");
                ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged);
                log.Info($"Purged {numberOfBiotasPurged:N0} biotas.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromFriendLists)
            {
                log.Info($"Pruning invalid friends from all friend lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromFriendLists(out var numberOfFriendsPruned);
                log.Info($"Pruned {numberOfFriendsPruned:N0} invalid friends found on friend lists.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedObjectsFromShortcutBars)
            {
                log.Info($"Pruning invalid shortcuts from all shortcut bars...");
                ShardDatabaseOfflineTools.PruneDeletedObjectsFromShortcutBars(out var numberOfShortcutsPruned);
                log.Info($"Pruned {numberOfShortcutsPruned:N0} deleted objects found on shortcut bars.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromSquelchLists)
            {
                log.Info($"Pruning invalid squelches from all squelch lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromSquelchLists(out var numberOfSquelchesPruned);
                log.Info($"Pruned {numberOfSquelchesPruned:N0} invalid squelched characters found on squelch lists.");
            }

            if (ConfigManager.Config.Offline.AutoUpdateWorldDatabase)
            {
                CheckForWorldDatabaseUpdate();

                if (ConfigManager.Config.Offline.AutoApplyWorldCustomizations)
                    AutoApplyWorldCustomizations();
            }
            else
                log.Info($"AutoUpdateWorldDatabase is disabled...");

            if (ConfigManager.Config.Offline.AutoApplyDatabaseUpdates)
                AutoApplyDatabaseUpdates();
            else
                log.Info($"AutoApplyDatabaseUpdates is disabled...");

            // This should only be enabled manually. To enable it, simply uncomment this line
            //ACE.Database.OfflineTools.Shard.BiotaGuidConsolidator.ConsolidateBiotaGuids(0xC0000000, out int numberOfBiotasConsolidated, out int numberOfErrors);

            ShardDatabaseOfflineTools.CheckForBiotaPropertiesPaletteOrderColumnInShard();

            // pre-load starterGear.json, abort startup if file is not found as it is required to create new characters.
            if (Factories.StarterGearFactory.GetStarterGearConfiguration() == null)
            {
                log.Fatal("Unable to load or parse starterGear.json. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Initializing ServerManager...");
            ServerManager.Initialize();

            log.Info("Initializing DatManager...");
            DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true);

            log.Info("Initializing DatabaseManager...");
            DatabaseManager.Initialize();

            if (DatabaseManager.InitializationFailure)
            {
                log.Fatal("DatabaseManager initialization failed. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Starting DatabaseManager...");
            DatabaseManager.Start();

            log.Info("Starting PropertyManager...");
            PropertyManager.Initialize();

            log.Info("Initializing GuidManager...");
            GuidManager.Initialize();

            if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart)
            {
                log.Info("Server Performance Monitor auto starting...");
                ServerPerformanceMonitor.Start();
            }

            if (ConfigManager.Config.Server.WorldDatabasePrecaching)
            {
                log.Info("Precaching Weenies...");
                DatabaseManager.World.CacheAllWeenies();
                log.Info("Precaching Cookbooks...");
                DatabaseManager.World.CacheAllCookbooks();
                log.Info("Precaching Events...");
                DatabaseManager.World.GetAllEvents();
                log.Info("Precaching House Portals...");
                DatabaseManager.World.CacheAllHousePortals();
                log.Info("Precaching Points Of Interest...");
                DatabaseManager.World.CacheAllPointsOfInterest();
                log.Info("Precaching Spells...");
                DatabaseManager.World.CacheAllSpells();
                log.Info("Precaching Treasures - Death...");
                DatabaseManager.World.CacheAllTreasuresDeath();
                log.Info("Precaching Treasures - Material Base...");
                DatabaseManager.World.CacheAllTreasureMaterialBase();
                log.Info("Precaching Treasures - Material Groups...");
                DatabaseManager.World.CacheAllTreasureMaterialGroups();
                log.Info("Precaching Treasures - Material Colors...");
                DatabaseManager.World.CacheAllTreasureMaterialColor();
                log.Info("Precaching Treasures - Wielded...");
                DatabaseManager.World.CacheAllTreasureWielded();
            }
            else
                log.Info("Precaching World Database Disabled...");

            log.Info("Initializing PlayerManager...");
            PlayerManager.Initialize();

            log.Info("Initializing HouseManager...");
            HouseManager.Initialize();

            log.Info("Initializing InboundMessageManager...");
            InboundMessageManager.Initialize();

            log.Info("Initializing SocketManager...");
            SocketManager.Initialize();

            log.Info("Initializing WorldManager...");
            WorldManager.Initialize();

            log.Info("Initializing EventManager...");
            EventManager.Initialize();

            // Free up memory before the server goes online. This can free up 6 GB+ on larger servers.
            log.Info("Forcing .net garbage collection...");
            for (int i = 0 ; i < 10 ; i++)
                GC.Collect();

            // This should be last
            log.Info("Initializing CommandManager...");
            CommandManager.Initialize();

            if (!PropertyManager.GetBool("world_closed", false).Item)
            {
                WorldManager.Open(null);
            }
        }

19 View Source File : WeatherForecastService.cs
License : MIT License
Project Creator : ADefWebserver

public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
        {
            var rng = new Random();
            return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = startDate.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            }).ToArray());
        }

19 View Source File : TaskSchedulerServer.cs
License : Apache License 2.0
Project Creator : 91270

public async Task<ApiResult<string>> AddTaskScheduleAsync(Sys_TasksQz tasksQz)
        {
            try
            {
                JobKey jobKey = new JobKey(tasksQz.ID, tasksQz.JobGroup);
                if (await _scheduler.Result.CheckExists(jobKey))
                {
                    return new ApiResult<string>
                    {
                        StatusCode = 500,
                        Message = $"该计划任务已经在执行:【{tasksQz.Name}】,请勿重复添加!",
                    };
                }
                #region 设置开始时间和结束时间

                tasksQz.BeginTime = tasksQz.BeginTime == null ? DateTime.Now : tasksQz.BeginTime;
                tasksQz.EndTime = tasksQz.EndTime == null ? DateTime.MaxValue.AddDays(-1) : tasksQz.EndTime;

                DateTimeOffset starRunTime = DateBuilder.NextGivenSecondDate(tasksQz.BeginTime, 1);//设置开始时间
                DateTimeOffset endRunTime = DateBuilder.NextGivenSecondDate(tasksQz.EndTime, 1);//设置暂停时间

                #endregion

                #region 通过反射获取程序集类型和类   

                replacedembly replacedembly = replacedembly.Load(new replacedemblyName(tasksQz.replacedemblyName));
                Type jobType = replacedembly.GetType(tasksQz.replacedemblyName + "." + tasksQz.ClreplacedName);

                #endregion
                //判断任务调度是否开启
                if (!_scheduler.Result.IsStarted)
                {
                    await StartTaskScheduleAsync();
                }

                //传入反射出来的执行程序集
                IJobDetail job = new JobDetailImpl(tasksQz.ID, tasksQz.JobGroup, jobType);
                job.JobDataMap.Add("JobParam", tasksQz.JobParams);
                ITrigger trigger;

                if (tasksQz.Cron != null && CronExpression.IsValidExpression(tasksQz.Cron) && tasksQz.TriggerType > 0)
                {
                    trigger = CreateCronTrigger(tasksQz);
                }
                else
                {
                    trigger = CreateSimpleTrigger(tasksQz);
                }
                // 告诉Quartz使用我们的触发器来安排作业
                await _scheduler.Result.ScheduleJob(job, trigger);
                return new ApiResult<string>
                {
                    StatusCode = 200,
                    Message = $"启动计划任务:【{tasksQz.Name}】成功!",
                };
            }
            catch (Exception)
            {
                throw;
            }
        }

19 View Source File : RandomPricesDataSource.cs
License : MIT License
Project Creator : ABTSoftware

private DateTime EmulateDateGap(DateTime candleOpenTime)
        {
            DateTime result = candleOpenTime;
            TimeSpan timeOfDay = candleOpenTime.TimeOfDay;
            if (timeOfDay > _closeMarketTime)
            {
                DateTime dateTime = candleOpenTime.Date;
                dateTime = dateTime.AddDays(1.0);
                result = dateTime.Add(_openMarketTime);
            }
            while (result.DayOfWeek == DayOfWeek.Saturday || result.DayOfWeek == DayOfWeek.Sunday)
            {
                result = result.AddDays(1.0);
            }
            return result;
        }

19 View Source File : UserStatsGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<UserMonthlyCountStats>> GetUsersCountOverMonth()
        {
            var startDate = DateTime.UtcNow.AddDays(-31);
            var endDate = DateTime.UtcNow;

            var users = (from u in _usersRepo.Table.Where(uu => uu.CreatedAt >= startDate && uu.CreatedAt <= endDate)
                         group u by u.CreatedAt.Date into g
                         orderby g.Key
                         select new UserMonthlyCountStats
                         {
                             Count = g.Count(),
                             Day = g.Key
                         }).ToList();
            var days = Enumerable.Range(0, 31).Select(offset => endDate.AddDays(-offset)).ToList();

            days.ForEach(day =>
            {
                if (!users.Any(u => u.Day.Date == day.Date))
                {
                    users.Add(new UserMonthlyCountStats
                    {
                        Day = day.Date,
                        Count = 0
                    });
                }
            });

            users = users.OrderBy(u => u.Day.Date).ToList();

            return users;
        }

19 View Source File : DelayedQueue.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<bool> Publish<T>(int playerId, T t, int delayMin, int delayMax = 0)
        {
            var channel = t.GetType().Name.ToLower();

            Random rnd = new Random();
            var delay = delayMax > delayMin ? rnd.Next(delayMin, delayMax) : delayMin;
            var timestamp = DateTimeOffset.Now.AddSeconds(delay).ToUnixTimeSeconds();

            var hasAdd = await _redisDb.SortedSetAdd($"{queueName}_{channel}", playerId.ToString(), timestamp);
            if (hasAdd)
            {
                return await _redisDb.StringSet($"{queueName}_{channel}_{playerId}", t, DateTime.Now.AddSeconds(delay).AddDays(1));
            }
            return await Task.FromResult(false);
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private ServiceModel CreateServiceModel() {
			var descriptions = new string[] {
				"30K maintenance service",
				"60K maintenance service",
				"90K maintenance service",
				"Battery replacement",
				"Brake replacement",
				"Major engine repair",
				"Minor engine repair",
				"Oil change and lube service",
				"Tire repair",
				"Tire rotation and alignment",
				"Transmission repair",
			};

			var description = descriptions[random.Next(descriptions.Length)];
			var orderNumber = 30000 + random.Next(10000);
			var itemCount = (int)Math.Max(1, (-1 + random.Next(5)));
			var itemNumber = (int)(1 + random.Next(itemCount));
			var tomorrow = DateTime.Today.AddDays(1);
			var dueDate = new DateTime(tomorrow.Year, tomorrow.Month, tomorrow.Day, 9 + random.Next(12), 30 * random.Next(2), 0);
			var hours = 1 + random.Next(4);

			return new ServiceModel(description, orderNumber.ToString(), itemNumber, itemCount, dueDate, hours);
		}

19 View Source File : SolarWeek.cs
License : MIT License
Project Creator : 6tail

public SolarWeek next(int weeks, bool separateMonth)
        {
            if (0 == weeks)
            {
                return new SolarWeek(year, month, day, start);
            }
            if (separateMonth)
            {
                int n = weeks;
                DateTime c = ExactDate.fromYmd(year, month, day);
                SolarWeek week = new SolarWeek(c, start);
                int m = this.month;
                bool plus = n > 0;
                while (0 != n)
                {
                    c = c.AddDays(plus ? 7 : -7);
                    week = new SolarWeek(c, start);
                    int weekMonth = week.getMonth();
                    if (m != weekMonth)
                    {
                        int index = week.getIndex();
                        if (plus)
                        {
                            if (1 == index)
                            {
                                Solar firstDay = week.getFirstDay();
                                week = new SolarWeek(firstDay.getYear(), firstDay.getMonth(), firstDay.getDay(), start);
                                weekMonth = week.getMonth();
                            }
                            else
                            {
                                c = ExactDate.fromYmd(week.getYear(), week.getMonth(), 1);
                                week = new SolarWeek(c, start);
                            }
                        }
                        else
                        {
                            int size = SolarUtil.getWeeksOfMonth(week.getYear(), week.getMonth(), start);
                            if (size == index)
                            {
                                Solar firstDay = week.getFirstDay();
                                Solar lastDay = firstDay.next(6);
                                week = new SolarWeek(lastDay.getYear(), lastDay.getMonth(), lastDay.getDay(), start);
                                weekMonth = week.getMonth();
                            }
                            else
                            {
                                c = ExactDate.fromYmd(week.getYear(), week.getMonth(), SolarUtil.getDaysOfMonth(week.getYear(), week.getMonth()));
                                week = new SolarWeek(c, start);
                            }
                        }
                        m = weekMonth;
                    }
                    n -= plus ? 1 : -1;
                }
                return week;
            }
            else
            {
                DateTime c = ExactDate.fromYmd(year, month, day);
                c = c.AddDays(weeks * 7);
                return new SolarWeek(c, start);
            }
        }

19 View Source File : PollDataAdapter.cs
License : MIT License
Project Creator : Adoxio

protected IPoll SelectPoll(Predicate<Enreplacedy> match)
		{
			var serviceContext = Dependencies.GetServiceContextForWrite();
			var website = Dependencies.GetWebsite();

			// Bulk-load all poll enreplacedies into cache.
			var allEnreplacedies = serviceContext.CreateQuery("adx_poll")
				.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_websiteid").Id == website.Id)
				.ToArray();

			var now = DateTime.UtcNow;
			var enreplacedy = allEnreplacedies.FirstOrDefault(e => match(e) && IsActive(e)
				&& ((DateTime.Compare(e.GetAttributeValue<DateTime?>("adx_releasedate") ?? now, now.AddDays(1))) <= 0
					&& (DateTime.Compare(e.GetAttributeValue<DateTime?>("adx_expirationdate") ?? now, now)) >= 0));

			if (enreplacedy == null)
			{
				return null;
			}

			/*
			var securityProvider = Dependencies.GetSecurityProvider();

			if (!securityProvider.Tryreplacedert(serviceContext, enreplacedy, CrmEnreplacedyRight.Read))
			{
				return null;
			}
			*/

			return CreatePoll(enreplacedy, serviceContext);
		}

19 View Source File : Yun.cs
License : MIT License
Project Creator : 6tail

public Solar getStartSolar()
        {
            Solar birth = lunar.getSolar();
            DateTime c = ExactDate.fromYmd(birth.getYear(), birth.getMonth(), birth.getDay());
            c = c.AddYears(startYear);
            c = c.AddMonths(startMonth);
            c = c.AddDays(startDay);
            return Solar.fromDate(c);
        }

19 View Source File : TransactionTokenManager.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<TransactionToken> GenerateToken(Guid transactionId, TokenType type)
        {
            var(login, user)= await _userDataManager.AddCurrentUserIfNeeded();

            var tokenString = _stringGenerator.GenerateIdentifier(100, CharsInToken.CapitalSmallNumeric_);
            var token = new TransactionToken
            {
                TransactionTokenId = Guid.NewGuid(),
                IssuedAtUtc = DateTime.UtcNow,
                UseAfterUtc = DateTime.UtcNow,
                UseBeforeUtc = DateTime.UtcNow.AddDays(6),
                Status = TokenStatus.Ok,
                Token = tokenString,
                Type = type,
                IssuerLoginId = login.LoginId
            };

            if (type == TokenType.Receiving)
            {
                token.RegistrationId = transactionId;
            }
            else if (type == TokenType.Returning)
            {
                token.ReceivingId = transactionId;
            }

            var model = _tokensRepo.Add(token);
            await _tokensRepo.SaveChangesAsync();
            return model;
        }

19 View Source File : UserStatsGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<UserYearlyCountListStats> GetUsersCountOverTwoYears()
        {
            // end Date 6/4/ 2020
            // start date 1/1/2019
            // the stats will
            // CurrentYear : 1/1/20, 1/2/20, 1/3/20, 1/4/20, 1/5/20 = 0, 1/6/20 = 0, 1/7/20 = 0, ...
            // PreviousYear: 1/1/19, 1/2/19, 1/3/19, 1/4/19, 1/5/19 = x, 1/6/20 = y, 1/7/19 = z, ...
            var startDate = DateTime.UtcNow.AddYears(-1).AddMonths(-DateTime.UtcNow.Month + 1).AddDays(-DateTime.UtcNow.Day + 1).Date;
            var endDate = DateTime.UtcNow.Date;

            var usersMonthly = (from u in _usersRepo.Table
                                where u.CreatedAt >= startDate && u.CreatedAt <= endDate
                                group u by new
                                {
                                    u.CreatedAt.Year,
                                    u.CreatedAt.Month
                                } into g
                                select new
                                {
                                    Count = g.Count(),
                                    MonthYear = new DateTime(g.Key.Year, g.Key.Month, 1)
                                }).ToList();

            var months = Enumerable.Range(0, 24).Select(offset => startDate.AddMonths(offset)).ToList();

            months.ForEach(month =>
            {
                if (!usersMonthly.Any(u => u.MonthYear.Year == month.Year && u.MonthYear.Month == month.Month))
                {
                    usersMonthly.Add(new
                    {
                        Count = 0,
                        MonthYear = month,
                    });
                }
            });

            return new UserYearlyCountListStats()
            {
                CurrentYear = usersMonthly.Where(um => um.MonthYear.Year == DateTime.UtcNow.Year).OrderBy(c => c.MonthYear).Select(c => c.Count).ToList(),
                PreviousYear = usersMonthly.Where(um => um.MonthYear.Year == DateTime.UtcNow.Year - 1).OrderBy(c => c.MonthYear).Select(c => c.Count).ToList()
            };
        }

19 View Source File : MudOnlineProvider.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task SetConnectionId(int playerId, string connectionId)
        {
            var key = "ConnectionId_" + playerId;
            await _db.StringSet(key, connectionId,DateTime.Now.AddDays(30));
        }

19 View Source File : FileCacheTest.cs
License : Apache License 2.0
Project Creator : acarteas

[TestMethod]
        public void FlushTest()
        {
            _cache = new FileCache("FlushTest");

            _cache.Add("Key1", "Value1", _cache.DefaultPolicy);
            _cache.Add("Key2", "Value2", DateTime.Now.AddDays(1), "Region1");
            Thread.Sleep(500);

            //attempt flush
            _cache.Flush(DateTime.Now.AddDays(1));

            Thread.Sleep(500);

            //check to see if size ends up at zero (expected result)
            _cache.GetCacheSize().Should().Be(0);
        }

19 View Source File : DateTimeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

public DateTime GenerateDateTimeBetween(DateTime minValue, DateTime maxValue)
        {
            var nbDays = (maxValue - minValue).Days;

            var midInterval = (minValue.AddDays(nbDays/2));

            var maxDaysAllowedBefore = (midInterval - minValue).Days;
            var maxDaysAllowedAfter = (maxValue - midInterval).Days;
            var maxDays = Math.Min(maxDaysAllowedBefore, maxDaysAllowedAfter);

            return midInterval.AddDays(_fuzzer.GenerateInteger(-maxDays, maxDays));
        }

19 View Source File : DocumentReferenceGenerator.cs
License : MIT License
Project Creator : Actipro

private static void AddDoreplacedentReference(RecentDoreplacedentManager manager, Uri uri, bool isPinned) {
			DoreplacedentReference docRef = new DoreplacedentReference(uri);
			docRef.LastOpenedDateTime = DateTime.Now.AddDays(-1 * manager.Doreplacedents.Count);;
			docRef.IsPinnedRecentDoreplacedent = isPinned;
			docRef.Description = "Rich-text file";
			docRef.ImageSourceSmall = new BitmapImage(new Uri("/Images/Icons/RichTextDoreplacedent16.png", UriKind.Relative));
			docRef.ImageSourceLarge = new BitmapImage(new Uri("/Images/Icons/RichTextDoreplacedent32.png", UriKind.Relative));
			manager.Doreplacedents.Add(docRef);
		}

19 View Source File : RelationCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Unit> Handle(RefuseFriendCommand command, CancellationToken cancellationToken)
        {
            var playerId = command.PlayerId;
            var relationId = command.RelationId;
            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            var relation = await _playerDomainService.Get(relationId);
            if (relation == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            var playerRelationFrom = await _playerRelationDomainService.Get(x => x.PlayerId == relationId && x.RelationId == playerId && x.Type == PlayerRelationTypeEnum.好友);
            if (playerRelationFrom == null)
            {
                await _mudProvider.ShowMessage(player.Id, $"【好友】[{relation.Name}]没有申请加你为好友,或者已撤销申请。");
                return Unit.Value;
            }

            var playerRelationTo = await _playerRelationDomainService.Get(x => x.PlayerId == playerId && x.RelationId == relationId && x.Type == PlayerRelationTypeEnum.好友);
            if (playerRelationTo != null)
            {
                await _mudProvider.ShowMessage(player.Id, $"【好友】你和[{relation.Name}]已经是好友了。");
                return Unit.Value;
            }


            await _playerRelationDomainService.Delete(playerRelationFrom);

            //1天内不得重复申请
            await _redisDb.StringSet(string.Format(RedisKey.RefuseFriend, relationId, playerId), 1, DateTime.Now.AddDays(1));

            await _mudProvider.ShowMessage(player.Id, $"【好友】你拒绝了[{relation.Name}]的好友申请。");

            var content = $"【好友】[{player.Name}]拒绝了你的好友申请。";

            await _emailDomainService.Add(new EmailEnreplacedy
            {
                ExpiryDate = DateTime.Now.AddDays(30),
                SendDate = DateTime.Now,
                replacedle = $"[{player.Name}]拒绝了你的好友申请",
                Content = content,
                Type = EmailTypeEnum.系统,
                TypeId = relation.Id
            });


            await _mudProvider.ShowMessage(relation.Id, content);

            return Unit.Value;
        }

19 View Source File : AopCacheAttribute.cs
License : MIT License
Project Creator : ad313

private DateTime GetCacheNewTime(CacheTimeType type, int length)
        {
            if (length <= 0) return DateTime.MaxValue;

            var limitTime = DateTime.Now;
            switch (type)
            {
                case CacheTimeType.Day:
                    limitTime = limitTime.AddDays(length);
                    break;
                case CacheTimeType.Hour:
                    limitTime = limitTime.AddHours(length);
                    break;
                case CacheTimeType.Minute:
                    limitTime = limitTime.AddMinutes(length);
                    break;
                case CacheTimeType.Second:
                    limitTime = limitTime.AddSeconds(length);
                    break;
            }

            return limitTime;
        }

19 View Source File : BuildWindow.cs
License : MIT License
Project Creator : 1ZouLTReX1

static string PrettyPrintTimeStamp(DateTime time)
    {
        var span = DateTime.Now - time;
        if (span.TotalMinutes < 60)
            return span.Minutes + " mins ago";
        if (DateTime.Now.Date == time.Date)
            return time.ToShortTimeString() + " today";
        if (DateTime.Now.Date.AddDays(-1) == time.Date)
            return time.ToShortTimeString() + " yesterday";
        return "" + time;
    }

19 View Source File : PollDataAdapter.cs
License : MIT License
Project Creator : Adoxio

private IPollPlacement CreatePollPlacement(Enreplacedy enreplacedy, OrganizationServiceContext serviceContext)
		{
			var polls = enreplacedy.GetRelatedEnreplacedies(serviceContext, new Relationship("adx_pollplacement_poll"))
				.Where(e => ((DateTime.Compare(e.GetAttributeValue<DateTime?>("adx_releasedate") ?? DateTime.UtcNow,
					DateTime.UtcNow.AddDays(1))) <= 0
					&& (DateTime.Compare(e.GetAttributeValue<DateTime?>("adx_expirationdate") ?? DateTime.UtcNow,
						DateTime.UtcNow)) >= 0))
				.Where(IsActive)
				.Select(e => CreatePoll(e, serviceContext));

			var pollPlacement = new PollPlacement(enreplacedy, polls);

			return pollPlacement;
		}

19 View Source File : RegCommand.cs
License : Apache License 2.0
Project Creator : AantCoder

public string Execute(SocketCommandContext context, string ip, string token)
        {
            try
            {
                IPEndPoint serverAdr;
                var message = CanExecute(context, ip, token, out serverAdr);
                if (!string.IsNullOrEmpty(message))
                {
                    return message;
                }

                try
                {
                    new TcpClient(serverAdr.Address.ToString(), serverAdr.Port);
                }
                catch
                (Exception ex)
                {
                    return Languages.Translator.ErrServerNotAvailable + "\n" + ex.Message;
                }

                var client = new SessionClient();
                if (!client.Connect(serverAdr.Address.ToString(), serverAdr.Port))
                {
                    return Languages.Translator.ErrServerNotAvailable;
                }

                var preplaced = new CryptoProvider().GetHash(token);
                if (!client.Login(SessionClientWrapper.DiscrodLogin, preplaced, null))
                {
                    return Languages.Translator.ErrInvalidToken;
                }

                var channelToServer = new Chanel2Server()
                {
                    Id = context.Channel.Id,
                    IP = serverAdr.Address.ToString(),
                    Port = serverAdr.Port,
                    LinkCreator = context.Message.Author.Id,
                    LastOnlineTime = DateTime.UtcNow.AddDays(-1),
                    Token = token,
                    LastRecivedPostIndex = -1,
                };

                //


                _appContext.RegisterNewServer(channelToServer, new SessionClientWrapper(channelToServer, client));
                context.Message.DeleteAsync();

                return string.Format(Languages.Translator.InfServerReg, serverAdr.ToString(), "#" + context.Channel.Name);
            }
            catch (Exception ex)
            {
                Loger.Log(ex.ToString());
                return "Internal error";
            }
        }

19 View Source File : UserStatsGetterTests.cs
License : MIT License
Project Creator : Abdulrhman5

[TestMethod]
        public async Task UsersCountOverMonth_ThereIsDescreteData_ShouldReturn31Element()
        {
            var userRepo = new Mock<IRepository<string, AppUser>>();
            var getter = new UserStatsGetter(userRepo.Object);
            var users = new List<AppUser>
            {
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-2),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-2),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-2),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-5),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-30),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-30),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-31),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-40),
                },
            };

            userRepo.Setup(u => u.Table).Returns(users.AsQueryable());

            var result = await getter.GetUsersCountOverMonth();

            replacedert.IsTrue(result.Count == 31 && result[0].Count == 2 && result[25].Count == 1 && result[28].Count == 3);
        }

19 View Source File : DateTimeFuzzerShould.cs
License : Apache License 2.0
Project Creator : 42skillz

private static void CheckThatEveryDateTimeBelongsToTheInclusiveTimeRange(HashSet<DateTime> generatedDateTimes,
            string minDate, string maxDate)
        {
            var minDateOk = DateTime.TryParseExact(minDate, "yyyy/MM/dd", null, DateTimeStyles.None, out var minDateTime);
            var maxDateOk = DateTime.TryParseExact(maxDate, "yyyy/MM/dd", null, DateTimeStyles.None, out var maxDateTime);

            foreach (var generatedDateTime in generatedDateTimes)
            {
                Check.That(generatedDateTime).IsBefore(maxDateTime.AddDays(1)).And.IsAfter(minDateTime.AddDays(-1));
            }
        }

19 View Source File : UserStatsGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<int>> GetUsersCountOverToday()
        {
            // This will resolve to MM/DD/YYYY 00:00:00
            var startDate = DateTime.UtcNow.Date;

            // This will resolve to MM/DD+1/YYYY 00:00:00
            var endDate = DateTime.UtcNow.Date.AddDays(1);

            var usersHourly = (from u in _usersRepo.Table
                               where u.CreatedAt >= startDate && u.CreatedAt <= endDate
                               group u by new
                               {
                                   u.CreatedAt.Date,
                                   u.CreatedAt.Hour
                               } into g
                               select new
                               {
                                   Count = g.Count(),
                                   Date = g.Key.Date,
                                   Hour = g.Key.Hour
                               }).ToList();
            var usersHourlyFormated = usersHourly.Select(u => new
            {
                Count = u.Count,
                DateTime = new DateTime(u.Date.Year, u.Date.Month, u.Date.Day, u.Hour, 0, 0)
            }).ToList();

            var hours = Enumerable.Range(0, 24).Select(offset =>
            {

                var dateTime = startDate.AddHours(offset);
                return dateTime;
            }).ToList();

            hours.ForEach(hour =>
            {
                if (!usersHourlyFormated.Any(u => u.DateTime == hour))
                {
                    usersHourlyFormated.Add(new
                    {
                        Count = 0,
                        DateTime = hour
                    });
                }
            });
            usersHourlyFormated = usersHourlyFormated.OrderBy(u => u.DateTime).ToList();

            var stats = usersHourlyFormated.Select(u => u.Count).ToList();
            return stats;
        }

19 View Source File : PlayerActionCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private async Task Friend(PlayerEnreplacedy player, PlayerEnreplacedy relation)
        {

            if (await _redisDb.StringGet<int>(string.Format(RedisKey.RefuseFriend, player.Id, relation.Id)) > 0)
            {
                await _mudProvider.ShowMessage(player.Id, $"【好友】[{relation.Name}]已拒绝你的申请。");
                return;
            }

            //我加对方
            var playerRelationFrom = await _playerRelationDomainService.Get(x => x.PlayerId == player.Id
                && x.RelationId == relation.Id
                && x.Type == PlayerRelationTypeEnum.好友);

            //对方加我
            var playerRelationTo = await _playerRelationDomainService.Get(x => x.PlayerId == relation.Id
                && x.RelationId == player.Id
                && x.Type == PlayerRelationTypeEnum.好友);



            if (playerRelationFrom != null && playerRelationTo != null)
            {
                if (playerRelationTo != null)
                {
                    await _mudProvider.ShowMessage(player.Id, $"【好友】你们已经是好友。");
                    return;
                }
                else
                {
                    await _mudProvider.ShowMessage(player.Id, $"【好友】你已申请加[{relation.Name}]为好友,请等待对方同意。");
                    return;
                }

            }



            if (playerRelationFrom == null)
            {
                if(playerRelationTo == null)
                {

                    await _mudProvider.ShowMessage(player.Id, $"【好友】你申请加[{relation.Name}]为好友,请等待对方同意。");

                    var content = $"【好友】[{player.Name}]想和你成为好友,到 '社交'->'好友' 界面可以同意或拒绝对方的申请,你也可以直接添加对方为好友。";

                    await _emailDomainService.Add(new EmailEnreplacedy
                    {
                        ExpiryDate = DateTime.Now.AddDays(30),
                        SendDate = DateTime.Now,
                        replacedle = $"{player.Name}想和你成为好友",
                        Content = content,
                        Type = EmailTypeEnum.系统,
                        TypeId = relation.Id
                    });


                    await _mudProvider.ShowMessage(relation.Id, content);
                }
                else
                {
                    await _mudProvider.ShowMessage(player.Id, $"【好友】你成功添加[{relation.Name}]为好友。");


                    var content = $"【好友】[{player.Name}]同意了你的申请,你们已成为了好友。";

                    await _emailDomainService.Add(new EmailEnreplacedy
                    {
                        ExpiryDate = DateTime.Now.AddDays(30),
                        SendDate = DateTime.Now,
                        replacedle = $"{player.Name}同意了你的好友申请",
                        Content = content,
                        Type = EmailTypeEnum.系统,
                        TypeId = relation.Id
                    });


                    await _mudProvider.ShowMessage(relation.Id, content);
                }


                playerRelationFrom = new PlayerRelationEnreplacedy
                {
                    CreatedTime = DateTime.Now,
                    PlayerId = player.Id,
                    RelationId = relation.Id,
                    Type = PlayerRelationTypeEnum.好友
                };
                await _playerRelationDomainService.Add(playerRelationFrom);



                await _queueHandler.SendQueueMessage(new ReceiveEmailQueue(relation.Id));
            }

        }

19 View Source File : TransactionStatsQueriesHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<int>> Handle(TransactionStatsOverYearQuery request, CancellationToken cancellationToken)
        {
            // end Date 6/4/ 2020
            // start date 1/1/2019
            // the stats will
            // CurrentYear : 1/1/20, 1/2/20, 1/3/20, 1/4/20, 1/5/20 = 0, 1/6/20 = 0, 1/7/20 = 0, ...
            var startDate = DateTime.UtcNow.AddMonths(-DateTime.UtcNow.Month + 1).AddDays(-DateTime.UtcNow.Day + 1).Date;
            var endDate = DateTime.UtcNow.Date.AddDays(1);

            var transesMonthly = (from r in _receivingsRepo.Table
                                  where
                                     r.ReceivedAtUtc >= startDate && r.ReceivedAtUtc <= endDate
                                  group r by new
                                  {
                                      r.ReceivedAtUtc.Year,
                                      r.ReceivedAtUtc.Month
                                  } into g
                                  select new
                                  {
                                      Count = g.Count(),
                                      MonthYear = new DateTime(g.Key.Year, g.Key.Month, 1)
                                  }).ToList();

            var months = Enumerable.Range(0, 12).Select(offset => startDate.AddMonths(offset)).ToList();

            months.ForEach(month =>
            {
                if (!transesMonthly.Any(u => u.MonthYear.Year == month.Year && u.MonthYear.Month == month.Month))
                {
                    transesMonthly.Add(new
                    {
                        Count = 0,
                        MonthYear = month,
                    });
                }
            });

            return transesMonthly.Select(m => m.Count).ToList();
        }

19 View Source File : TransactionStatsQueriesHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<TransactionTodayStatsDto> Handle(TransactionStatsOverTodayQuery request, CancellationToken cancellationToken)
        {
            // This will resolve to MM/DD/YYYY 00:00:00
            var startDate = DateTime.UtcNow.Date;

            // This will resolve to MM/DD+1/YYYY 00:00:00
            var endDate = DateTime.UtcNow.Date.AddDays(1);

            var transesHourly = (from r in _receivingsRepo.Table
                                 where r.ReceivedAtUtc >= startDate && r.ReceivedAtUtc <= endDate
                                 group r by new
                                 {
                                     r.ReceivedAtUtc.Date,
                                     r.ReceivedAtUtc.Hour,
                                 } into g
                                 select new
                                 {
                                     Count = g.Count(),
                                     Date = g.Key.Date,
                                     Hour = g.Key.Hour
                                 });
            var transesHourlyFormated = transesHourly.Select(r => new
            {
                r.Count,
                DateTime = new DateTime(r.Date.Year, r.Date.Month, r.Date.Day, r.Hour, 0, 0)
            }).ToList();

            var hours = Enumerable.Range(0, 24).Select(offset =>
            {

                var dateTime = startDate.AddHours(offset);
                return dateTime;
            }).ToList();

            hours.ForEach(hour =>
            {
                if (!transesHourlyFormated.Any(t => t.DateTime == hour))
                {
                    transesHourlyFormated.Add(new
                    {
                        Count = 0,
                        DateTime = hour
                    });
                }
            });

            transesHourlyFormated = transesHourlyFormated.OrderBy(t => t.DateTime).ToList();
            var stats = transesHourlyFormated.Select(t => t.Count).ToList();

            var transactions = from r in _registrationsRepo.Table
                               where r.ShouldReturnItAfter.HasValue && r.Status == ObjectRegistrationStatus.OK
                               select r;
            var late = transactions
                .AsEnumerable()
                .Count(r => r.ObjectReceiving != null &&
                    r.ObjectReceiving.ObjectReturning != null &&
                    (r.ObjectReceiving.ReceivedAtUtc + r.ShouldReturnItAfter.Value) > r.ObjectReceiving.ObjectReturning.ReturnedAtUtc.AddMinutes(30));
            var notReturned = transactions.Count(r => r.ObjectReceiving != null && r.ObjectReceiving.ObjectReturning == null);
            var onTime = transactions
                .AsEnumerable()
                .Count(r => r.ObjectReceiving != null &&
                    r.ObjectReceiving.ObjectReturning != null &&
                    r.ObjectReceiving.ReceivedAtUtc.Add(r.ShouldReturnItAfter.Value) <= r.ObjectReceiving.ObjectReturning.ReturnedAtUtc.AddMinutes(30));

            return new TransactionTodayStatsDto
            {
                LateReturn = late,
                NotReturnedYet = notReturned,
                OnTimeReturn = onTime,
                TransactionsOverToday = stats
            };
        }

19 View Source File : NpcEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(ChatWithNpcEvent message, CancellationToken cancellationToken)
        {
            var playerId = message.PlayerId;
            var npcId = message.NpcId;

            await _redisDb.StringSet<int>(string.Format(RedisKey.ChatWithNpc, playerId, npcId), 1, DateTime.Now.AddDays(30));
            await _redisDb.StringSet<int>(string.Format(RedisKey.ChatWithNpcLike, playerId, npcId), 1, DateTime.Now.AddHours(1));
        }

19 View Source File : UniformHeatmapAndPaletteProvider.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private IDataSeries CreateSeries()
        {
            double angle = Math.Round(Math.PI * 2 * 1 / 30, 3);
            int w = 300, h = 200;
            var data = new double[h, w];
            for (int x = 0; x < w; x++)
                for (int y = 0; y < h; y++)
                {
                    var v = (1 + Math.Round(Math.Sin(x * 0.04 + angle), 3)) * 50 + (1 + Math.Round(Math.Sin(y * 0.1 + angle), 3)) * 50 * (1 + Math.Round(Math.Sin(angle * 2), 3));
                    var cx = 150; var cy = 100;
                    var r = Math.Sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));
                    var exp = Math.Max(0, 1 - r * 0.008);
                    data[y, x] = (v * exp + _random.NextDouble() * 50);
                }

            var xStart = new DateTime(2017, 1, 13, 0, 0, 0);
            var xStep = DateTime.MinValue.AddDays(1).AddHours(6).AddMinutes(30);
            return new UniformHeatmapDataSeries<DateTime, int, double>(data, xStart, xStep, 0, 2) { SeriesName = "UniformHeatmap" };
        }

19 View Source File : DateTimeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

public DateTime GenerateDateTimeBetween(DateTime minValue, DateTime maxValue)
        {
            var nbDays = (maxValue - minValue).Days;

            var midInterval = (minValue.AddDays(nbDays/2));

            var maxDaysAllowedBefore = (midInterval - minValue).Days;
            var maxDaysAllowedAfter = (maxValue - midInterval).Days;
            var maxDays = Math.Min(maxDaysAllowedBefore, maxDaysAllowedAfter);

            return midInterval.AddDays(_fuzzer.GenerateInteger(-maxDays, maxDays));
        }

19 View Source File : FileCacheTest.cs
License : Apache License 2.0
Project Creator : acarteas

[TestMethod]
        public void AbsoluteExpirationTest()
        {
            _cache = new FileCache();
            CacheItemPolicy policy = new CacheItemPolicy();

            //add an item and have it expire yesterday
            policy.AbsoluteExpiration = (DateTimeOffset)DateTime.Now.AddDays(-1);
            _cache.Set("test", "test", policy);

            //then try to access the item
            object result = _cache.Get("test");
            result.Should().BeNull();
        }

19 View Source File : PlayerActionCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private async Task UnFriend(PlayerEnreplacedy player, PlayerEnreplacedy relation)
        {

            //我加对方
            var playerRelationFrom = await _playerRelationDomainService.Get(x => x.PlayerId == player.Id
                && x.RelationId == relation.Id
                && x.Type == PlayerRelationTypeEnum.好友);

            //对方加我
            var playerRelationTo = await _playerRelationDomainService.Get(x => x.PlayerId == relation.Id
                && x.RelationId == player.Id
                && x.Type == PlayerRelationTypeEnum.好友);



            if (playerRelationFrom != null && playerRelationTo != null)
            {
                await _playerRelationDomainService.Delete(playerRelationFrom);

                await _playerRelationDomainService.Delete(playerRelationTo);

                //1天内不得重复申请
                await _redisDb.StringSet(string.Format(RedisKey.RefuseFriend, relation.Id, player.Id), 1, DateTime.Now.AddDays(1));

                await _mudProvider.ShowMessage(player.Id, $"【好友】你已经与[{relation.Name}]取消好友关系。");

                var content = $"【好友】[{player.Name}]已经与你取消好友关系。";

                await _emailDomainService.Add(new EmailEnreplacedy
                {
                    ExpiryDate = DateTime.Now.AddDays(30),
                    SendDate = DateTime.Now,
                    replacedle = $"{player.Name}与你取消好友关系",
                    Content = content,
                    Type = EmailTypeEnum.系统,
                    TypeId = relation.Id
                });


                await _mudProvider.ShowMessage(relation.Id, content);
            }
            else
            {
                await _mudProvider.ShowMessage(player.Id, $"【好友】你们并不是好友。");
            }
        }

19 View Source File : SentinelCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[CommandHandler("ban", AccessLevel.Sentinel, CommandHandlerFlag.None, 4,
            "Bans the specified player account.",
            "[accountname] [days] [hours] [minutes] (reason)\n"
            + "This command bans the specified player account for the specified time. This player will not be able to enter the game with any character until the time expires.\n"
            + "Example: @ban AccountName 0 0 5\n"
            + "Example: @ban AccountName 1 0 0 banned 1 day because reasons\n")]
        public static void HandleBanAccount(Session session, params string[] parameters)
        {
            // usage: @ban < acct > < days > < hours > < minutes >
            // This command bans the specified player account for the specified time.This player will not be able to enter the game with any character until the time expires.
            // @ban - Bans the specified player account.

            var accountName = parameters[0];
            var banDays     = parameters[1];
            var banHours    = parameters[2];
            var banMinutes  = parameters[3];

            var banReason = string.Empty;
            if (parameters.Length > 4)
            {
                var parametersAfterBanParams = "";
                for (var i = 4; i < parameters.Length; i++)
                {
                    parametersAfterBanParams += parameters[i] + " ";
                }
                parametersAfterBanParams = parametersAfterBanParams.Trim();
                banReason = parametersAfterBanParams;
            }

            var account = DatabaseManager.Authentication.GetAccountByName(accountName);

            if (account == null)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Cannot ban \"{accountName}\" because that account cannot be found in database. Check syntax/spelling and try again.", ChatMessageType.Broadcast);
                return;
            }

            if (!double.TryParse(banDays, out var days) || days < 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Days must not be less than 0.", ChatMessageType.Broadcast);
                return;
            }
            if (!double.TryParse(banHours, out var hours) || hours < 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Hours must not be less than 0.", ChatMessageType.Broadcast);
                return;
            }
            if (!double.TryParse(banMinutes, out var minutes) || minutes < 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Minutes must not be less than 0.", ChatMessageType.Broadcast);
                return;
            }

            var bannedOn = DateTime.UtcNow;
            var banExpires = DateTime.UtcNow.AddDays(days).AddHours(hours).AddMinutes(minutes);

            var bannedBy = 0u;
            if (session != null)
            {
                bannedBy = session.AccountId;
            }

            account.BannedTime = bannedOn;
            account.BanExpireTime = banExpires;
            account.BannedByAccountId = bannedBy;
            if (!string.IsNullOrWhiteSpace(banReason))
                account.BanReason = banReason;

            DatabaseManager.Authentication.UpdateAccount(account);

            // Boot the player
            if (NetworkManager.Find(accountName) != null)
            {
                var bootArgs = new List<string> { "account" };
                if (!string.IsNullOrWhiteSpace(banReason))
                {
                    bootArgs.Add($"{accountName},");
                    bootArgs.Add(banReason);
                }
                else
                    bootArgs.Add(accountName);
                HandleBoot(session, bootArgs.ToArray());
            }

            var banText = $"Banned account {accountName} for {days} days, {hours} hours and {minutes} minutes.{(!string.IsNullOrWhiteSpace(banReason) ? $" Reason: {banReason}" : "")}";
            CommandHandlerHelper.WriteOutputInfo(session, banText, ChatMessageType.Broadcast);
            PlayerManager.BroadcastToAuditChannel(session?.Player, banText);
        }

19 View Source File : DefaultJwtTokenStorageProvider.cs
License : MIT License
Project Creator : 17MKH

public async Task Save(JwtResultModel model, List<Claim> claims)
    {
        var enreplacedy = await _repository.Find(m => m.AccountId == model.AccountId && m.Platform == model.Platform)
            .ToFirst();

        var exists = true;
        if (enreplacedy == null)
        {
            exists = false;
            enreplacedy = new JwtAuthInfoEnreplacedy
            {
                AccountId = model.AccountId,
                Platform = model.Platform
            };
        }

        enreplacedy.LoginIP = claims.First(m => m.Type == MkhClaimTypes.IP).Value;
        enreplacedy.LoginTime = claims.First(m => m.Type == MkhClaimTypes.LOGIN_TIME).Value.ToLong();
        enreplacedy.RefreshToken = model.RefreshToken;

        //默认刷新令牌有效期7天
        enreplacedy.RefreshTokenExpiredTime = DateTime.Now.AddDays(_jwtOptions.RefreshTokenExpires <= 0 ? 7 : _jwtOptions.RefreshTokenExpires);

        if (exists)
        {
            await _repository.Update(enreplacedy);
        }
        else
        {
            await _repository.Add(enreplacedy);
        }

        //刷新令牌加入缓存
        await _cacheHandler.Set(_cacheKeys.RefreshToken(model.AccountId, model.Platform), model.RefreshToken, enreplacedy.RefreshTokenExpiredTime);
    }

19 View Source File : HostTraceListener.cs
License : MIT License
Project Creator : actions

private StreamWriter CreatePageLogWriter()
        {
            if (_enableLogRetention)
            {
                DirectoryInfo diags = new DirectoryInfo(_logFileDirectory);
                var logs = diags.GetFiles($"{_logFilePrefix}*.log");
                foreach (var log in logs)
                {
                    if (log.LastWriteTimeUtc.AddDays(_retentionDays) < DateTime.UtcNow)
                    {
                        try
                        {
                            log.Delete();
                        }
                        catch (Exception)
                        {
                            // catch Exception and continue
                            // we shouldn't block logging and fail the runner if the runner can't delete an older log file.
                        }
                    }
                }
            }

            string fileName = StringUtil.Format(_logFileNamingPattern, _logFilePrefix, DateTime.UtcNow);
            string logFile = Path.Combine(_logFileDirectory, fileName);
            Stream logStream;
            if (File.Exists(logFile))
            {
                logStream = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Read, bufferSize: 4096);
            }
            else
            {
                logStream = new FileStream(logFile, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize: 4096);
            }

            return new StreamWriter(logStream);
        }

19 View Source File : RelationCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Unit> Handle(AgreeFriendCommand command, CancellationToken cancellationToken)
        {
            var playerId = command.PlayerId;
            var relationId = command.RelationId;
            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            var relation = await _playerDomainService.Get(relationId);
            if (relation == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            var playerRelationFrom = await _playerRelationDomainService.Get(x => x.PlayerId == relationId && x.RelationId == playerId && x.Type == PlayerRelationTypeEnum.好友);
            if (playerRelationFrom == null)
            {
                await _mudProvider.ShowMessage(player.Id, $"【好友】[{relation.Name}]没有申请加你为好友,或者已撤销申请。");
                return Unit.Value;
            }

            var playerRelationTo = await _playerRelationDomainService.Get(x => x.PlayerId == playerId && x.RelationId == relationId && x.Type == PlayerRelationTypeEnum.好友);
            if (playerRelationTo != null)
            {
                await _mudProvider.ShowMessage(player.Id, $"【好友】你和[{relation.Name}]已经是好友了。");
                return Unit.Value;
            }


            playerRelationTo = new PlayerRelationEnreplacedy
            {
                PlayerId = playerId,
                RelationId = relationId,
                Type = PlayerRelationTypeEnum.好友,
                CreatedTime = DateTime.Now
            };
            await _playerRelationDomainService.Add(playerRelationTo);

            await _mudProvider.ShowMessage(player.Id, $"【好友】你同意了[{relation.Name}]的好友申请。");

            var content = $"【好友】[{player.Name}]同意了你的申请,你们已成为了好友。";

            await _emailDomainService.Add(new EmailEnreplacedy
            {
                ExpiryDate = DateTime.Now.AddDays(30),
                SendDate = DateTime.Now,
                replacedle = $"{player.Name}同意了你的好友申请",
                Content = content,
                Type = EmailTypeEnum.系统,
                TypeId = relation.Id
            });


            await _mudProvider.ShowMessage(relation.Id, content);

            return Unit.Value;
        }

19 View Source File : TimeAggregatedDataGenerator.cs
License : MIT License
Project Creator : Actipro

public void Generate() {
			// Create a random number generator
			var resolvedRandomSeed = randomSeed ?? Environment.TickCount;
			var random = new Random(resolvedRandomSeed);

			// Initialize the date
			DateTime date;
			var resolvedDataPointCount = this.DataPointCount;
			switch (timePeriod) {
				case TimePeriod.Month:
					date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
					date = date.AddMonths(-resolvedDataPointCount);
					break;
				case TimePeriod.Week:
					date = DateTime.Today;
					date = date.AddDays(-resolvedDataPointCount * 7);
					break;
				default:  // Year
					date = new DateTime(DateTime.Today.Year, 1, 1);
					date = date.AddYears(-resolvedDataPointCount);
					break;
			}

			// Initialize the results with the first data item
			this.BeginUpdate();
			try {
				this.Clear();

				// Quit if there are no data points
				if (resolvedDataPointCount == 0)
					return;
				
				// Determine the trend percentage
				double trendPercentage;
				switch (trend) {
					case Trend.Upward:
						trendPercentage = 0.3;
						break;
					case Trend.Downward:
						trendPercentage = 0.7;
						break;
					default:  // Random
						trendPercentage = 0.5;
						break;
				}

				// Get the first amount
				var delta = Convert.ToDouble(trendPercentage) * this.StepRange;
				var step = Convert.ToDouble(random.NextDouble()) * this.StepRange;
				var firstAmount = (presetAmounts != null ? presetAmounts[0] : this.StartAmount + step - delta);
				this.Add(this.CreateData(random, 0, timePeriod, date, firstAmount));
				
				switch (timePeriod) {
					case TimePeriod.Month:
						date = date.AddMonths(1);
						break;
					case TimePeriod.Week:
						date = date.AddDays(7);
						break;
					default:  // Year
						date = date.AddYears(1);
						break;
				}

				for (int index = 1; index < resolvedDataPointCount; index++) {
					step = Convert.ToDouble(random.NextDouble()) * this.StepRange;
					var amount = (presetAmounts != null ? presetAmounts[index] : this[index - 1].Amount + step - delta);

					if (!this.AllowNegativeNumbers)
						amount = Math.Max(0, amount);

					this.Add(this.CreateData(random, index, timePeriod, date, amount));

					switch (timePeriod) {
						case TimePeriod.Month:
							date = date.AddMonths(1);
							break;
						case TimePeriod.Week:
							date = date.AddDays(7);
							break;
						default:  // Year
							date = date.AddYears(1);
							break;
					}
				}
			}
			finally {
				this.EndUpdate();
			}
		}

19 View Source File : Solar.cs
License : MIT License
Project Creator : 6tail

public Solar next(int days, bool onlyWorkday)
        {
            DateTime c = ExactDate.fromYmdHms(year, month, day, hour, minute, second);
            if (0 != days)
            {
                if (!onlyWorkday)
                {
                    c = c.AddDays(days);
                }
                else
                {
                    int rest = Math.Abs(days);
                    int add = days < 1 ? -1 : 1;
                    while (rest > 0)
                    {
                        c = c.AddDays(add);
                        bool work = true;
                        Holiday holiday = HolidayUtil.getHoliday(c.Year, c.Month, c.Day);
                        if (null == holiday)
                        {
                            string week = c.DayOfWeek.ToString("d");
                            if ("0".Equals(week)||"6".Equals(week))
                            {
                                work = false;
                            }
                        }
                        else
                        {
                            work = holiday.isWork();
                        }
                        if (work)
                        {
                            rest--;
                        }
                    }
                }
            }
            return new Solar(c);
        }

19 View Source File : WeatherForecastController.cs
License : MIT License
Project Creator : ad313

[HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

19 View Source File : RelationCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Unit> Handle(FriendToCommand command, CancellationToken cancellationToken)
        {
            var playerId = command.PlayerId;
            var relationId = command.RelationId;
            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            var relation = await _playerDomainService.Get(relationId);
            if (relation == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            if (await _redisDb.StringGet<int>(string.Format(RedisKey.RefuseFriend, player.Id, relation.Id)) > 0)
            {
                await _mudProvider.ShowMessage(player.Id, $"【好友】[{relation.Name}]已拒绝你的申请。");
                return Unit.Value;
            }

            //我加对方
            var playerRelationFrom = await _playerRelationDomainService.Get(x => x.PlayerId == player.Id
                && x.RelationId == relation.Id
                && x.Type == PlayerRelationTypeEnum.好友);

            //对方加我
            var playerRelationTo = await _playerRelationDomainService.Get(x => x.PlayerId == relation.Id
                && x.RelationId == player.Id
                && x.Type == PlayerRelationTypeEnum.好友);



            if (playerRelationFrom != null && playerRelationTo != null)
            {
                if (playerRelationTo != null)
                {
                    await _mudProvider.ShowMessage(player.Id, $"【好友】你们已经是好友。");
                    return Unit.Value;
                }
                else
                {
                    await _mudProvider.ShowMessage(player.Id, $"【好友】你已申请加[{relation.Name}]为好友,请等待对方同意。");
                    return Unit.Value;
                }

            }



            if (playerRelationFrom == null)
            {
                if (playerRelationTo == null)
                {

                    await _mudProvider.ShowMessage(player.Id, $"【好友】你申请加[{relation.Name}]为好友,请等待对方同意。");

                    var content = $"【好友】[{player.Name}]想和你成为好友,到 '社交'->'好友' 界面可以同意或拒绝对方的申请,你也可以直接添加对方为好友。";

                    await _emailDomainService.Add(new EmailEnreplacedy
                    {
                        ExpiryDate = DateTime.Now.AddDays(30),
                        SendDate = DateTime.Now,
                        replacedle = $"{player.Name}想和你成为好友",
                        Content = content,
                        Type = EmailTypeEnum.系统,
                        TypeId = relation.Id
                    });


                    await _mudProvider.ShowMessage(relation.Id, content);
                }
                else
                {
                    await _mudProvider.ShowMessage(player.Id, $"【好友】你成功添加[{relation.Name}]为好友。");


                    var content = $"【好友】[{player.Name}]同意了你的申请,你们已成为了好友。";

                    await _emailDomainService.Add(new EmailEnreplacedy
                    {
                        ExpiryDate = DateTime.Now.AddDays(30),
                        SendDate = DateTime.Now,
                        replacedle = $"{player.Name}同意了你的好友申请",
                        Content = content,
                        Type = EmailTypeEnum.系统,
                        TypeId = relation.Id
                    });


                    await _mudProvider.ShowMessage(relation.Id, content);
                }


                playerRelationFrom = new PlayerRelationEnreplacedy
                {
                    CreatedTime = DateTime.Now,
                    PlayerId = player.Id,
                    RelationId = relation.Id,
                    Type = PlayerRelationTypeEnum.好友
                };
                await _playerRelationDomainService.Add(playerRelationFrom);



                await _queueHandler.SendQueueMessage(new ReceiveEmailQueue(relation.Id));
            }
            return Unit.Value;
        }

19 View Source File : WeatherForecastController.cs
License : MIT License
Project Creator : ad313

[HttpGet]
        [RpcServer("rpc-test1")]
        public IEnumerable<WeatherForecast> Get()
        {
            //var v = _testClreplaced.Get();
            //v = _testClreplaced.Get();
            //var ss = AopCacheProviderInstance.Get<Guid>("aaaaa","b").GetAwaiter().GetResult();

            //AopCacheProviderInstance.Remove("aaaaa","b");

            //v = _testClreplaced.Get();

            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

19 View Source File : Edi.cs
License : MIT License
Project Creator : 0ffffffffh

private static int GetOccurancePeriodInterval()
        {
            var ts = DateTime.Today.AddDays(1) - DateTime.Now;
            return (int)ts.TotalMilliseconds;
        }

19 View Source File : DateTimePicker.xaml.cs
License : MIT License
Project Creator : ADeltaX

private DateTime Increase(int selstart, int value)
		{
			DateTime retval = (ParseDateText(false) ?? SelectedDate);

			try
			{
				switch (DateFormat.Substring(selstart, 1))
				{
					case "h":
					case "H":
						retval = retval.AddHours(value);
						break;
					case "y":
						retval = retval.AddYears(value);
						break;
					case "M":
						retval = retval.AddMonths(value);
						break;
					case "m":
						retval = retval.AddMinutes(value);
						break;
					case "d":
						retval = retval.AddDays(value);
						break;
					case "s":
						retval = retval.AddSeconds(value);
						break;
				}
			}
			catch (ArgumentException ex)
			{
				//Catch dates with year over 9999 etc, dont throw
			}

			return retval;
		}

19 View Source File : UrlMappingRepository.cs
License : MIT License
Project Creator : a34546

public async Task<string> GenerateTinyUrl(string url, string key)
        {
            if (!_cache.TryGetValue(key, out Client client)) throw new Exception(" key is error");
            if (await QueryNoTracking().AnyAsync(x => x.Url.Equals(url, StringComparison.CurrentCultureIgnoreCase))) return (await QueryNoTracking().FirstOrDefaultAsync(x => x.Url == url))?.Code;
            var code = Utils.GenerateCode(6);
            while (!await IsUnique(code))
            {
                code = Utils.GenerateCode(6);
            }
            var enreplacedy = new UrlMapping { Code = code, Url = url, Source = client.Name };
            var now = DateTime.Now;

            if (client.Days.HasValue) enreplacedy.ExpiryTime = now.AddDays(client.Days.Value);
            await InsertAsync(enreplacedy);
            //清空已过期的链接
            HardDelete(x => x.ExpiryTime.HasValue && x.ExpiryTime.Value < now);
            await _unitOfWork.SaveChangesAsync();
            return enreplacedy.Code;
        }

19 View Source File : SolarWeek.cs
License : MIT License
Project Creator : 6tail

public Solar getFirstDay()
        {
            DateTime c = ExactDate.fromYmd(year, month, day);
            int week = Convert.ToInt32(c.DayOfWeek.ToString("d"));
            int prev = week - start;
            if (prev < 0)
            {
                prev += 7;
            }
            c = c.AddDays(-prev);
            return new Solar(c);
        }

19 View Source File : SozlukDataStore.cs
License : MIT License
Project Creator : 0ffffffffh

public static SearchAndIndexQueryResult FetchBasliksUsingSearch(bool fresh, string content, string suser, DateTime begin, DateTime end, int pageNumber, string pagerHash, bool leaveDatesAsIs)
        {
            SearchAndIndexQueryResult resultSet;
            SqlServerIo sql;
            TimeSpan invTimeout;
            int rowBegin, rowEnd;
            string query;
            KeysetId keysetId;
            string baslik, descr, deceptedDate;
            int entryCount;
            bool resultCached;

            rowBegin = (pageNumber * BasliksPerPage) + 1;
            rowEnd = rowBegin + BasliksPerPage - 1;

            //Workarounds, workarounds, workarounds !
            if (begin != DateTime.MinValue && end != DateTime.MinValue)
            {
                if (leaveDatesAsIs)
                {
                    deceptedDate = begin.AddTicks((end - begin).Ticks / 2).ToString();
                }
                else
                {
                    //push it out of from the search date range to reverse daterange check logic
                    deceptedDate = end.AddDays(2).ToString();
                }
            }
            else
                deceptedDate = string.Empty;

            query = BuildFetchSQLQuery(ref pagerHash, content, suser, begin, end, rowBegin, rowEnd);


            if (fresh)
            {
                keysetId = KeysetId.Todays(true);
                invTimeout = TodaysTimeout;
            }
            else
            {
                keysetId = KeysetId.Search(pagerHash,true);
                invTimeout = SearchResultTimeout;
            }

            resultCached = CacheManager.TryGetCachedQueryResult<SearchAndIndexQueryResult>(query, out resultSet);

            if (!resultCached)
            {
                sql = SqlServerIo.Create();

                if (!sql.Execute(false, query))
                {
                    SqlServerIo.Release(sql);
                    return new SearchAndIndexQueryResult();
                }

                resultSet = new SearchAndIndexQueryResult
                {
                    PagerHash = pagerHash
                };

                while (sql.Read())
                {
                    baslik = sql.GetValueOfColumn<string>("Baslik");
                    entryCount = sql.GetValueOfColumn<int>("EntryCount");

                    if (resultSet.TotalRecordCount == 0)
                        resultSet.TotalRecordCount = sql.GetValueOfColumn<int>("TotalRecordCount");

                    if (entryCount>0)
                        descr = content;
                    else
                        descr = Strev(content);

                    if (string.IsNullOrEmpty(suser))
                        suser = string.Empty;

                    resultSet.Entries.Add(
                        new Entry(
                            baslik, 
                            suser, 
                            deceptedDate, 
                            descr,entryCount)
                            );

                    resultSet.PhysicalRecordCount++;
                }

                resultSet.LogicalRecordCount = resultSet.Entries.Count;

                SqlServerIo.Release(sql);

                CacheManager.CacheObject(keysetId,true, query, resultSet,invTimeout);
            }

            return resultSet;
        }

19 View Source File : ScTempTables.cs
License : MIT License
Project Creator : 0x1000000

public async Task Exec(IScenarioContext context)
        {
            var tbl = new IdModified();
            DateTime now = new DateTime(2020, 10, 18);

            await context.Database.Statement(tbl.Script.Create());

            await InsertDataInto(tbl, Gereplacedems())
                .MapData(s => s.Set(s.Target.Modified, s.Source))
                .Exec(context.Database);

            context.WriteLine("Data from temporary table:");

            var clYear = CustomColumnFactory.DateTime(nameof(DateAddDatePart.Year));
            var clMonth = CustomColumnFactory.DateTime(nameof(DateAddDatePart.Month));
            var clWeek = CustomColumnFactory.DateTime(nameof(DateAddDatePart.Week));
            var clDay = CustomColumnFactory.DateTime(nameof(DateAddDatePart.Day));
            var clHour = CustomColumnFactory.DateTime(nameof(DateAddDatePart.Hour));
            var clMinute = CustomColumnFactory.DateTime(nameof(DateAddDatePart.Minute));
            var clSecond = CustomColumnFactory.DateTime(nameof(DateAddDatePart.Second));
            var clMillisecond = CustomColumnFactory.DateTime(nameof(DateAddDatePart.Millisecond));

            var number = 3;
            var result = await Select(
                    tbl.Id,
                    tbl.Modified,
                    DateAdd(DateAddDatePart.Year, number, tbl.Modified).As(clYear),
                    DateAdd(DateAddDatePart.Month, number, tbl.Modified).As(clMonth),
                    DateAdd(DateAddDatePart.Week, number, tbl.Modified).As(clWeek),
                    DateAdd(DateAddDatePart.Day, number, tbl.Modified).As(clDay),
                    DateAdd(DateAddDatePart.Hour, number, tbl.Modified).As(clHour),
                    DateAdd(DateAddDatePart.Minute, number, tbl.Modified).As(clMinute),
                    DateAdd(DateAddDatePart.Second, number, tbl.Modified).As(clSecond),
                    DateAdd(DateAddDatePart.Millisecond, number, tbl.Modified).As(clMillisecond)
                )
                .From(tbl)
                .QueryList(context.Database,
                    r => new
                    {
                        Original = tbl.Modified.Read(r), 
                        Year = clYear.Read(r), 
                        Month = clMonth.Read(r),
                        Week = clWeek.Read(r), 
                        Day = clDay.Read(r), 
                        Hour = clHour.Read(r), 
                        Minute = clMinute.Read(r),
                        Second = clSecond.Read(r), 
                        Millisecond = clMillisecond.Read(r)
                    });

            //Checking Items
            foreach (var r in result)
            {
                replacedertDatesEqual(r.Original.AddYears(number), r.Year, "Year");
                replacedertDatesEqual(r.Original.AddMonths(number), r.Month, "Month");
                replacedertDatesEqual(r.Original.AddDays(number*7), r.Week, "Week");
                replacedertDatesEqual(r.Original.AddDays(number), r.Day, "Day");
                replacedertDatesEqual(r.Original.AddHours(number), r.Hour, "Hour");
                replacedertDatesEqual(r.Original.AddMinutes(number), r.Minute, "Minute");
                replacedertDatesEqual(r.Original.AddSeconds(number), r.Second, "Second");
                replacedertDatesEqual(r.Original.AddMilliseconds(number), r.Millisecond, "Millisecond");
            }

            context.WriteLine("All dates are correct!");

            await context.Database.Statement(tbl.Script.Drop());
            await context.Database.Statement(tbl.Script.DropIfExist());

            IEnumerable<DateTime> Gereplacedems()
            {

                for (int i = 0; i < 10; i++)
                {
                    now = now.AddDays(-1);
                    yield return now;
                }
            }

            void replacedertDatesEqual(DateTime expected, DateTime actual, string mode)
            {
                if (expected != actual)
                {
                    throw new SqExpressException($"{context.Dialect} {mode} - Expected '{expected:O}' does not equal to actual '{actual:O}'");
                }
            }
        }

19 View Source File : DateTimeFuzzerShould.cs
License : Apache License 2.0
Project Creator : 42skillz

private static void CheckThatDateTimeBelongsToTheInclusiveTimeRange(DateTime generatedDateTime, string minDate,
            string maxDate)
        {
            var minDateOk = DateTime.TryParseExact(minDate, "yyyy/MM/dd", null, DateTimeStyles.None, out var minDateTime);
            var maxDateOk = DateTime.TryParseExact(maxDate, "yyyy/MM/dd", null, DateTimeStyles.None, out var maxDateTime);

            Check.That(generatedDateTime).IsBefore(maxDateTime.AddDays(1)).And.IsAfter(minDateTime.AddDays(-1));
        }

19 View Source File : RelationCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Unit> Handle(UnFriendToCommand command, CancellationToken cancellationToken)
        {
            var playerId = command.PlayerId;
            var relationId = command.RelationId;
            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            var relation = await _playerDomainService.Get(relationId);
            if (relation == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            //我加对方
            var playerRelationFrom = await _playerRelationDomainService.Get(x => x.PlayerId == player.Id
                && x.RelationId == relation.Id
                && x.Type == PlayerRelationTypeEnum.好友);

            //对方加我
            var playerRelationTo = await _playerRelationDomainService.Get(x => x.PlayerId == relation.Id
                && x.RelationId == player.Id
                && x.Type == PlayerRelationTypeEnum.好友);



            if (playerRelationFrom != null && playerRelationTo != null)
            {
                await _playerRelationDomainService.Delete(playerRelationFrom);

                await _playerRelationDomainService.Delete(playerRelationTo);

                //1天内不得重复申请
                await _redisDb.StringSet(string.Format(RedisKey.RefuseFriend, relation.Id, player.Id), 1, DateTime.Now.AddDays(1));

                await _mudProvider.ShowMessage(player.Id, $"【好友】你已经与[{relation.Name}]取消好友关系。");

                var content = $"【好友】[{player.Name}]已经与你取消好友关系。";

                await _emailDomainService.Add(new EmailEnreplacedy
                {
                    ExpiryDate = DateTime.Now.AddDays(30),
                    SendDate = DateTime.Now,
                    replacedle = $"{player.Name}与你取消好友关系",
                    Content = content,
                    Type = EmailTypeEnum.系统,
                    TypeId = relation.Id
                });


                await _mudProvider.ShowMessage(relation.Id, content);
            }
            else
            {
                await _mudProvider.ShowMessage(player.Id, $"【好友】你们并不是好友。");
            }

            return Unit.Value;
        }

19 View Source File : TransactionStatsQueriesHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<TransactionMonthlyStatsDto>> Handle(TransactionStatsOverMonthQuery request, CancellationToken cancellationToken)
        {
            var startDate = DateTime.UtcNow.Date.AddDays(-31);
            var endDate = DateTime.UtcNow.Date;

            var transes = (from r in _receivingsRepo.Table
                           where
                              r.ReceivedAtUtc.Date >= startDate && r.ReceivedAtUtc.Date <= endDate
                           group r by r.ReceivedAtUtc.Date into g
                           orderby g.Key
                           select new TransactionMonthlyStatsDto
                           {
                               Count = g.Count(),
                               Day = g.Key
                           }).ToList();
            var days = Enumerable.Range(0, 31).Select(offset => endDate.AddDays(-offset)).ToList();

            days.ForEach(day =>
            {
                if (!transes.Any(t => t.Day.Date == day.Date))
                {
                    transes.Add(new TransactionMonthlyStatsDto
                    {
                        Count = 0,
                        Day = day.Date,
                    });
                }
            });

            return transes.OrderBy(t => t.Day.Date).ToList();
        }

See More Examples