System.DateTime.AddSeconds(double)

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

2186 Examples 7

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

public void ProcessPacket(ClientPacket packet)
        {
            if (isReleased) // Session has been removed
                return;

            packetLog.DebugFormat("[{0}] Processing packet {1}", session.LoggingIdentifier, packet.Header.Sequence);
            NetworkStatistics.C2S_Packets_Aggregate_Increment();

            if (!packet.VerifyCRC(ConnectionData.CryptoClient))
            {
                return;
            }

            // If the client sent a NAK with a cleartext CRC then process it
            if ((packet.Header.Flags & PacketHeaderFlags.RequestRetransmit) == PacketHeaderFlags.RequestRetransmit
                && !((packet.Header.Flags & PacketHeaderFlags.EncryptedChecksum) == PacketHeaderFlags.EncryptedChecksum))
            {
                List<uint> uncached = null;

                foreach (uint sequence in packet.HeaderOptional.RetransmitData)
                {
                    if (!Retransmit(sequence))
                    {
                        if (uncached == null)
                            uncached = new List<uint>();

                        uncached.Add(sequence);
                    }
                }

                if (uncached != null)
                {
                    // Sends a response packet w/ PacketHeader.RejectRetransmit
                    var packetRejectRetransmit = new PacketRejectRetransmit(uncached);
                    EnqueueSend(packetRejectRetransmit);
                }

                NetworkStatistics.C2S_RequestsForRetransmit_Aggregate_Increment();
                return; //cleartext crc NAK is never accompanied by additional data needed by the rest of the pipeline
            }

            #region order-insensitive "half-processing"

            if (packet.Header.HasFlag(PacketHeaderFlags.Disconnect))
            {
                session.Terminate(SessionTerminationReason.PacketHeaderDisconnect);
                return;
            }

            if (packet.Header.HasFlag(PacketHeaderFlags.NetErrorDisconnect))
            {
                session.Terminate(SessionTerminationReason.ClientSentNetworkErrorDisconnect);
                return;
            }

            // depending on the current session state:
            // Set the next timeout tick value, to compare against in the WorldManager
            // Sessions that have gone past the AuthLoginRequest step will stay active for a longer period of time (exposed via configuration) 
            // Sessions that in the AuthLoginRequest will have a short timeout, as set in the AuthenticationHandler.DefaultAuthTimeout.
            // Example: Applications that check uptime will stay in the AuthLoginRequest state.
            session.Network.TimeoutTick = (session.State == SessionState.AuthLoginRequest) ?
                DateTime.UtcNow.AddSeconds(AuthenticationHandler.DefaultAuthTimeout).Ticks : // Default is 15s
                DateTime.UtcNow.AddSeconds(NetworkManager.DefaultSessionTimeout).Ticks; // Default is 60s

            #endregion

            #region Reordering stage

            // Reordering stage
            // Check if this packet's sequence is a sequence which we have already processed.
            // There are some exceptions:
            // Sequence 0 as we have several Seq 0 packets during connect.  This also cathes a case where it seems CICMDCommand arrives at any point with 0 sequence value too.
            // If the only header on the packet is AckSequence. It seems AckSequence can come in with the same sequence value sometimes.
            if (packet.Header.Sequence <= lastReceivedPacketSequence && packet.Header.Sequence != 0 &&
                !(packet.Header.Flags == PacketHeaderFlags.AckSequence && packet.Header.Sequence == lastReceivedPacketSequence))
            {
                packetLog.WarnFormat("[{0}] Packet {1} received again", session.LoggingIdentifier, packet.Header.Sequence);
                return;
            }

            // Check if this packet's sequence is greater then the next one we should be getting.
            // If true we must store it to replay once we have caught up.
            var desiredSeq = lastReceivedPacketSequence + 1;
            if (packet.Header.Sequence > desiredSeq)
            {
                packetLog.DebugFormat("[{0}] Packet {1} received out of order", session.LoggingIdentifier, packet.Header.Sequence);

                if (!outOfOrderPackets.ContainsKey(packet.Header.Sequence))
                    outOfOrderPackets.TryAdd(packet.Header.Sequence, packet);

                if (desiredSeq + 2 <= packet.Header.Sequence && DateTime.UtcNow - LastRequestForRetransmitTime > new TimeSpan(0, 0, 1))
                    DoRequestForRetransmission(packet.Header.Sequence);

                return;
            }

            #endregion

            #region Final processing stage

            // Processing stage
            // If we reach here, this is a packet we should proceed with processing.
            HandleOrderedPacket(packet);
        
            // Process data now in sequence
            // Finally check if we have any out of order packets or fragments we need to process;
            CheckOutOfOrderPackets();
            CheckOutOfOrderFragments();

            #endregion
        }

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

public void Attack(WorldObject target, int attackSequence, bool subsequent = false)
        {
            //log.Info($"{Name}.Attack({target.Name}, {attackSequence})");

            if (AttackSequence != attackSequence)
                return;

            if (CombatMode != CombatMode.Melee || MeleeTarget == null || IsBusy || !IsAlive || suicideInProgress)
            {
                OnAttackDone();
                return;
            }

            var creature = target as Creature;
            if (creature == null || !creature.IsAlive)
            {
                OnAttackDone();
                return;
            }

            var animLength = DoSwingMotion(target, out var attackFrames);
            if (animLength == 0)
            {
                OnAttackDone();
                return;
            }

            // point of no return beyond this point -- cannot be cancelled
            Attacking = true;

            if (subsequent)
            {
                // client shows hourglreplaced, until attack done is received
                // retail only did this for subsequent attacks w/ repeat attacks on
                Session.Network.EnqueueSend(new GameEventCombatCommenceAttack(Session));
            }

            var weapon = GetEquippedMeleeWeapon();
            var attackType = GetWeaponAttackType(weapon);
            var numStrikes = GetNumStrikes(attackType);
            var swingTime = animLength / numStrikes / 1.5f;

            var actionChain = new ActionChain();

            // stamina usage
            // TODO: ensure enough stamina for attack
            var staminaCost = GetAttackStamina(GetPowerRange());
            UpdateVitalDelta(Stamina, -staminaCost);

            if (numStrikes != attackFrames.Count)
            {
                //log.Warn($"{Name}.GetAttackFrames(): MotionTableId: {MotionTableId:X8}, MotionStance: {CurrentMotionState.Stance}, Motion: {GetSwingAnimation()}, AttackFrames.Count({attackFrames.Count}) != NumStrikes({numStrikes})");
                numStrikes = attackFrames.Count;
            }

            // handle self-procs
            TryProcEquippedItems(this, this, true, weapon);

            var prevTime = 0.0f;
            bool targetProc = false;

            for (var i = 0; i < numStrikes; i++)
            {
                // are there animation hooks for damage frames?
                //if (numStrikes > 1 && !TwoHandedCombat)
                //actionChain.AddDelaySeconds(swingTime);
                actionChain.AddDelaySeconds(attackFrames[i].time * animLength - prevTime);
                prevTime = attackFrames[i].time * animLength;

                actionChain.AddAction(this, () =>
                {
                    if (IsDead)
                    {
                        Attacking = false;
                        OnAttackDone();
                        return;
                    }

                    var damageEvent = DamageTarget(creature, weapon);

                    // handle target procs
                    if (damageEvent != null && damageEvent.HasDamage && !targetProc)
                    {
                        TryProcEquippedItems(this, creature, false, weapon);
                        targetProc = true;
                    }

                    if (weapon != null && weapon.IsCleaving)
                    {
                        var cleave = GetCleaveTarget(creature, weapon);

                        foreach (var cleaveHit in cleave)
                        {
                            // target procs don't happen for cleaving
                            DamageTarget(cleaveHit, weapon);
                        }
                    }
                });

                //if (numStrikes == 1 || TwoHandedCombat)
                    //actionChain.AddDelaySeconds(swingTime);
            }

            //actionChain.AddDelaySeconds(animLength - swingTime * numStrikes);
            actionChain.AddDelaySeconds(animLength - prevTime);

            actionChain.AddAction(this, () =>
            {
                Attacking = false;

                // powerbar refill timing
                var refillMod = IsDualWieldAttack ? 0.8f : 1.0f;    // dual wield powerbar refills 20% faster

                PowerLevel = AttackQueue.Fetch();

                var nextRefillTime = PowerLevel * refillMod;
                NextRefillTime = DateTime.UtcNow.AddSeconds(nextRefillTime);

                var dist = GetCylinderDistance(target);

                if (creature.IsAlive && GetCharacterOption(CharacterOption.AutoRepeatAttacks) && (dist <= MeleeDistance || dist <= StickyDistance && IsMeleeVisible(target)) && !IsBusy && !AttackCancelled)
                {
                    // client starts refilling power meter
                    Session.Network.EnqueueSend(new GameEventAttackDone(Session));

                    var nextAttack = new ActionChain();
                    nextAttack.AddDelaySeconds(nextRefillTime);
                    nextAttack.AddAction(this, () => Attack(target, attackSequence, true));
                    nextAttack.EnqueueChain();
                }
                else
                    OnAttackDone();
            });

            actionChain.EnqueueChain();

            if (UnderLifestoneProtection)
                LifestoneProtectionDispel();
        }

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

public static void RunMainThreadSync(Action act, int waitSecond = 10)
        {
            if (GlobalData.MainThreadNum == Thread.CurrentThread.ManagedThreadId)
                act();
            else
            {
                //Loger.Log($"Client RunMainThreadSync begin");
                var num = RunMainThread(act);
                int i = 0;
                while (GlobalData.ActionNumReady < num && i++ < 20) Thread.Sleep(1);

                if (GlobalData.ActionNumReady < num)
                {
                    var end = DateTime.UtcNow.AddSeconds(waitSecond);
                    while (GlobalData.ActionNumReady < num && DateTime.UtcNow < end) Thread.Sleep(10);

                    if (GlobalData.ActionNumReady < num)
                    {
                        Loger.Log("Client RunMainThread Timeout Exception");
                        throw new ApplicationException("Client RunMainThread Timeout");
                    }
                }

                //Loger.Log($"Client RunMainThreadSync end i={i}");
            }
        }

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

public static void UseObjectOnTarget(Player player, WorldObject source, WorldObject target)
        {
            //Console.WriteLine($"Aetheria.UseObjectOnTarget({player.Name}, {source.Name}, {target.Name})");

            if (player.IsBusy)
            {
                player.SendUseDoneEvent(WeenieError.YoureTooBusy);
                return;
            }

            // verify use requirements
            var useError = VerifyUseRequirements(player, source, target);
            if (useError != WeenieError.None)
            {
                player.SendUseDoneEvent(useError);
                return;
            }

            var animTime = 0.0f;

            var actionChain = new ActionChain();

            player.IsBusy = true;

            // handle switching to peace mode
            if (player.CombatMode != CombatMode.NonCombat)
            {
                var stanceTime = player.SetCombatMode(CombatMode.NonCombat);
                actionChain.AddDelaySeconds(stanceTime);

                animTime += stanceTime;
            }

            // perform clapping motion
            animTime += player.EnqueueMotion(actionChain, MotionCommand.ClapHands);

            actionChain.AddAction(player, () =>
            {
                // re-verify
                var useError = VerifyUseRequirements(player, source, target);
                if (useError != WeenieError.None)
                {
                    player.SendUseDoneEvent(useError);
                    return;
                }

                ActivateSigil(player, source, target);
            });

            player.EnqueueMotion(actionChain, MotionCommand.Ready);

            actionChain.AddAction(player, () => player.IsBusy = false);

            actionChain.EnqueueChain();

            player.NextUseTime = DateTime.UtcNow.AddSeconds(animTime);
        }

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

public static WorldObjectEntry GetWorldObjectEntry(WorldObject worldObject
            , PlayerGameProgress gameProgress
            , Dictionary<Map, List<Pawn>> cacheColonists)
        {
            var worldObjectEntry = new WorldObjectEntry();
            worldObjectEntry.Type = worldObject is Caravan ? WorldObjectEntryType.Caravan : WorldObjectEntryType.Base;
            worldObjectEntry.Tile = worldObject.Tile;
            worldObjectEntry.Name = worldObject.LabelCap;
            worldObjectEntry.LoginOwner = SessionClientController.My.Login;
            worldObjectEntry.FreeWeight = 999999;

            //определяем цену и вес 
            var caravan = worldObject as Caravan;
            if (caravan != null)
            {
                //Loger.Log("Client TestBagSD 002");
                var transferables = CalculateTransferables(caravan);
                //Loger.Log("Client TestBagSD 003");

                List<ThingCount> stackParts = new List<ThingCount>();
                for (int i = 0; i < transferables.Count; i++)
                {
                    TransferableUtility.TransferNoSplit(transferables[i].things, transferables[i].MaxCount/*CountToTransfer*/, delegate (Thing originalThing, int toTake)
                    {
                        stackParts.Add(new ThingCount(originalThing, toTake));
                    }, false, false);
                }
                //Loger.Log("Client TestBagSD 004");
                worldObjectEntry.FreeWeight = CollectionsMreplacedCalculator.Capacity(stackParts)
                    - CollectionsMreplacedCalculator.MreplacedUsage(stackParts, IgnorePawnsInventoryMode.Ignore, false, false);
                //Loger.Log("Client TestBagSD 005");

                worldObjectEntry.MarketValue = 0f;
                worldObjectEntry.MarketValuePawn = 0f;
                for (int i = 0; i < stackParts.Count; i++)
                {
                    int count = stackParts[i].Count;

                    if (count > 0)
                    {
                        Thing thing = stackParts[i].Thing;
                        if (thing is Pawn)
                        {
                            worldObjectEntry.MarketValuePawn += thing.MarketValue
                                + WealthWatcher.GetEquipmentApparelAndInventoryWealth(thing as Pawn);
                            GameProgressAdd(gameProgress, thing as Pawn);
                        }
                        else
                            worldObjectEntry.MarketValue += thing.MarketValue * (float)count;
                    }
                }
                //Loger.Log("Client TestBagSD 006");
            }
            else if (worldObject is Settlement)
            {
                //Loger.Log("Client TestBagSD 007");
                var map = (worldObject as Settlement).Map;
                if (map != null)
                {
                    //Loger.Log("Client TestBagSD 008");
                    try
                    {
                        DateTime lastForceRecount;
                        if (!LastForceRecount.TryGetValue(map.uniqueID, out lastForceRecount))
                            LastForceRecount.Add(map.uniqueID, DateTime.UtcNow.AddSeconds(new Random(map.uniqueID * 7).Next(0, 10)));
                        else if ((DateTime.UtcNow - lastForceRecount).TotalSeconds> 30)
                        {
                            LastForceRecount[map.uniqueID] = DateTime.UtcNow;
                            ModBaseData.RunMainThread(() =>
                            {
                                map.wealthWatcher.ForceRecount();
                            });
                        }
                        worldObjectEntry.MarketValue = map.wealthWatcher.WealthTotal;
                    }
                    catch
                    {
                        Thread.Sleep(100);
                        try
                        {
                            worldObjectEntry.MarketValue = map.wealthWatcher.WealthTotal;
                        }
                        catch
                        {
                        }
                    }

                    worldObjectEntry.MarketValuePawn = 0;

                    //Loger.Log("Client TestBagSD 015");
                    List<Pawn> ps;
                    if (!cacheColonists.TryGetValue(map, out ps))
                    {
                        var mapPawnsA = new Pawn[map.mapPawns.AllPawnsSpawned.Count];
                        map.mapPawns.AllPawnsSpawned.CopyTo(mapPawnsA);

                        ps = mapPawnsA.Where(p => p.Faction == Faction.OfPlayer && p.RaceProps.Humanlike).ToList();
                        cacheColonists[map] = ps;
                    }

                    //Loger.Log("Client TestBagSD 016");
                    foreach (Pawn current in ps)
                    {
                        worldObjectEntry.MarketValuePawn += current.MarketValue;

                        GameProgressAdd(gameProgress, current);
                    }
                    //Loger.Log("Client TestBagSD 017");
                    //Loger.Log("Map things "+ worldObjectEntry.MarketValue + " pawns " + worldObjectEntry.MarketValuePawn);
                }
            }
            //Loger.Log("Client TestBagSD 018");

            WorldObjectEntry storeWO;
            if (WorldObjectEntrys.TryGetValue(worldObject.ID, out storeWO))
            {
                //если серверу приходит объект без данного ServerId, значит это наш новый объект (кроме первого запроса, т.к. не было ещё загрузки)
                worldObjectEntry.ServerId = storeWO.ServerId;
            }
            //Loger.Log("Client TestBagSD 019");

            return worldObjectEntry;
        }

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

private async Task Fighting(PlayerEnreplacedy player, TargetTypeEnum? targetType, int targetId)
        {
            if (targetType == TargetTypeEnum.Npc)
            {
                var npc = await _npcDomainService.Get(targetId);
                if (npc == null)
                {
                    await StopAction(player);
                    return;
                }

                var npcFightingPlayerId = await _redisDb.StringGet<int>(string.Format(RedisKey.NpcFighting, npc.Id));
                if (npcFightingPlayerId != player.Id)
                {
                    await StopAction(player);
                    return;
                }

                await _redisDb.StringSet(string.Format(RedisKey.NpcFighting, npc.Id), player.Id, DateTime.Now.AddSeconds(60));

                await FightingNpc(player, npc);
            }
            else if (targetType == TargetTypeEnum.玩家)
            {
                var target = await _playerDomainService.Get(targetId);
                if (target == null)
                {
                    await StopAction(player);
                    return;
                }

                await FightingPlayer(player, target);
            }
            else
            {
                await StopAction(player);
            }


          

        }

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

public void RecalculateDecayTime(Player player)
        {
            // empty corpses decay faster
            if (Inventory.Count == 0)
                TimeToRot = EmptyDecayTime;
            else
                // a player corpse decays after 5 mins * playerLevel with a minimum of 1 hour
                TimeToRot = Math.Max(3600, (player.Level ?? 1) * 300);

            var dtTimeToRot = DateTime.UtcNow.AddSeconds(TimeToRot ?? 0);
            var tsDecay = dtTimeToRot - DateTime.UtcNow;

            Level = player.Level ?? 1;

            log.Debug($"[CORPSE] {Name}.RecalculateDecayTime({player.Name}) 0x{Guid}: Player Level: {player.Level} | Inventory.Count: {Inventory.Count} | TimeToRot: {TimeToRot} | CreationTimestamp: {CreationTimestamp} ({Time.GetDateTimeFromTimestamp(CreationTimestamp ?? 0).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}) | Corpse should not decay before: {dtTimeToRot.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}, {tsDecay.ToString("%d")} day(s), {tsDecay.ToString("%h")} hours, {tsDecay.ToString("%m")} minutes, and {tsDecay.ToString("%s")} seconds from now.");
        }

19 View Source File : ClientSideCaching.cs
License : MIT License
Project Creator : 2881099

bool TryGetCacheValue(string key, Type valueType, out object value)
            {
                if (_dict.TryGetValue(key, out var trydictval) && trydictval.Values.TryGetValue(valueType, out var tryval)
                    //&& DateTime.Now.Subtract(_dt2020.AddSeconds(tryval.SetTime)) < TimeSpan.FromMinutes(5)
                    )
                {
                    if (_options.CheckExpired?.Invoke(key, _dt2020.AddSeconds(tryval.SetTime)) == true)
                    {
                        RemoveCache(key);
                        value = null;
                        return false;
                    }
                    var time = GetTime();
                    if (_options.Capacity > 0)
                    {
                        lock (_dictLock)
                        {
                            _dictSort.Remove($"{trydictval.GetTime.ToString("X").PadLeft(16, '0')}{key}");
                            _dictSort.Add($"{time.ToString("X").PadLeft(16, '0')}{key}");
                        }
                    }
                    Interlocked.Exchange(ref trydictval.GetTime, time);
                    value = tryval.Value;
                    return true;
                }
                value = null;
                return false;
            }

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

protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Call the inner handler.
            var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

            // Inspect whether response has throttling information
            IEnumerable<string> vssRequestDelayed = null;
            IEnumerable<string> vssRequestQuotaReset = null;

            if (response.Headers.TryGetValues(HttpHeaders.VssRateLimitDelay, out vssRequestDelayed) &&
                response.Headers.TryGetValues(HttpHeaders.VssRateLimitReset, out vssRequestQuotaReset) &&
                !string.IsNullOrEmpty(vssRequestDelayed.FirstOrDefault()) &&
                !string.IsNullOrEmpty(vssRequestQuotaReset.FirstOrDefault()))
            {
                TimeSpan delay = TimeSpan.FromSeconds(double.Parse(vssRequestDelayed.First()));
                int expirationEpoch = int.Parse(vssRequestQuotaReset.First());
                DateTime expiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expirationEpoch);

                _throttlingReporter.ReportThrottling(delay, expiration);
            }

            return response;
        }

19 View Source File : ObjectPool.cs
License : MIT License
Project Creator : 2881099

private void CheckAvailable(int interval)
        {

            new Thread(() =>
            {

                if (UnavailableException != null)
                    TestTrace.WriteLine($"【{Policy.Name}】Next recovery time:{DateTime.Now.AddSeconds(interval)}", ConsoleColor.DarkYellow);

                while (UnavailableException != null)
                {

                    if (running == false) return;

                    Thread.CurrentThread.Join(TimeSpan.FromSeconds(interval));

                    if (running == false) return;

                    try
                    {

                        var conn = GetFree(false);
                        if (conn == null) throw new Exception($"CheckAvailable: Failed to get resource {this.Statistics}");

                        try
                        {

                            if (Policy.OnCheckAvailable(conn) == false) throw new Exception("CheckAvailable: An exception needs to be thrown");
                            break;

                        }
                        finally
                        {

                            Return(conn);
                        }

                    }
                    catch (Exception ex)
                    {
                        TestTrace.WriteLine($"【{Policy.Name}】Next recovery time: {DateTime.Now.AddSeconds(interval)} ({ex.Message})", ConsoleColor.DarkYellow);
                    }
                }

                RestoreToAvailable();

            }).Start();
        }

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

public void Join(Player player)
        {
            var color = GetFreeColor();
            if (color != ChessColor.None)
            {
                if (NextRangeCheck == null)
                    NextRangeCheck = DateTime.UtcNow.AddSeconds(5);

                AddSide(player, color);
            }

            player.Session.Network.EnqueueSend(new GameEventJoinGameResponse(player.Session, ChessBoard.Guid, color));
        }

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

public static double GetFutureUnixTime(double seconds)
        {
            TimeSpan span = (DateTime.UtcNow.AddSeconds(seconds) - unixEpoch);

            return span.TotalSeconds;
        }

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 : ServerManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void ShutdownServer()
        {
            var shutdownTime = DateTime.UtcNow.AddSeconds(ShutdownInterval);

            ShutdownTime = shutdownTime;

            var lastNoticeTime = DateTime.UtcNow;

            // wait for shutdown interval to expire
            while (shutdownTime != DateTime.MinValue && shutdownTime >= DateTime.UtcNow)
            {
                // this allows the server shutdown to be canceled
                if (!ShutdownInitiated)
                {
                    // reset shutdown details
                    string shutdownText = $"The server has canceled the shutdown procedure @ {DateTime.UtcNow} UTC";
                    log.Info(shutdownText);

                    // special text
                    foreach (var player in PlayerManager.GetAllOnline())
                        player.Session.WorldBroadcast(shutdownText);

                    // break function
                    return;
                }

                lastNoticeTime = NotifyPlayersOfPendingShutdown(lastNoticeTime, shutdownTime.AddSeconds(1));

                Thread.Sleep(10);
            }

            ShutdownInProgress = true;

            PropertyManager.ResyncVariables();
            PropertyManager.StopUpdating();

            WorldManager.EnqueueAction(new ActionEventDelegate(() =>
            {
                log.Debug("Logging off all players...");

                // logout each player
                foreach (var player in PlayerManager.GetAllOnline())
                    player.Session.LogOffPlayer(true);
            }));

            // Wait for all players to log out
            var logUpdateTS = DateTime.MinValue;
            int playerCount;
            var playerLogoffStart = DateTime.UtcNow;
            while ((playerCount = PlayerManager.GetOnlineCount()) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for {playerCount} player{(playerCount > 1 ? "s" : "")} to log off...");
                Thread.Sleep(10);
                if (playerCount > 0 && DateTime.UtcNow - playerLogoffStart > TimeSpan.FromMinutes(5))
                {
                    playerLogoffStart = DateTime.UtcNow;
                    log.Warn($"5 minute log off failsafe reached and there are {playerCount} player{(playerCount > 1 ? "s" : "")} still online.");
                    foreach (var player in PlayerManager.GetAllOnline())
                    {
                        log.Warn($"Player {player.Name} (0x{player.Guid}) appears to be stuck in world and unable to log off normally. Requesting Forced Logoff...");
                        player.ForcedLogOffRequested = true;
                        player.ForceLogoff();
                    }    
                }
            }

            WorldManager.EnqueueAction(new ActionEventDelegate(() =>
            {
                log.Debug("Disconnecting all sessions...");

                // disconnect each session
                NetworkManager.DisconnectAllSessionsForShutdown();
            }));

            // Wait for all sessions to drop out
            logUpdateTS = DateTime.MinValue;
            int sessionCount;
            while ((sessionCount = NetworkManager.GetAuthenticatedSessionCount()) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for {sessionCount} authenticated session{(sessionCount > 1 ? "s" : "")} to disconnect...");
                Thread.Sleep(10);
            }

            log.Debug("Adding all landblocks to destruction queue...");

            // Queue unloading of all the landblocks
            // The actual unloading will happen in WorldManager.UpdateGameWorld
            LandblockManager.AddAllActiveLandblocksToDestructionQueue();

            // Wait for all landblocks to unload
            logUpdateTS = DateTime.MinValue;
            int landblockCount;
            while ((landblockCount = LandblockManager.GetLoadedLandblocks().Count) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for {landblockCount} loaded landblock{(landblockCount > 1 ? "s" : "")} to unload...");
                Thread.Sleep(10);
            }

            log.Debug("Stopping world...");

            // Disabled thread update loop
            WorldManager.StopWorld();

            // Wait for world to end
            logUpdateTS = DateTime.MinValue;
            while (WorldManager.WorldActive)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, "Waiting for world to stop...");
                Thread.Sleep(10);
            }

            log.Info("Saving OfflinePlayers that have unsaved changes...");
            PlayerManager.SaveOfflinePlayersWithChanges();

            // Wait for the database queue to empty
            logUpdateTS = DateTime.MinValue;
            int shardQueueCount;
            while ((shardQueueCount = DatabaseManager.Shard.QueueCount) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for database queue ({shardQueueCount}) to empty...");
                Thread.Sleep(10);
            }

            // Write exit to console/log
            log.Info($"Exiting at {DateTime.UtcNow}");

            // System exit
            Environment.Exit(Environment.ExitCode);
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 2881099

public DateTime LastSave() => Call("LASTSAVE", rt => rt.ThrowOrValue(a => _epoch.AddSeconds(a.ConvertTo<long>()).ToLocalTime()));

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

public void TickOutbound()
        {
            // Check if the player has been booted
            if (PendingTermination != null)
            {
                if (PendingTermination.TerminationStatus == SessionTerminationPhase.Initialized)
                {
                    State = SessionState.TerminationStarted;
                    Network.Update(); // boot messages may need sending
                    if (DateTime.UtcNow.Ticks > PendingTermination.TerminationEndTicks)
                        PendingTermination.TerminationStatus = SessionTerminationPhase.SessionWorkCompleted;
                }
                return;
            }

            if (State == SessionState.TerminationStarted)
                return;

            // Checks if the session has stopped responding.
            if (DateTime.UtcNow.Ticks >= Network.TimeoutTick)
            {
                // The Session has reached a timeout.  Send the client the error disconnect signal, and then drop the session
                Terminate(SessionTerminationReason.NetworkTimeout);
                return;
            }

            Network.Update();

            // Live server seemed to take about 6 seconds. 4 seconds is nice because it has smooth animation, and saves the user 2 seconds every logoff
            // This could be made 0 for instant logoffs.
            if (logOffRequestTime != DateTime.MinValue && logOffRequestTime.AddSeconds(6) <= DateTime.UtcNow)
                SendFinalLogOffMessages();

            // This section deviates from known retail pcaps/behavior, but appears to be the least harmful way to work around something that seemingly didn't occur to players using ThwargLauncher connecting to retail servers.
            // In order to prevent the launcher from thinking the session is dead, we will send a Ping Response every 100 seconds, this will in effect make the client appear active to the launcher and allow players to create characters in peace.
            if (State == SessionState.AuthConnected) // TODO: why is this needed? Why didn't retail have this problem? Is this fuzzy memory?
            {
                if (lastCharacterSelectPingReply == DateTime.MinValue)
                    lastCharacterSelectPingReply = DateTime.UtcNow.AddSeconds(100);
                else if (DateTime.UtcNow > lastCharacterSelectPingReply)
                {
                    Network.EnqueueSend(new GameEventPingResponse(this));
                    lastCharacterSelectPingReply = DateTime.UtcNow.AddSeconds(100);
                }
            }
            else if (lastCharacterSelectPingReply != DateTime.MinValue)
                lastCharacterSelectPingReply = DateTime.MinValue;
        }

19 View Source File : UnixTime.cs
License : MIT License
Project Creator : aabiryukov

public static DateTime ConvertToDateTime(UInt32 unixtime) { return st_unixEpoch.AddSeconds(unixtime); }

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

public void Refill(Player player, CraftTool spirit)
        {
            // TODO: this should be moved to recipe system
            if (!IsEncapsulatedSpirit(spirit))
            {
                player.SendUseDoneEvent();
                return;
            }

            if (player.IsBusy)
            {
                player.SendUseDoneEvent(WeenieError.YoureTooBusy);
                return;
            }

            // verify use requirements
            var useError = VerifyUseRequirements(player, spirit, this);
            if (useError != WeenieError.None)
            {
                player.SendUseDoneEvent(useError);
                return;
            }

            player.IsBusy = true;

            var animTime = 0.0f;

            var actionChain = new ActionChain();

            // handle switching to peace mode
            if (player.CombatMode != CombatMode.NonCombat)
            {
                var stanceTime = player.SetCombatMode(CombatMode.NonCombat);
                actionChain.AddDelaySeconds(stanceTime);

                animTime += stanceTime;
            }

            // perform clapping motion
            animTime += player.EnqueueMotion(actionChain, MotionCommand.ClapHands);

            actionChain.AddAction(player, () =>
            {
                // re-verify
                var useError = VerifyUseRequirements(player, spirit, this);
                if (useError != WeenieError.None)
                {
                    player.SendUseDoneEvent(useError);
                    player.IsBusy = false;
                    return;
                }

                if (Structure == MaxStructure)
                {
                    player.Session.Network.EnqueueSend(new GameMessageSystemChat("This essence is already full.", ChatMessageType.Broadcast));
                    player.SendUseDoneEvent(WeenieError.YouDoNotPreplacedCraftingRequirements);
                    player.IsBusy = false;
                    return;
                }

                player.UpdateProperty(this, PropertyInt.Structure, MaxStructure);

                player.TryConsumeFromInventoryWithNetworking(spirit, 1);

                player.Session.Network.EnqueueSend(new GameMessageSystemChat("You add the spirit to the essence.", ChatMessageType.Broadcast));

                player.SendUseDoneEvent();

                player.IsBusy = false;
            });

            player.EnqueueMotion(actionChain, MotionCommand.Ready);

            actionChain.EnqueueChain();

            player.NextUseTime = DateTime.UtcNow.AddSeconds(animTime);
        }

19 View Source File : ExtensionMethod.cs
License : MIT License
Project Creator : 1iveowl

public static DateTime UnixTimeStampToDateTimeUtc(this double unixTimeStamp)
        {
            // Unix timestamp is seconds past epoch
            var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            dateTime = dateTime.AddSeconds(unixTimeStamp).ToUniversalTime();
            return dateTime;
        }

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

public void LaunchMissile(WorldObject target, int attackSequence, MotionStance stance, bool subsequent = false)
        {
            if (AttackSequence != attackSequence)
                return;

            var weapon = GetEquippedMissileWeapon();
            if (weapon == null || CombatMode == CombatMode.NonCombat)
            {
                OnAttackDone();
                return;
            }

            var ammo = weapon.IsAmmoLauncher ? GetEquippedAmmo() : weapon;
            if (ammo == null)
            {
                OnAttackDone();
                return;
            }

            var launcher = GetEquippedMissileLauncher();

            var creature = target as Creature;
            if (!IsAlive || IsBusy || MissileTarget == null || creature == null || !creature.IsAlive || suicideInProgress)
            {
                OnAttackDone();
                return;
            }

            if (!TargetInRange(target))
            {
                // this must also be sent to actually display the transient message
                SendWeenieError(WeenieError.MissileOutOfRange);

                // this prevents the accuracy bar from refilling when 'repeat attacks' is enabled
                OnAttackDone();

                return;
            }

            var actionChain = new ActionChain();

            if (subsequent && !IsFacing(target))
            {
                var rotateTime = Rotate(target);
                actionChain.AddDelaySeconds(rotateTime);
            }

            // launch animation
            // point of no return beyond this point -- cannot be cancelled
            actionChain.AddAction(this, () => Attacking = true);

            if (subsequent)
            {
                // client shows hourglreplaced, until attack done is received
                // retail only did this for subsequent attacks w/ repeat attacks on
                Session.Network.EnqueueSend(new GameEventCombatCommenceAttack(Session));
            }

            var projectileSpeed = GetProjectileSpeed();

            // get z-angle for aim motion
            var aimVelocity = GetAimVelocity(target, projectileSpeed);

            var aimLevel = GetAimLevel(aimVelocity);

            // calculate projectile spawn pos and velocity
            var localOrigin = GetProjectileSpawnOrigin(ammo.WeenieClreplacedId, aimLevel);

            var velocity = CalculateProjectileVelocity(localOrigin, target, projectileSpeed, out Vector3 origin, out Quaternion orientation);

            //Console.WriteLine($"Velocity: {velocity}");

            if (velocity == Vector3.Zero)
            {
                // pre-check succeeded, but actual velocity calculation failed
                SendWeenieError(WeenieError.MissileOutOfRange);

                // this prevents the accuracy bar from refilling when 'repeat attacks' is enabled
                Attacking = false;
                OnAttackDone();
                return;
            }

            var launchTime = EnqueueMotionPersist(actionChain, aimLevel);

            // launch projectile
            actionChain.AddAction(this, () =>
            {
                // handle self-procs
                TryProcEquippedItems(this, this, true, weapon);

                var sound = GetLaunchMissileSound(weapon);
                EnqueueBroadcast(new GameMessageSound(Guid, sound, 1.0f));

                // stamina usage
                // TODO: ensure enough stamina for attack
                // TODO: verify formulas - double/triple cost for bow/xbow?
                var staminaCost = GetAttackStamina(GetAccuracyRange());
                UpdateVitalDelta(Stamina, -staminaCost);

                var projectile = LaunchProjectile(launcher, ammo, target, origin, orientation, velocity);
                UpdateAmmoAfterLaunch(ammo);
            });

            // ammo remaining?
            if (!ammo.UnlimitedUse && (ammo.StackSize == null || ammo.StackSize <= 1))
            {
                actionChain.AddAction(this, () =>
                {
                    Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "You are out of ammunition!"));
                    SetCombatMode(CombatMode.NonCombat);
                    Attacking = false;
                    OnAttackDone();
                });

                actionChain.EnqueueChain();
                return;
            }

            // reload animation
            var animSpeed = GetAnimSpeed();
            var reloadTime = EnqueueMotionPersist(actionChain, stance, MotionCommand.Reload, animSpeed);

            // reset for next projectile
            EnqueueMotionPersist(actionChain, stance, MotionCommand.Ready);
            var linkTime = MotionTable.GetAnimationLength(MotionTableId, stance, MotionCommand.Reload, MotionCommand.Ready);
            //var cycleTime = MotionTable.GetCycleLength(MotionTableId, CurrentMotionState.Stance, MotionCommand.Ready);

            actionChain.AddAction(this, () =>
            {
                if (CombatMode == CombatMode.Missile)
                    EnqueueBroadcast(new GameMessageParentEvent(this, ammo, ACE.Enreplacedy.Enum.ParentLocation.RightHand, ACE.Enreplacedy.Enum.Placement.RightHandCombat));
            }); 

            actionChain.AddDelaySeconds(linkTime);

            actionChain.AddAction(this, () =>
            {
                Attacking = false;

                if (creature.IsAlive && GetCharacterOption(CharacterOption.AutoRepeatAttacks) && !IsBusy && !AttackCancelled)
                {
                    // client starts refilling accuracy bar
                    Session.Network.EnqueueSend(new GameEventAttackDone(Session));

                    AccuracyLevel = AttackQueue.Fetch();

                    // can be cancelled, but cannot be pre-empted with another attack
                    var nextAttack = new ActionChain();
                    var nextRefillTime = AccuracyLevel;

                    NextRefillTime = DateTime.UtcNow.AddSeconds(nextRefillTime);
                    nextAttack.AddDelaySeconds(nextRefillTime);

                    // perform next attack
                    nextAttack.AddAction(this, () => { LaunchMissile(target, attackSequence, stance, true); });
                    nextAttack.EnqueueChain();
                }
                else
                    OnAttackDone();
            });

            actionChain.EnqueueChain();

            if (UnderLifestoneProtection)
                LifestoneProtectionDispel();
        }

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

public WorldObjectsValues CostAllWorldObjects()
        {
            if (AllWorldObjectsTime < DateTime.UtcNow.AddSeconds(-5))
            {
                AllWorldObjectsTime = DateTime.UtcNow;
                AllWorldObjects = CostWorldObjects();
            }
            return AllWorldObjects;
        }

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

public void Drow(Rect inRect)
        {
            var iconWidth = 25f;
            var iconWidthSpase = 30f;

            /// -----------------------------------------------------------------------------------------
            /// Список каналов
            ///
            if (SessionClientController.Data.Chats != null)
            {
                lock (SessionClientController.Data.Chats)
                {
                    if (SessionClientController.Data.ChatNotReadPost > 0) SessionClientController.Data.ChatNotReadPost = 0;

                    //Loger.Log("Client " + SessionClientController.Data.Chats.Count);
                    if (lbCannalsHeight == 0)
                    {
                        var textHeight = new DialogControlBase().TextHeight;
                        lbCannalsHeight = (float)Math.Round((decimal)(inRect.height / 2f / textHeight)) * textHeight;
                    }
                    Widgets.Label(new Rect(inRect.x, inRect.y + iconWidthSpase + lbCannalsHeight, 100f, 22f), "OCity_Dialog_Players".Translate());

                    if (lbCannals == null)
                    {
                        //первый запуск
                        lbCannals = new ListBox<string>();
                        lbCannals.Area = new Rect(inRect.x
                            , inRect.y + iconWidthSpase
                            , 100f
                            , lbCannalsHeight);
                        lbCannals.OnClick += (index, text) => DataLastChatsTime = DateTime.MinValue; /*StatusTemp = text;*/
                        lbCannals.SelectedIndex = 0;
                    }

                    if (lbPlayers == null)
                    {
                        //первый запуск
                        lbPlayers = new ListBox<ListBoxPlayerItem>();
                        lbPlayers.OnClick += (index, item) =>
                        {
                        //убираем выделение
                        lbPlayers.SelectedIndex = -1;
                        //вызываем контекстное меню
                        PlayerItemMenu(item);
                        };

                        lbPlayers.Tooltip = (item) => item.Tooltip;
                    }

                    if (PanelLastHeight != inRect.height)
                    {
                        PanelLastHeight = inRect.height;
                        lbPlayers.Area = new Rect(inRect.x
                            , inRect.y + iconWidthSpase + lbCannalsHeight + 22f
                            , 100f
                            , inRect.height - (iconWidthSpase + lbCannalsHeight + 22f));
                    }

                    if (NeedUpdateChat)
                    {
                        lbCannalsLastSelectedIndex = -1;
                        NeedUpdateChat = false;
                    }

                    var nowUpdateChat = DataLastChatsTime != SessionClientController.Data.ChatsTime.Time;
                    if (nowUpdateChat)
                    {
                        Loger.Log("Client UpdateChats nowUpdateChat");
                        DataLastChatsTime = SessionClientController.Data.ChatsTime.Time;
                        lbCannalsLastSelectedIndex = -1; //сброс для обновления содержимого окна
                        NeedUpdateChat = true;
                    }

                    if (nowUpdateChat
                        || DataLastChatsTimeUpdateTime < DateTime.UtcNow.AddSeconds(-5))
                    {
                        DataLastChatsTimeUpdateTime = DateTime.UtcNow;
                        //пишем в лог
                        var updateLogHash = SessionClientController.Data.Chats.Count * 1000000
                            + SessionClientController.Data.Chats.Sum(c => c.Posts.Count);
                        if (updateLogHash != UpdateLogHash)
                        {
                            UpdateLogHash = updateLogHash;
                            Loger.Log("Client UpdateChats chats="
                                + SessionClientController.Data.Chats.Count.ToString()
                                + " players=" + SessionClientController.Data.Players.Count.ToString());
                        }

                        //устанавливаем данные
                        lbCannals.DataSource = SessionClientController.Data.Chats
                            //.OrderBy(c => (c.OwnerMaker ? "2" : "1") + c.Name) нелья просто отсортировать, т.к. потом находим по индексу
                            .Select(c => c.Name)
                            .ToList();
                        if (lbCannalsGoToChat != null)
                        {
                            var lbCannalsGoToChatIndex = lbCannals.DataSource.IndexOf(lbCannalsGoToChat);
                            if (lbCannalsGoToChatIndex >= 0)
                            {
                                lbCannals.SelectedIndex = lbCannalsGoToChatIndex;
                                lbCannalsGoToChat = null;
                            }
                        }

                        //Заполняем список игроков по группами {
                        lbPlayers.DataSource = new List<ListBoxPlayerItem>();
                        var allreadyLogin = new List<string>();
                        Func<string, string, ListBoxPlayerItem> addPl = (login, text) =>
                        {
                            allreadyLogin.Add(login);
                            var n = new ListBoxPlayerItem()
                            {
                                Login = login,
                                Text = text,
                                Tooltip = login
                            };
                            lbPlayers.DataSource.Add(n);
                            return n;
                        };

                        Action<string> addreplaced = (text) =>
                        {
                            if (lbPlayers.DataSource.Count > 0) addPl(null, " ").Groupreplacedle = true;
                            addPl(null, " <i>– " + text + " –</i> ").Groupreplacedle = true;
                        };

                        Func<string, bool> isOnline = (login) => login == SessionClientController.My.Login
                            || SessionClientController.Data.Players.ContainsKey(login) && SessionClientController.Data.Players[login].Online;
                        Func<bool, string, string> frameOnline = (online, txt) =>
                            online
                            ? "<b>" + txt + "</b>"
                            : "<color=#888888ff>" + txt + "</color>";

                        if (lbCannals.SelectedIndex > 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex)
                        {
                            var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex];

                            // в чате создатель
                            addreplaced("OCity_Dialog_Exchenge_Chat".Translate());
                            var n = addPl(selectCannal.OwnerLogin
                                , frameOnline(isOnline(selectCannal.OwnerLogin), "★ " + selectCannal.OwnerLogin));
                            n.Tooltip += "OCity_Dialog_ChennelOwn".Translate();
                            n.InChat = true;

                            // в чате
                            var offlinePartyLogin = new List<string>();
                            for (int i = 0; i < selectCannal.PartyLogin.Count; i++)
                            {
                                var lo = selectCannal.PartyLogin[i];
                                if (lo != "system" && lo != selectCannal.OwnerLogin)
                                {
                                    if (isOnline(lo))
                                    {
                                        n = addPl(lo, frameOnline(true, lo));
                                        n.Tooltip += "OCity_Dialog_ChennelUser".Translate();
                                        n.InChat = true;
                                    }
                                    else
                                        offlinePartyLogin.Add(lo);
                                }
                            }

                            // в чате оффлайн
                            //addreplaced("оффлайн".Translate());
                            for (int i = 0; i < offlinePartyLogin.Count; i++)
                            {
                                var lo = offlinePartyLogin[i];
                                n = addPl(lo, frameOnline(false, lo));
                                n.Tooltip += "OCity_Dialog_ChennelUser".Translate();
                                n.InChat = true;
                            }
                        }

                        var other = SessionClientController.Data.Chats[0].PartyLogin == null
                            ? new List<string>()
                            : SessionClientController.Data.Chats[0].PartyLogin
                            .Where(p => p != "" && p != "system" && !allreadyLogin.Any(al => al == p))
                            .ToList();
                        if (other.Count > 0)
                        {
                            // игроки
                            addreplaced("OCity_Dialog_Exchenge_Gamers".Translate());
                            var offlinePartyLogin = new List<string>();
                            for (int i = 0; i < other.Count; i++)
                            {
                                var lo = other[i];
                                if (isOnline(lo))
                                {
                                    var n = addPl(lo, frameOnline(true, lo));
                                    //n.Tooltip += "OCity_Dialog_ChennelUser".Translate();
                                }
                                else
                                    offlinePartyLogin.Add(lo);
                            }

                            // игроки оффлайн
                            //addreplaced("оффлайн".Translate());
                            for (int i = 0; i < offlinePartyLogin.Count; i++)
                            {
                                var lo = offlinePartyLogin[i];
                                var n = addPl(lo, frameOnline(false, lo));
                                //n.Tooltip += "OCity_Dialog_ChennelUser".Translate();
                            }

                        }
                    }

                    lbCannals.Drow();
                    lbPlayers.Drow();

                    var iconRect = new Rect(inRect.x, inRect.y, iconWidth, iconWidth);
                    TooltipHandler.TipRegion(iconRect, "OCity_Dialog_ChennelCreate".Translate());
                    if (Widgets.ButtonImage(iconRect, GeneralTexture.IconAddTex))
                    {
                        CannalAdd();
                    }

                    if (lbCannals.SelectedIndex > 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex)
                    {
                        //Если что-то выделено, и это не общий чат (строка 0)
                        iconRect.x += iconWidthSpase;
                        TooltipHandler.TipRegion(iconRect, "OCity_Dialog_ChennelClose".Translate());
                        if (Widgets.ButtonImage(iconRect, GeneralTexture.IconDelTex))
                        {
                            CannalDelete();
                        }
                    }

                    if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex)
                    {
                        iconRect.x += iconWidthSpase;
                        TooltipHandler.TipRegion(iconRect, "OCity_Dialog_OthersFunctions".Translate());
                        if (Widgets.ButtonImage(iconRect, GeneralTexture.IconSubMenuTex))
                        {
                            CannalsMenuShow();
                        }
                    }

                    /// -----------------------------------------------------------------------------------------
                    /// Чат
                    ///
                    if (lbCannalsLastSelectedIndex != lbCannals.SelectedIndex)
                    {
                        lbCannalsLastSelectedIndex = lbCannals.SelectedIndex;
                        if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex)
                        {
                            var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex];
                            if (selectCannal.Posts != null && selectCannal.Posts.Count > 0)
                            {
                                var chatLastPostTime = selectCannal.Posts.Max(p => p.Time);
                                if (ChatLastPostTime != chatLastPostTime)
                                {
                                    ChatLastPostTime = chatLastPostTime;
                                    Func<ChatPost, string> getPost = (cp) => "[" + cp.Time.ToGoodUtcString("dd HH:mm ") + cp.OwnerLogin + "]: " + cp.Message;

                                    var totalLength = 0;
                                    ChatBox.Text = selectCannal.Posts
                                        .Reverse<ChatPost>()
                                        .Where(i => (totalLength += i.Message.Length) < 5000)
                                        .Aggregate("", (r, i) => getPost(i) + (r == "" ? "" : Environment.NewLine + r));
                                    ChatScrollToDown = true;
                                }
                                //else ChatBox.Text = "";
                            }
                            //else ChatBox.Text = "";
                        }
                        else
                            ChatBox.Text = "";
                    }

                    if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex)
                    {
                        var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex];
                        var chatAreaOuter = new Rect(inRect.x + 110f, inRect.y, inRect.width - 110f, inRect.height - 30f);
                        ChatBox.Drow(chatAreaOuter, ChatScrollToDown);
                        ChatScrollToDown = false;

                        var rrect = new Rect(inRect.x + inRect.width - 25f, inRect.y + inRect.height - 25f, 25f, 25f);
                        Text.Font = GameFont.Medium;
                        Text.Anchor = TextAnchor.MiddleCenter;
                        Widgets.Label(rrect, "▶");
                        Text.Font = GameFont.Small;
                        Text.Anchor = TextAnchor.MiddleLeft;
                        bool rrcklick = Widgets.ButtonInvisible(rrect);

                        if (ChatInputText != "")
                        {
                            if (Mouse.IsOver(rrect))
                            {
                                Widgets.DrawHighlight(rrect);
                            }

                            var ev = Event.current;
                            if (ev.isKey && ev.type == EventType.KeyDown && ev.keyCode == KeyCode.Return
                                || rrcklick)
                            {
                                //SoundDefOf.RadioButtonClicked.PlayOneShotOnCamera();
                                SessionClientController.Command((connect) =>
                                {
                                    connect.PostingChat(selectCannal.Id, ChatInputText);
                                });

                                ChatInputText = "";
                            }
                        }

                        GUI.SetNextControlName("StartTextField");
                        ChatInputText = GUI.TextField(new Rect(inRect.x + 110f, inRect.y + inRect.height - 25f, inRect.width - 110f - 30f, 25f)
                            , ChatInputText, 10000);

                        if (NeedFockus)
                        {
                            NeedFockus = false;
                            GUI.FocusControl("StartTextField");
                        }
                    }
                }
            }
        }

19 View Source File : CSRedisClientKeyTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
		public void ExpireAt() {
			replacedert.True(rds.MSet("TestExpireAt_null1", base.Null, "TestExpireAt_string1", base.String, "TestExpireAt_bytes1", base.Bytes, "TestExpireAt_clreplaced1", base.Clreplaced));

			replacedert.True(rds.ExpireAt("TestExpireAt_null1", DateTime.UtcNow.AddSeconds(10)));
			replacedert.InRange(rds.Ttl("TestExpireAt_null1"), 9, 20);
			replacedert.True(rds.ExpireAt("TestExpireAt_string1", DateTime.UtcNow.AddHours(1)));
			replacedert.InRange(rds.Ttl("TestExpireAt_string1"), 60 * 60 - 10, 60 * 60 + 10);
		}

19 View Source File : DwellHandler.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public void OnFocusEnter(FocusEventData eventData)
        {
            if (eventData.NewFocusedObject == gameObject
                && eventData.Pointer.InputSourceParent.SourceType == dwellProfile.DwellPointerType)
            {
                HasFocus = true;

                // check intent to resume
                if (CurrentDwellState == DwellStateType.DwellCanceled
                    && pointer.InputSourceParent.SourceId == eventData.Pointer.InputSourceParent.SourceId // Make sure the returning pointer id is the same
                    && (DateTime.UtcNow - focusExitTime) <= dwellProfile.TimeToAllowDwellResume)
                {
                    // Add the time duration focus was away since this is a dwell resume and we need to account for the time that focus was lost for the target.
                    // replacedigning this the current time would restart computation for dwell progress.
                    focusEnterTime = focusEnterTime.AddSeconds((DateTime.UtcNow - focusExitTime).TotalSeconds);
                    CurrentDwellState = DwellStateType.DwellStarted;
                    DwellStarted.Invoke(pointer);
                }
                // dwell state machine re-starts
                else if (CurrentDwellState <= DwellStateType.DwellIntended)
                {
                    focusEnterTime = DateTime.UtcNow;
                    CurrentDwellState = DwellStateType.FocusGained;
                    pointer = eventData.Pointer;
                    FillTimer = 0;
                }
            }
        }

19 View Source File : KeysTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void ExpireAt()
        {
            cli.MSet("TestExpireAt_null1", base.Null, "TestExpireAt_string1", base.String, "TestExpireAt_bytes1", base.Bytes, "TestExpireAt_clreplaced1", base.Clreplaced);

            replacedert.True(cli.ExpireAt("TestExpireAt_null1", DateTime.UtcNow.AddSeconds(10)));
            replacedert.InRange(cli.Ttl("TestExpireAt_null1"), 9, 20);
            replacedert.True(cli.ExpireAt("TestExpireAt_string1", DateTime.UtcNow.AddHours(1)));
            replacedert.InRange(cli.Ttl("TestExpireAt_string1"), 60 * 60 - 10, 60 * 60 + 10);
        }

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

public void AddSide(Player player, ChessColor color)
        {
            // ai is represented with object guid 0
            var playerGuid = player != null ? player.Guid : new ObjectGuid(0);

            Sides[(int)color] = new ChessSide(playerGuid, color);

            if (player != null)
                player.ChessMatch = this;

            // spawn weenie pieces in the world for side
            Logic.WalkPieces((piece) =>
            {
                if (piece.Color == color)
                    AddWeeniePiece(piece);
            });

            if (Sides[(int)Chess.InverseColor(color)] == null)
            {
                var ai_enabled = PropertyManager.GetDouble("chess_ai_start_time").Item;
                if (ai_enabled > 0)
                {
                    player.Session.Network.EnqueueSend(new GameMessageSystemChat($"If another player doesn't join within {ai_enabled} seconds, the game will automatically start with AI", ChatMessageType.Broadcast));
                    StartAiTime = DateTime.UtcNow.AddSeconds(ai_enabled);
                }
            }
            else
                Actions.Enqueue(new ChessDelayedAction(ChessDelayedActionType.Start));
        }

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

public static DateTime GetDateTimeFromTimestamp(double timestamp)
        {
            return unixEpoch.AddSeconds(timestamp);
        }

19 View Source File : Converter.cs
License : MIT License
Project Creator : 4egod

public static DateTime FromUnixTimestamp(this int unixTimestamp)
        {
            DateTime result = new DateTime(1970, 1, 1);
            result = result.AddSeconds(unixTimestamp);
            return result;
        }

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

public void NotifyGenerator(ObjectGuid target, RegenerationType eventType)
        {
            //log.Debug($"{_generator.Name}.NotifyGenerator({target:X8}, {eventType})");

            Spawned.TryGetValue(target.Full, out var woi);

            if (woi == null) return;

            var adjEventType = eventType; // some generators use pickup when they mean to use destruction, some use destruction when they mean to use pickup. this data comes from 16py mostly and these issues are corrected below.
            var whenCreate = (RegenerationType)Biota.WhenCreate;
            var adjWhenCreate = (RegenerationType)Biota.WhenCreate;

            if (eventType == RegenerationType.PickUp && whenCreate == RegenerationType.Destruction)
                adjEventType = RegenerationType.Destruction;

            if (eventType == RegenerationType.Destruction && whenCreate == RegenerationType.PickUp)
                adjEventType = RegenerationType.PickUp;

            // If WhenCreate is Undef, replacedume it means Destruction (bad data)
            if (eventType == RegenerationType.Destruction && whenCreate == RegenerationType.Undef)
                adjWhenCreate = RegenerationType.Destruction;

            // If WhenCreate is Undef, replacedume it means Pickup (bad data)
            if (eventType == RegenerationType.PickUp && whenCreate == RegenerationType.Undef)
                adjWhenCreate = RegenerationType.PickUp;

            //if (eventType != adjEventType)
            //    log.Warn($"0x{Generator.Guid}:{Generator.Name}({Generator.WeenieClreplacedId}).GeneratorProfile[{LinkId}].NotifyGenerator: RegenerationType = {eventType.ToString()}, WhenCreate = {whenCreate.ToString()}, Using {adjEventType.ToString()} as RegenerationType instead");

            if (whenCreate != adjWhenCreate)
                log.Warn($"0x{Generator.Guid}:{Generator.Name}({Generator.WeenieClreplacedId}).GeneratorProfile[{LinkId}].NotifyGenerator: RegenerationType = {eventType.ToString()}, WhenCreate = {whenCreate.ToString()}, Using {adjWhenCreate.ToString()} as WhenCreate instead");

            if (adjWhenCreate != adjEventType)
                return;            

            RemoveQueue.Enqueue((DateTime.UtcNow.AddSeconds(Delay), woi.Guid.Full));
        }

19 View Source File : ObjectPool.cs
License : MIT License
Project Creator : 2881099

private void CheckAvailable(int interval)
        {

            new Thread(() =>
            {

                if (UnavailableException != null)
                {
                    var bgcolor = Console.BackgroundColor;
                    var forecolor = Console.ForegroundColor;
                    Console.BackgroundColor = ConsoleColor.DarkYellow;
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write($"【{Policy.Name}】恢复检查时间:{DateTime.Now.AddSeconds(interval)}");
                    Console.BackgroundColor = bgcolor;
                    Console.ForegroundColor = forecolor;
                    Console.WriteLine();
                }

                while (UnavailableException != null)
                {

                    if (running == false) return;

                    Thread.CurrentThread.Join(TimeSpan.FromSeconds(interval));

                    if (running == false) return;

                    try
                    {

                        var conn = getFree(false);
                        if (conn == null) throw new Exception($"CheckAvailable 无法获得资源,{this.Statistics}");

                        try
                        {

                            if (Policy.OnCheckAvailable(conn) == false) throw new Exception("CheckAvailable 应抛出异常,代表仍然不可用。");
                            break;

                        }
                        finally
                        {

                            Return(conn);
                        }

                    }
                    catch (Exception ex)
                    {
                        var bgcolor = Console.BackgroundColor;
                        var forecolor = Console.ForegroundColor;
                        Console.BackgroundColor = ConsoleColor.DarkYellow;
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.Write($"【{Policy.Name}】仍然不可用,下一次恢复检查时间:{DateTime.Now.AddSeconds(interval)},错误:({ex.Message})");
                        Console.BackgroundColor = bgcolor;
                        Console.ForegroundColor = forecolor;
                        Console.WriteLine();
                    }
                }

                RestoreToAvailable();

            }).Start();
        }

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

public static void UseObjectOnTarget(Player player, WorldObject source, WorldObject target)
        {
            //Console.WriteLine($"Tailoring.UseObjectOnTarget({player.Name}, {source.Name}, {target.Name})");

            // verify use requirements
            var useError = VerifyUseRequirements(player, source, target);
            if (useError != WeenieError.None)
            {
                player.SendUseDoneEvent(useError);
                return;
            }

            var animTime = 0.0f;

            var actionChain = new ActionChain();

            // handle switching to peace mode
            if (player.CombatMode != CombatMode.NonCombat)
            {
                var stanceTime = player.SetCombatMode(CombatMode.NonCombat);
                actionChain.AddDelaySeconds(stanceTime);

                animTime += stanceTime;
            }

            // perform clapping motion
            animTime += player.EnqueueMotion(actionChain, MotionCommand.ClapHands);

            actionChain.AddAction(player, () =>
            {
                // re-verify
                var useError = VerifyUseRequirements(player, source, target);
                if (useError != WeenieError.None)
                {
                    player.SendUseDoneEvent(useError);
                    return;
                }

                DoTailoring(player, source, target);
            });

            actionChain.EnqueueChain();

            player.NextUseTime = DateTime.UtcNow.AddSeconds(animTime);
        }

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

public async Task<Unit> Handle(FightWithNpcCommand command, CancellationToken cancellationToken)
        {
            var playerId = command.PlayerId;
            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                return Unit.Value;
            }

            var npcId = command.NpcId;
            var npc = await _npcDomainService.Get(npcId);
            if (npc == null)
            {
                return Unit.Value;
            }


            if (!npc.CanFight)
            {
                await _bus.RaiseEvent(new DomainNotification($"你不能与[{npc.Name}]切磋!"));
                return Unit.Value;
            }


            if (player.RoomId != npc.RoomId)
            {
                await _bus.RaiseEvent(new DomainNotification($"[{npc.Name}]已经离开此地,无法发起切磋!"));
                return Unit.Value;
            }

            if (npc.IsDead)
            {
                await _bus.RaiseEvent(new DomainNotification($"[{npc.Name}]已经死了,无法发起切磋!"));
                return Unit.Value;
            }

            var npcFightingPlayerId = await _redisDb.StringGet<int>(string.Format(RedisKey.NpcFighting, npc.Id));
            if (npcFightingPlayerId > 0 && npcFightingPlayerId != playerId)
            {
                await _bus.RaiseEvent(new DomainNotification($"[{npc.Name}]拒绝了你的切磋请求!"));
                return Unit.Value;
            }



            var hasChangedStatus= await BeginChangeStatus(new PlayerStatusModel
            {
                PlayerId = playerId,
                Status = PlayerStatusEnum.切磋,
                TargetType = TargetTypeEnum.Npc,
                TargetId = npcId
            });

            if (hasChangedStatus)
            {
                await _mudProvider.ShowMessage(playerId, $"【切磋】你对着[{npc.Name}]说道:在下[{player.Name}],领教阁下的高招!");

                await _mudProvider.ShowMessage(playerId, $"【切磋】[{npc.Name}]说道:「既然阁下赐教,在下只好奉陪,我们点到为止。」");

                await _redisDb.StringSet(string.Format(RedisKey.NpcFighting, npc.Id), playerId, DateTime.Now.AddSeconds(20));

                int minDelay = npc.Speed;
                int maxDelay = minDelay + 1000;

                var actionPoint = await _redisDb.StringGet<int>(string.Format(RedisKey.ActionPoint, playerId));
                await _mudProvider.ShowActionPoint(playerId, actionPoint);

                await _recurringQueue.Publish($"npc_{npc.Id}", new NpcStatusModel
                {
                    NpcId = npc.Id,
                    Status = NpcStatusEnum.切磋,
                    TargetId = playerId,
                    TargetType = TargetTypeEnum.玩家
                }, minDelay, maxDelay);

                await _mudProvider.ShowBox(playerId, new { boxName = "fighting" });


                var myWeapons = await _playerWareDomainService.GetAllWeapon(playerId);
                var myWeaponIds = myWeapons.Select(x => x.WareId);

                var weapons = (await _wareDomainService.GetAll()).Where(x => x.Category == WareCategoryEnum.武器 && myWeaponIds.Contains(x.Id)).ToList();



                var skillModels = new List<SkillModel>();

                var playerSkills = await _playerSkillDomainService.GetAll(player.Id);

                var ids = playerSkills?.Select(x => x.SkillId);

                var skills = (await _skillDomainService.GetAll()).Where(x => x.Category == SkillCategoryEnum.外功 && ids.Contains(x.Id));
                foreach (var playerSkill in playerSkills)
                {
                    var skill = skills.FirstOrDefault(x => x.Id == playerSkill.SkillId);
                    if (skill != null)
                    {
                        switch (skill.Type)
                        {
                            case SkillTypeEnum.刀法:
                                if (weapons.Count(x => x.Type == WareTypeEnum.刀) == 0)
                                {
                                    continue;
                                }
                                break;
                            case SkillTypeEnum.剑法:
                                if (weapons.Count(x => x.Type == WareTypeEnum.剑) == 0)
                                {
                                    continue;
                                }
                                break;
                            case SkillTypeEnum.枪棍:
                                if (weapons.Count(x => x.Type == WareTypeEnum.枪) == 0)
                                {
                                    continue;
                                }
                                break;

                        }

                        var skillModel = _mapper.Map<SkillModel>(skill);
                        skillModel.ObjectSkillId = playerSkill.Id;
                        skillModel.Level = playerSkill.Level;
                        skillModel.Exp = playerSkill.Exp;
                        skillModel.IsDefault = playerSkill.IsDefault;
                        skillModels.Add(skillModel);
                    }

                }

                if (skillModels.Count(x => (x.Type == SkillTypeEnum.刀法 || x.Type == SkillTypeEnum.剑法 || x.Type == SkillTypeEnum.枪棍) && x.IsDefault) == 0)
                {
                    skillModels.FirstOrDefault(x => x.Type == SkillTypeEnum.拳脚).IsDefault = true;
                }

                await _mudProvider.ShowFightingSkill(playerId, skillModels);
            }


            return Unit.Value;
        }

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

private static DateTime LogStatusUpdate(DateTime logUpdateTS, string logMessage)
        {
            if (logUpdateTS == DateTime.MinValue || DateTime.UtcNow > logUpdateTS.ToUniversalTime())
            {
                log.Info(logMessage);
                logUpdateTS = DateTime.UtcNow.AddSeconds(10);
            }

            return logUpdateTS;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

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

[GameAction(GameActionType.QueryBirth)]
        public static void Handle(ClientMessage message, Session session)
        {
            var target = message.Payload.ReadString16L();
            DateTime playerDOB = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            playerDOB = playerDOB.AddSeconds(session.Player.CreationTimestamp.Value).ToUniversalTime();

            var dobEvent = new GameMessages.Messages.GameMessageSystemChat($"You were born on {playerDOB:G}.", ChatMessageType.Broadcast);

            session.Network.EnqueueSend(dobEvent);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 8x8

public JaaSJwtBuilder WithDefaults()
            {
                return WithExpTime(DateTime.UtcNow.AddSeconds(EXP_TIME_DELAY_SEC))
                    .WithNbfTime(DateTime.UtcNow.AddSeconds(-NBF_TIME_DELAY_SEC))
                    .WithLiveStreamingEnabled(true)
                    .WithRecordingEnabled(true)
                    .WithOutboundCallEnabled(true)
                    .WithTranscriptionEnabled(true)
                    .WithModerator(true)
                    .WithRoomName("*")
                    .WithUserId(System.Guid.NewGuid().ToString());
            }

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

protected override void OnInitialInventoryLoadCompleted()
        {
            if (Level.HasValue)
            {
                var dtTimeToRot = DateTime.UtcNow.AddSeconds(TimeToRot ?? 0);
                var tsDecay = dtTimeToRot - DateTime.UtcNow;

                log.Debug($"[CORPSE] {Name} (0x{Guid}) Reloaded from Database: Corpse Level: {Level ?? 0} | InventoryLoaded: {InventoryLoaded} | Inventory.Count: {Inventory.Count} | TimeToRot: {TimeToRot} | CreationTimestamp: {CreationTimestamp} ({Time.GetDateTimeFromTimestamp(CreationTimestamp ?? 0).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}) | Corpse should not decay before: {dtTimeToRot.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}, {tsDecay.ToString("%d")} day(s), {tsDecay.ToString("%h")} hours, {tsDecay.ToString("%m")} minutes, and {tsDecay.ToString("%s")} seconds from now.");
            }
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 2881099

public DateTime Time() => Call("TIME", rt => rt.ThrowOrValue((a, _) => _epoch.AddSeconds(a[0].ConvertTo<long>()).AddTicks(a[1].ConvertTo<long>() * 10).ToLocalTime()));

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

public void DoHealMotion(Player healer, Player target, bool success)
        {
            if (!success || target.IsDead || target.Teleporting || target.suicideInProgress)
            {
                healer.SendUseDoneEvent();
                return;
            }

            healer.IsBusy = true;

            var motionCommand = healer.Equals(target) ? MotionCommand.SkillHealSelf : MotionCommand.SkillHealOther;

            var motion = new Motion(healer, motionCommand);
            var currentStance = healer.CurrentMotionState.Stance;
            var animLength = MotionTable.GetAnimationLength(healer.MotionTableId, currentStance, motionCommand);

            var startPos = new Physics.Common.Position(healer.PhysicsObj.Position);

            var actionChain = new ActionChain();
            //actionChain.AddAction(healer, () => healer.EnqueueBroadcastMotion(motion));
            actionChain.AddAction(healer, () => healer.SendMotionAsCommands(motionCommand, currentStance));
            actionChain.AddDelaySeconds(animLength);
            actionChain.AddAction(healer, () =>
            {
                // check healing move distance cap
                var endPos = new Physics.Common.Position(healer.PhysicsObj.Position);
                var dist = startPos.Distance(endPos);

                //Console.WriteLine($"Dist: {dist}");

                // only PKs affected by these caps?
                if (dist < Healing_MaxMove || healer.PlayerKillerStatus == PlayerKillerStatus.NPK)
                    DoHealing(healer, target);
                else
                    healer.Session.Network.EnqueueSend(new GameMessageSystemChat("Your movement disrupted healing!", ChatMessageType.Broadcast));

                healer.IsBusy = false;

                healer.SendUseDoneEvent();
            });

            healer.EnqueueMotion(actionChain, MotionCommand.Ready);

            actionChain.EnqueueChain();

            healer.NextUseTime = DateTime.UtcNow.AddSeconds(animLength);
        }

19 View Source File : UnixTime.cs
License : MIT License
Project Creator : aabiryukov

public static DateTime ConvertToDateTime(uint unixtime) { return st_unixEpoch.AddSeconds(unixtime); }

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

public void RushNextPlayerSave(int seconds)
        {
            if (LastRequestedDatabaseSave.AddSeconds(PlayerSaveIntervalSecs) <= DateTime.UtcNow.AddSeconds(seconds))
                return;

            LastRequestedDatabaseSave = DateTime.UtcNow.AddSeconds(seconds).AddSeconds(-1 * PlayerSaveIntervalSecs);
        }

19 View Source File : BssomBinaryPrimitives.cs
License : MIT License
Project Creator : 1996v

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static DateTime ReadDateTime(IBssomBuffer reader)
        {
            ref byte refb = ref reader.ReadRef(StandardDateTimeSize);
            long utcSeconds = ReadInt64LittleEndian(ref refb);
            uint utcNanoseconds = ReadUInt32LittleEndian(ref Unsafe.Add(ref refb, 8));
            reader.SeekWithOutVerify(StandardDateTimeSize, BssomSeekOrgin.Current);
            return DateTimeConstants.UnixEpoch.AddSeconds(utcSeconds).AddTicks(utcNanoseconds);
        }

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

public void HandleActionTargetedMissileAttack(uint targetGuid, uint attackHeight, float accuracyLevel)
        {
            //log.Info($"-");

            if (CombatMode != CombatMode.Missile)
            {
                log.Error($"{Name}.HandleActionTargetedMissileAttack({targetGuid:X8}, {attackHeight}, {accuracyLevel}) - CombatMode mismatch {CombatMode}, LastCombatMode: {LastCombatMode}");

                if (LastCombatMode == CombatMode.Missile)
                    CombatMode = CombatMode.Missile;
                else
                {
                    OnAttackDone();
                    return;
                }
            }

            if (IsBusy || Teleporting || suicideInProgress)
            {
                SendWeenieError(WeenieError.YoureTooBusy);
                OnAttackDone();
                return;
            }

            if (IsJumping)
            {
                SendWeenieError(WeenieError.YouCantDoThatWhileInTheAir);
                OnAttackDone();
                return;
            }

            if (PKLogout)
            {
                SendWeenieError(WeenieError.YouHaveBeenInPKBattleTooRecently);
                OnAttackDone();
                return;
            }

            var weapon = GetEquippedMissileWeapon();
            var ammo = GetEquippedAmmo();

            // sanity check
            accuracyLevel = Math.Clamp(accuracyLevel, 0.0f, 1.0f);

            if (weapon == null || weapon.IsAmmoLauncher && ammo == null)
            {
                OnAttackDone();
                return;
            }

            AttackHeight = (AttackHeight)attackHeight;
            AttackQueue.Add(accuracyLevel);

            if (MissileTarget == null)
                AccuracyLevel = accuracyLevel;  // verify

            // get world object of target guid
            var target = CurrentLandblock?.GetObject(targetGuid) as Creature;
            if (target == null || target.Teleporting)
            {
                //log.Warn($"{Name}.HandleActionTargetedMissileAttack({targetGuid:X8}, {AttackHeight}, {accuracyLevel}) - couldn't find creature target guid");
                OnAttackDone();
                return;
            }

            if (Attacking || MissileTarget != null && MissileTarget.IsAlive)
                return;

            if (!CanDamage(target))
            {
                SendTransientError($"You cannot attack {target.Name}");
                OnAttackDone();
                return;
            }

            //log.Info($"{Name}.HandleActionTargetedMissileAttack({targetGuid:X8}, {attackHeight}, {accuracyLevel})");

            AttackTarget = target;
            MissileTarget = target;

            var attackSequence = ++AttackSequence;

            // record stance here and preplaced it along
            // accounts for odd client behavior with swapping bows during repeat attacks
            var stance = CurrentMotionState.Stance;

            // turn if required
            var rotateTime = Rotate(target);
            var actionChain = new ActionChain();

            var delayTime = rotateTime;
            if (NextRefillTime > DateTime.UtcNow.AddSeconds(delayTime))
                delayTime = (float)(NextRefillTime - DateTime.UtcNow).TotalSeconds;

            actionChain.AddDelaySeconds(delayTime);

            // do missile attack
            actionChain.AddAction(this, () => LaunchMissile(target, attackSequence, stance));
            actionChain.EnqueueChain();
        }

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

public string GetTextInfo()
        {
            if (TextInfoTime < DateTime.UtcNow.AddSeconds(-5))
            {
                TextInfoTime = DateTime.UtcNow;
                TextInfo = GetTextInfoCalc();
            }
            return TextInfo;
        }

19 View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099

public Resp3Helper.ReadResult<DateTime> Time() => ExecCmd<long[]>("TIME").NewValue(a => new DateTime(1970, 0, 0).AddSeconds(a[0]).AddTicks(a[1] * 10));

19 View Source File : DateTimeExtensions.cs
License : MIT License
Project Creator : 1100100

public static DateTime ToDateTime(this long timestamp, TimestampUnit timestampUnit = TimestampUnit.Second, DateTimeKind dateTimeKind = DateTimeKind.Local)
        {
            var time = timestampUnit == TimestampUnit.Second
                ? Jan1St1970.AddSeconds(timestamp)
                : Jan1St1970.AddMilliseconds(timestamp);
            return dateTimeKind == DateTimeKind.Local ? time.ToLocalTime() : time;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : CSRedisClientKeyTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
		public void PExpireAt() {
			replacedert.True(rds.MSet("TestPExpireAt_null1", base.Null, "TestPExpireAt_string1", base.String, "TestPExpireAt_bytes1", base.Bytes, "TestPExpireAt_clreplaced1", base.Clreplaced));

			replacedert.True(rds.ExpireAt("TestPExpireAt_null1", DateTime.UtcNow.AddSeconds(10)));
			replacedert.InRange(rds.PTtl("TestPExpireAt_null1"), 9000, 20000);
			replacedert.True(rds.ExpireAt("TestPExpireAt_string1", DateTime.UtcNow.AddHours(1)));
			replacedert.InRange(rds.PTtl("TestPExpireAt_string1"), 1000 * 60 * 60 - 10000, 1000 * 60 * 60 + 10000);
		}

19 View Source File : KeysTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void PExpireAt()
        {
            cli.MSet("TestPExpireAt_null1", base.Null, "TestPExpireAt_string1", base.String, "TestPExpireAt_bytes1", base.Bytes, "TestPExpireAt_clreplaced1", base.Clreplaced);

            replacedert.True(cli.ExpireAt("TestPExpireAt_null1", DateTime.UtcNow.AddSeconds(10)));
            replacedert.InRange(cli.PTtl("TestPExpireAt_null1"), 9000, 20000);
            replacedert.True(cli.ExpireAt("TestPExpireAt_string1", DateTime.UtcNow.AddHours(1)));
            replacedert.InRange(cli.PTtl("TestPExpireAt_string1"), 1000 * 60 * 60 - 10000, 1000 * 60 * 60 + 10000);
        }

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

public void Update()
        {
            switch (State)
            {
                case ChessState.WaitingForPlayers:
                    {
                        if (StartAiTime != null && DateTime.UtcNow >= StartAiTime)
                        {
                            AddAi();
                        }
                        break;
                    }

                case ChessState.InProgress:
                    {
                        switch (AiState)
                        {
                            case ChessAiState.WaitingToStart:
                                StartAiMove();
                                break;
                            case ChessAiState.WaitingForFinish:
                                FinishAiMove();
                                break;
                        }
                        break;
                    }
            }

            // don't handle any delayed actions while ai is working to prevent races
            if (AiState != ChessAiState.None)
                return;

            // don't handle any delayed actions while weenie pieces are moving or attacking
            if (WaitingForMotion)
                return;

            while (Actions.Count > 0)
            {
                var action = Actions.Dequeue();

                switch (action.Action)
                {
                    case ChessDelayedActionType.Start:
                        Start();
                        break;
                    case ChessDelayedActionType.Move:
                        MoveDelayed(action);
                        break;
                    case ChessDelayedActionType.MovePreplaced:
                        MovePreplacedDelayed(action);
                        break;
                    case ChessDelayedActionType.Stalemate:
                        StalemateDelayed(action);
                        break;
                    case ChessDelayedActionType.Quit:
                        QuitDelayed(action.Color);
                        break;
                }
            }

            if (NextRangeCheck != null)
            {
                if (NextRangeCheck.Value <= DateTime.UtcNow)
                {
                    foreach (var side in Sides)
                    {
                        if (side == null)
                            continue;

                        if (side.IsAi())
                            continue;

                        var player = side.GetPlayer();
                        if (player == null)
                        {
                            QuitDelayed(side.Color);
                            return;
                        }

                        // arbitrary distance, should there be some warning before reaching leash range?
                        var distanceToGame = player.Location.DistanceTo(ChessBoard.Location);
                        if (distanceToGame > 40.0f)
                        {
                            QuitDelayed(side.Color);
                            return;
                        }
                    }
                    NextRangeCheck = DateTime.UtcNow.AddSeconds(5);
                }
            }
        }

See More Examples