System.DateTime.Subtract(System.DateTime)

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

1132 Examples 7

19 Source : RTCPSession.cs
with MIT License
from chatop2020

private void SendReportTimerCallback(Object stateInfo)
        {
            try
            {
                if (!IsClosed)
                {
                    lock (m_rtcpReportTimer)
                    {
                        if ((LastActivityAt != DateTime.MinValue && DateTime.Now.Subtract(LastActivityAt).TotalMilliseconds > NO_ACTIVITY_TIMEOUT_MILLISECONDS) ||
                            (LastActivityAt == DateTime.MinValue && DateTime.Now.Subtract(CreatedAt).TotalMilliseconds > NO_ACTIVITY_TIMEOUT_MILLISECONDS))
                        {
                            if (!IsTimedOut)
                            {
                                logger.LogWarning($"RTCP session for local ssrc {Ssrc} has not had any activity for over {NO_ACTIVITY_TIMEOUT_MILLISECONDS / 1000} seconds.");
                                IsTimedOut = true;

                                OnTimeout?.Invoke(MediaType);
                            }
                        }

                        //logger.LogDebug($"SendRtcpSenderReport ssrc {Ssrc}, last seqnum {LastSeqNum}, pkts {PacketsSentCount}, bytes {OctetsSentCount} ");

                        var report = GetRtcpReport();

                        OnReportReadyToSend?.Invoke(MediaType, report);

                        m_previousPacketsSentCount = PacketsSentCount;

                        var interval = GetNextRtcpInterval(RTCP_MINIMUM_REPORT_PERIOD_MILLISECONDS);
                        if (m_rtcpReportTimer == null)
                        {
                            m_rtcpReportTimer = new Timer(SendReportTimerCallback, null, interval, Timeout.Infinite);
                        }
                        else
                        {
                            m_rtcpReportTimer?.Change(interval, Timeout.Infinite);
                        }
                    }
                }
            }
            catch (ObjectDisposedException) // The RTP socket can disappear between the null check and the report send.
            {
                m_rtcpReportTimer?.Dispose();
            }
            catch (Exception excp)
            {
                // RTCP reports are not critical enough to bubble the exception up to the application.
                logger.LogError($"Exception SendReportTimerCallback. {excp.Message}");
                m_rtcpReportTimer?.Dispose();
            }
        }

19 Source : RTSPClient.cs
with MIT License
from chatop2020

private void ProcessRTPPackets()
        {
            try
            {
                Thread.CurrentThread.Name = "rtspclient-rtp";

                _lastRTPReceivedAt = DateTime.Now;
                _lastBWCalcAt = DateTime.Now;

                while (!_isClosed)
                {
                    while (_rtspSession.HasRTPPacket())
                    {
                        RTPPacket rtpPacket = _rtspSession.GetNextRTPPacket();

                        if (rtpPacket != null)
                        {
                            _lastRTPReceivedAt = DateTime.Now;
                            _bytesSinceLastBWCalc += RTPHeader.MIN_HEADER_LEN + rtpPacket.Payload.Length;

                            if (_rtpTrackingAction != null)
                            {
                                double bwCalcSeconds = DateTime.Now.Subtract(_lastBWCalcAt).TotalSeconds;
                                if (bwCalcSeconds > BANDWIDTH_CALCULATION_SECONDS)
                                {
                                    _lastBWCalc = _bytesSinceLastBWCalc * 8 / bwCalcSeconds;
                                    _lastFrameRate = _framesSinceLastCalc / bwCalcSeconds;
                                    _bytesSinceLastBWCalc = 0;
                                    _framesSinceLastCalc = 0;
                                    _lastBWCalcAt = DateTime.Now;
                                }

                                var abbrevURL = (_url.Length <= 50) ? _url : _url.Substring(0, 50);
                                string rtpTrackingText = String.Format("Url: {0}\r\nRcvd At: {1}\r\nSeq Num: {2}\r\nTS: {3}\r\nPayoad: {4}\r\nFrame Size: {5}\r\nBW: {6}\r\nFrame Rate: {7}", abbrevURL, DateTime.Now.ToString("HH:mm:ss:fff"), rtpPacket.Header.SequenceNumber, rtpPacket.Header.Timestamp, ((SDPMediaFormatsEnum)rtpPacket.Header.PayloadType).ToString(), _lastFrameSize + " bytes", _lastBWCalc.ToString("0.#") + "bps", _lastFrameRate.ToString("0.##") + "fps");
                                _rtpTrackingAction(rtpTrackingText);
                            }

                            if (rtpPacket.Header.Timestamp < _lastCompleteFrameTimestamp)
                            {
                                System.Diagnostics.Debug.WriteLine("Ignoring RTP packet with timestamp " + rtpPacket.Header.Timestamp + " as it's earlier than the last complete frame.");
                            }
                            else
                            {
                                while (_frames.Count > MAX_FRAMES_QUEUE_LENGTH)
                                {
                                    var oldestFrame = _frames.OrderBy(x => x.Timestamp).First();
                                    _frames.Remove(oldestFrame);
                                    System.Diagnostics.Debug.WriteLine("Receive queue full, dropping oldest frame with timestamp " + oldestFrame.Timestamp + ".");
                                }

                                var frame = _frames.Where(x => x.Timestamp == rtpPacket.Header.Timestamp).SingleOrDefault();

                                if (frame == null)
                                {
                                    frame = new RTPFrame() { Timestamp = rtpPacket.Header.Timestamp, HasMarker = rtpPacket.Header.MarkerBit == 1 };
                                    frame.AddRTPPacket(rtpPacket);
                                    _frames.Add(frame);
                                }
                                else
                                {
                                    frame.HasMarker = (rtpPacket.Header.MarkerBit == 1);
                                    frame.AddRTPPacket(rtpPacket);
                                }

                                if (frame.IsComplete())
                                {
                                    // The frame is ready for handing over to the UI.
                                    byte[] imageBytes = frame.GetFramePayload();

                                    _lastFrameSize = imageBytes.Length;
                                    _framesSinceLastCalc++;

                                    _lastCompleteFrameTimestamp = rtpPacket.Header.Timestamp;
                                    //System.Diagnostics.Debug.WriteLine("Frame ready " + frame.Timestamp + ", sequence numbers " + frame.StartSequenceNumber + " to " + frame.EndSequenceNumber + ",  payload length " + imageBytes.Length + ".");
                                    //logger.LogDebug("Frame ready " + frame.Timestamp + ", sequence numbers " + frame.StartSequenceNumber + " to " + frame.EndSequenceNumber + ",  payload length " + imageBytes.Length + ".");
                                    _frames.Remove(frame);

                                    // Also remove any earlier frames as we don't care about anything that's earlier than the current complete frame.
                                    foreach (var oldFrame in _frames.Where(x => x.Timestamp <= rtpPacket.Header.Timestamp).ToList())
                                    {
                                        System.Diagnostics.Debug.WriteLine("Discarding old frame for timestamp " + oldFrame.Timestamp + ".");
                                        logger.LogWarning("Discarding old frame for timestamp " + oldFrame.Timestamp + ".");
                                        _frames.Remove(oldFrame);
                                    }

                                    if (OnFrameReady != null)
                                    {
                                        try
                                        {
                                            //if (frame.FramePackets.Count == 1)
                                            //{
                                            //    // REMOVE.
                                            //    logger.LogWarning("Discarding frame as there should have been more than 1 RTP packets.");
                                            //}
                                            //else
                                            //{
                                            //System.Diagnostics.Debug.WriteLine("RTP frame ready for timestamp " + frame.Timestamp + ".");
                                            OnFrameReady(this, frame);
                                            //}
                                        }
                                        catch (Exception frameReadyExcp)
                                        {
                                            logger.LogError("Exception RTSPClient.ProcessRTPPackets OnFrameReady. " + frameReadyExcp);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (DateTime.Now.Subtract(_lastRTPReceivedAt).TotalSeconds > RTP_TIMEOUT_SECONDS)
                    {
                        logger.LogWarning("No RTP packets were received on RTSP session " + _rtspSession.SessionID + " for " + RTP_TIMEOUT_SECONDS + ". The session will now be closed.");
                        Close();
                    }
                    else
                    {
                        Thread.Sleep(1);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception RTSPClient.ProcessRTPPackets. " + excp);
            }
        }

19 Source : SctpTransport.cs
with MIT License
from chatop2020

protected SctpTransportCookie GetCookie(SctpPacket sctpPacket)
        {
            var cookieEcho = sctpPacket.Chunks.Single(x => x.KnownType == SctpChunkType.COOKIE_ECHO);
            var cookieBuffer = cookieEcho.ChunkValue;
            var cookie = JSONParser.FromJson<SctpTransportCookie>(Encoding.UTF8.GetString(cookieBuffer));

            logger.LogDebug($"Cookie: {cookie.ToJson()}");

            string calculatedHMAC = GetCookieHMAC(cookieBuffer);
            if (calculatedHMAC != cookie.HMAC)
            {
                logger.LogWarning($"SCTP COOKIE ECHO chunk had an invalid HMAC, calculated {calculatedHMAC}, cookie {cookie.HMAC}.");
                SendError(
                  true,
                  sctpPacket.Header.DestinationPort,
                  sctpPacket.Header.SourcePort,
                  0,
                  new SctpCauseOnlyError(SctpErrorCauseCode.InvalidMandatoryParameter));
                return SctpTransportCookie.Empty;
            }
            else if (DateTime.Now.Subtract(DateTime.Parse(cookie.CreatedAt)).TotalSeconds > cookie.Lifetime)
            {
                logger.LogWarning($"SCTP COOKIE ECHO chunk was stale, created at {cookie.CreatedAt}, now {DateTime.Now.ToString("o")}, lifetime {cookie.Lifetime}s.");
                var diff = DateTime.Now.Subtract(DateTime.Parse(cookie.CreatedAt).AddSeconds(cookie.Lifetime));
                SendError(
                  true,
                  sctpPacket.Header.DestinationPort,
                  sctpPacket.Header.SourcePort,
                  0,
                  new SctpErrorStaleCookieError { MeasureOfStaleness = (uint)(diff.TotalMilliseconds * 1000) });
                return SctpTransportCookie.Empty;
            }
            else
            {
                return cookie;
            }
        }

19 Source : SIPCDR.cs
with MIT License
from chatop2020

public int GetProgressDuration()
        {
            return (ProgressTime != null && AnswerTime != null) ? Convert.ToInt32(AnswerTime.Value.Subtract(ProgressTime.Value).TotalSeconds) : 0;
        }

19 Source : SIPCDR.cs
with MIT License
from chatop2020

public int GetAnsweredDuration()
        {
            return (AnswerTime != null && HangupTime != null) ? Convert.ToInt32(HangupTime.Value.Subtract(AnswerTime.Value).TotalSeconds) : 0;
        }

19 Source : NetServices.cs
with MIT License
from chatop2020

public static IPAddress GetLocalAddressForRemote(IPAddress destination)
        {
            if (destination == null || IPAddress.Any.Equals(destination) || IPAddress.IPv6Any.Equals(destination))
            {
                return null;
            }

            if (m_localAddressTable.TryGetValue(destination, out var cachedAddress))
            {
                if (DateTime.Now.Subtract(cachedAddress.Item2).TotalSeconds >= LOCAL_ADDRESS_CACHE_LIFETIME_SECONDS)
                {
                    m_localAddressTable.TryRemove(destination, out _);
                }

                return cachedAddress.Item1;
            }
            else
            {
                IPAddress localAddress = null;

                if (destination.AddressFamily == AddressFamily.InterNetwork || destination.IsIPv4MappedToIPv6)
                {
                    using (UdpClient udpClient = new UdpClient())
                    {
                        try
                        {
                            udpClient.Connect(destination.MapToIPv4(), NETWORK_TEST_PORT);
                            localAddress = (udpClient.Client.LocalEndPoint as IPEndPoint)?.Address;
                        }
                        catch (SocketException)
                        {
                            // Socket exception is thrown if the OS cannot find a suitable entry in the routing table.
                        }
                    }
                }
                else
                {
                    using (UdpClient udpClient = new UdpClient(AddressFamily.InterNetworkV6))
                    {
                        try
                        {
                            udpClient.Connect(destination, NETWORK_TEST_PORT);
                            localAddress = (udpClient.Client.LocalEndPoint as IPEndPoint)?.Address;
                        }
                        catch (SocketException)
                        {
                            // Socket exception is thrown if the OS cannot find a suitable entry in the routing table.
                        }
                    }

                }

                if (localAddress != null)
                {
                    m_localAddressTable.TryAdd(destination, new Tuple<IPAddress, DateTime>(localAddress, DateTime.Now));
                }

                return localAddress;
            }
        }

19 Source : Functions.cs
with GNU General Public License v2.0
from CheepYT

public static int GetUnixTime()
        {
            return (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        }

19 Source : BasicDataConversion.cs
with MIT License
from chinabeacon

public static long ConvertDataTimeLong(this DateTime dt)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            TimeSpan toNow = dt.Subtract(dtStart);
            long timeStamp = toNow.Ticks;
            timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
            timeStamp = timeStamp > 0 ? timeStamp : 0;
            return timeStamp;
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from CHKZL

public void 设置全屏()
        {
            TimeSpan ts = DateTime.UtcNow.Subtract(全屏操作的时间);
            if(ts.TotalMilliseconds>500)
            {
                全屏操作的时间 = DateTime.UtcNow;
            }
            else
            {
                return;
            }
            
            if (this.WindowState == WindowState.Normal)
            {
                this.WindowState = WindowState.Maximized;
            }
            else if (this.WindowState == WindowState.Maximized)
            {
                this.WindowState = WindowState.Normal;
            }
            if (字幕.字幕位置 != (int)this.Width / 100 * (int)字幕位置.Value)
            {
                字幕.字幕位置 = (int)this.Width / 100 * (int)字幕位置.Value;
                if (字幕.FontSize > 50)
                {
                    字幕.FontSize = 1;
                }
                else
                {
                    字幕.FontSize++;
                }
            }
        }

19 Source : MainFrame.cs
with MIT License
from chrisnas

private void _listener_Changed(object sender, ClipboardChangedEventArgs e)
    {
        // Note: in WinDBG, the same content is copied to the clipboard TWICE.
        //       so we need to skip the notifications that occurs too close from
        //       the previous one.
        var now = DateTime.UtcNow;
        if (now.Subtract(_lastClipboardNotificationTime) < MIN_ELAPSE_SINCE_CLIPBOARD_NOTIFICATION)
        {
            return;
        }
        _lastClipboardNotificationTime = now;

        // TODO: make this "maybe long" treatment asynchronous if needed
        //
        // Check if this is a supported format
        HeapSnapshot snapshot = GetSnapshotFromClipboard();
        if (snapshot == null)
        {
            return;
        }

        AddOneSnapshot(snapshot);
    }

19 Source : User.cs
with MIT License
from chucklenugget

public int GetSecondsLeftOnCooldown(string command)
      {
        DateTime expiration;

        if (!CommandCooldownExpirations.TryGetValue(command, out expiration))
          return 0;

        return (int)Math.Max(0, expiration.Subtract(DateTime.UtcNow).TotalSeconds);
      }

19 Source : ZoneManager.cs
with MIT License
from chucklenugget

void Create(ZoneType type, string name, MonoBehaviour owner, float radius, DateTime? endTime = null)
      {
        var zone = new GameObject().AddComponent<Zone>();
        zone.Init(type, name, owner, radius, Instance.Options.Zones.DomeDarkness, endTime);

        Instance.Puts($"Created zone {zone.Name} at {zone.transform.position} with radius {radius}");

        if (endTime != null)
          Instance.Puts($"Zone {zone.Name} will be destroyed at {endTime} ({endTime.Value.Subtract(DateTime.UtcNow).ToShortString()} from now)");

        Zones.Add(owner, zone);
      }

19 Source : LoggingBootstrapperExtender.cs
with Apache License 2.0
from Cimpress-MCP

public void OnAfterRequest(NancyContext context, IDictionary<string, object> logData)
        {
            var request = context.Request;
            var response = context.Response;

            if (context.Items.ContainsKey(NancyServiceBootstrapper.StartTimeString))
            {
                var startTime = (DateTime)context.Items[NancyServiceBootstrapper.StartTimeString];
                var endTime = DateTime.UtcNow;
                logData[NancyServiceBootstrapper.StartTimeString] = startTime;
                logData[NancyServiceBootstrapper.EndTimeString] = endTime;
                logData["CallDuration"] = (int)endTime.Subtract(startTime).TotalMilliseconds;
            }

            var correlationId = string.Empty;
            if (context.Items.ContainsKey(CorrelationIdString))
            {
                correlationId = (string) context.Items[CorrelationIdString];
            }
            
            var stream = new MemoryStream();
            response.Contents(stream);
            stream.Position = 0;
            var responseBody = new StreamReader(stream).ReadToEnd();
            var responseIsJson = response.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(responseBody);
            var bodyObject = responseIsJson ? JsonConvert.DeserializeObject(responseBody) : responseBody;

            //If the body is too large, just log the first x characters (and don't return the JSON object if applicable) 
            if(_loggedBodySizeLimit > -1 && responseBody.Length > _loggedBodySizeLimit)
            {
                bodyObject = responseBody.Substring(0, _loggedBodySizeLimit);
            }

            logData["Response"] = new Dictionary<string, object>
            {
                { "Body", bodyObject },
                { "StatusCode", response.StatusCode },
                { "Reason", response.ReasonPhrase },
            };

            _logger.Info(new BaseMessage
            {
                Message = request.Path,
                CorrelationId = correlationId,
                Info = logData
            });

            context.Response.Headers.Add("CorrelationId", correlationId);
        }

19 Source : LoggingBootstrapperExtender.cs
with Apache License 2.0
from Cimpress-MCP

public void OnError(NancyContext context, Exception ex, Response newResponse, IDictionary<string, object> logData)
        {
            if (context.Items.ContainsKey(NancyServiceBootstrapper.StartTimeString))
            {
                var startTime = (DateTime)context.Items[NancyServiceBootstrapper.StartTimeString];
                var endTime = DateTime.UtcNow;
                logData[NancyServiceBootstrapper.StartTimeString] = startTime;
                logData[NancyServiceBootstrapper.EndTimeString] = endTime;
                logData["CallDuration"] = (int)endTime.Subtract(startTime).TotalMilliseconds;
            }

            var correlationId = string.Empty;
            if (context.Items.ContainsKey(CorrelationIdString))
            {
                correlationId = (string) context.Items[CorrelationIdString];
            }

            logData["Host"] = Environment.MachineName;
            logData["StackTrace"] = ex.ToString();

            _logger.Error(new BaseMessage
            {
                Message = context.Request.Path,
                CorrelationId = correlationId,
                Info = logData
            });

            newResponse.Headers.Add("CorrelationId", correlationId);
        }

19 Source : QueryTranslator.cs
with MIT License
from circles-arrows

internal virtual bool ShouldRefreshFunctionalIds()
        {
            string query = "MATCH (version:RefactorVersion) RETURN version.LastRun as LastRun";
            var result = Transaction.RunningTransaction.Run(query);

            RawRecord record = result.FirstOrDefault();
            if (record is null)
                return true;

            DateTime? lastRun = Conversion<long?, DateTime?>.Convert(record["LastRun"].As<long?>());
            if (lastRun is null)
                return true;

            if (DateTime.UtcNow.Subtract(lastRun.Value).TotalHours >= 12)
                return true;

            return false;
        }

19 Source : Conversion.cs
with MIT License
from circles-arrows

private protected static long ToTimeInMS(DateTime value)
        {
            //if date is not utc convert to utc.
            DateTime utcTime = value.Kind != DateTimeKind.Utc ? value.ToUniversalTime() : value;

            //return value.Ticks;
            DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return (long)utcTime.Subtract(dt).TotalMilliseconds;
        }

19 Source : Program.cs
with Apache License 2.0
from Cinegy

private static void PrintConsoleFeedback()
        {
            var runningTime = DateTime.UtcNow.Subtract(StartTime);

            Console.SetCursorPosition(0, 0);

            if ((_options as StreamOptions) != null)
            {
                PrintToConsole("URL: {0}://{1}:{2}\tRunning time: {3:hh\\:mm\\:ss}\t\t",
                    ((StreamOptions)_options).NoRtpHeaders ? "udp" : "rtp",
                    $"@{((StreamOptions)_options).AdapterAddress}",
                    ((StreamOptions)_options).SrtPort, runningTime);

                var networkMetric = _replacedyser.NetworkMetric;
                var rtpMetric = _replacedyser.RtpMetric;

                PrintToConsole(
                    "\nNetwork Details\n----------------\nTotal Packets Rcvd: {0} \tBuffer Usage: {1:0.00}%/(Peak: {2:0.00}%)\t\t\nTotal Data (MB): {3}\t\tPackets per sec:{4}\t",
                    networkMetric.TotalPackets, networkMetric.NetworkBufferUsage, networkMetric.PeriodMaxNetworkBufferUsage,
                    networkMetric.TotalData / 1048576,
                    networkMetric.PacketsPerSecond);

                PrintToConsole("Period Max Packet Jitter (ms): {0}\t\t",
                    networkMetric.PeriodLongestTimeBetweenPackets);

                PrintToConsole(
                    "Bitrates (Mbps): {0:0.00}/{1:0.00}/{2:0.00}/{3:0.00} (Current/Avg/Peak/Low)\t\t\t",
                    (networkMetric.CurrentBitrate / 1048576.0), networkMetric.AverageBitrate / 1048576.0,
                    (networkMetric.HighestBitrate / 1048576.0), (networkMetric.LowestBitrate / 1048576.0));

                if (!((StreamOptions)_options).NoRtpHeaders)
                {
                    PrintToConsole(
                        "\nRTP Details\n----------------\nSeq Num: {0}\tMin Lost Pkts: {1}\nTimestamp: {2}\tSSRC: {3}\t",
                        rtpMetric.LastSequenceNumber, rtpMetric.EstimatedLostPackets, rtpMetric.LastTimestamp,
                        rtpMetric.Ssrc);
                }
            }

            var pidMetrics = _replacedyser.PidMetrics;

            lock (pidMetrics)
            {

                var span = new TimeSpan((long)(_replacedyser.LastPcr / 2.7));
                PrintToConsole(_replacedyser.LastPcr > 0 ? $"\nPCR Value: {span}\n----------------" : "\n\n");

                PrintToConsole(pidMetrics.Count < 10
                    ? $"\nPID Details - Unique PIDs: {pidMetrics.Count}\n----------------"
                    : $"\nPID Details - Unique PIDs: {pidMetrics.Count}, (10 shown by packet count)\n----------------");

                foreach (var pidMetric in pidMetrics.OrderByDescending(m => m.PacketCount).Take(10))
                {
                    PrintToConsole("TS PID: {0}\tPacket Count: {1} \t\tCC Error Count: {2}\t", pidMetric.Pid,
                        pidMetric.PacketCount, pidMetric.CcErrorCount);
                }
            }

            var tsDecoder = _replacedyser.TsDecoder;

            if (tsDecoder != null)
            {
                lock (tsDecoder)
                {
                    var pmts = tsDecoder.ProgramMapTables.OrderBy(p => p.ProgramNumber).ToList();

                    PrintToConsole(pmts.Count < 5
                        ? $"\t\t\t\nService Information - Service Count: {pmts.Count}\n----------------\t\t\t\t"
                        : $"\t\t\t\nService Information - Service Count: {pmts.Count}, (5 shown)\n----------------\t\t\t\t");

                    foreach (var pmtable in pmts.Take(5))
                    {
                        var desc = tsDecoder.GetServiceDescriptorForProgramNumber(pmtable?.ProgramNumber);
                        if (desc != null)
                        {
                            PrintToConsole(
                                $"Service {pmtable?.ProgramNumber}: {desc.ServiceName.Value} ({desc.ServiceProviderName.Value}) - {desc.ServiceTypeDescription}\t\t\t"
                                );
                        }
                    }

                    var pmt = tsDecoder.GetSelectedPmt(_options.ProgramNumber);
                    if (pmt != null)
                    {
                        _options.ProgramNumber = pmt.ProgramNumber;
                        _replacedyser.SelectedPcrPid = pmt.PcrPid;
                    }

                    var serviceDesc = tsDecoder.GetServiceDescriptorForProgramNumber(pmt?.ProgramNumber);

                    PrintToConsole(serviceDesc != null
                        ? $"\t\t\t\nElements - Selected Program: {serviceDesc.ServiceName} (ID:{pmt?.ProgramNumber}) (first 5 shown)\n----------------\t\t\t\t"
                        : $"\t\t\t\nElements - Selected Program Service ID {pmt?.ProgramNumber} (first 5 shown)\n----------------\t\t\t\t");

                    if (pmt?.EsStreams != null)
                    {
                        foreach (var stream in pmt.EsStreams.Take(5))
                        {
                            if (stream == null) continue;
                            if (stream.StreamType != 6)
                            {
                                PrintToConsole(
                                    "PID: {0} ({1})", stream.ElementaryPid,
                                    DescriptorDictionaries.ShortElementaryStreamTypeDescriptions[
                                        stream.StreamType]);
                            }
                            else
                            {
                                if (stream.Descriptors.OfType<Ac3Descriptor>().Any())
                                {
                                    PrintToConsole("PID: {0} ({1})", stream.ElementaryPid, "AC-3 / Dolby Digital");
                                    continue;
                                }
                                if (stream.Descriptors.OfType<Eac3Descriptor>().Any())
                                {
                                    PrintToConsole("PID: {0} ({1})", stream.ElementaryPid, "EAC-3 / Dolby Digital Plus");
                                    continue;
                                }
                                if (stream.Descriptors.OfType<SubreplacedlingDescriptor>().Any())
                                {
                                    PrintToConsole("PID: {0} ({1})", stream.ElementaryPid, "DVB Subreplacedles");
                                    continue;
                                }
                                if (stream.Descriptors.OfType<TeletextDescriptor>().Any())
                                {
                                    PrintToConsole("PID: {0} ({1})", stream.ElementaryPid, "Teletext");
                                    continue;
                                }
                                if (stream.Descriptors.OfType<RegistrationDescriptor>().Any())
                                {
                                    if (stream.Descriptors.OfType<RegistrationDescriptor>().First().Organization == "2LND")
                                    {
                                        PrintToConsole("PID: {0} ({1})", stream.ElementaryPid, "Cinegy DANIEL2");
                                        continue;
                                    }
                                }

                                PrintToConsole(
                                    "PID: {0} ({1})", stream.ElementaryPid,
                                    DescriptorDictionaries.ShortElementaryStreamTypeDescriptions[
                                        stream.StreamType]);

                            }

                        }
                    }
                }

                if (_options.DecodeTeletext)
                {
                    PrintTeletext();
                }
            }

            if (_lastPrintedTsCount != pidMetrics.Count)
            {
                _lastPrintedTsCount = pidMetrics.Count;
                Console.Clear();
            }

            var result = ConsoleDisplay.ToString();

            Console.WriteLine(result);
            ConsoleDisplay.Clear();

        }

19 Source : TimeInputType.cs
with GNU General Public License v3.0
from CircuitLord

public override Double? ConvertToNumber(String value)
        {
            var dt = ConvertFromTime(value);

            if (dt.HasValue)
            {
                return dt.Value.Subtract(new DateTime()).TotalMilliseconds;
            }

            return null;
        }

19 Source : TimeInputType.cs
with GNU General Public License v3.0
from CircuitLord

public override DateTime? ConvertToDate(String value)
        {
            var time = ConvertFromTime(value);

            if (time != null)
            {
                return UnixEpoch.Add(time.Value.Subtract(new DateTime()));
            }

            return null;
        }

19 Source : ThreadingExtension.cs
with MIT License
from CitiesSkylinesMultiplayer

public override void OnAfterSimulationTick()
        {
            // Send economy and frame drop packets every two seconds
            if (DateTime.Now.Subtract(_lastEconomyAndDropSync).TotalSeconds > 2)
            {
                // Only send economy and dropped frames when connected
                // (loading may acreplacedulate dropped frames we need to ignore)
                if (MultiplayerManager.Instance.IsConnected())
                {
                    ResourceCommandHandler.Send();
                    SlowdownHelper.SendDroppedFrames();
                }
                _lastEconomyAndDropSync = DateTime.Now;
            }

            // Finish transactions
            TransactionHandler.FinishSend();
        }

19 Source : UtRedisDbBinaryRepository.cs
with MIT License
from CityOfZion

[TestMethod]
        public async Task AddBlockHeader_ValidBlockHeader_BlockHeaderAndHeightHashSaved()
        {
            // Arrange
            var expectedBlockByteArray = new byte[]
            {
                157, 179, 60, 8, 66, 122, 255, 105, 126, 49, 180, 74, 212, 41, 126, 177, 14, 255, 59, 82, 218, 113, 248,
                145, 98, 5, 128, 140, 42, 70, 32, 69, 0
            };
            var hash = UInt256.Parse("0x4520462a8c80056291f871da523bff0eb17e29d44ab4317e69ff7a42083cb39d");

            const uint index = 0;

            var timestamp = (uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            var blockHeaderParameter = new BlockHeader
            {
                Hash = hash,
                Index = index
                    
            };

            blockHeaderParameter.Timestamp = timestamp;

            _serializerMock
                .Setup(x => x.Serialize(blockHeaderParameter, null))
                .Returns(expectedBlockByteArray);

            var redisDbContextMock = AutoMockContainer.GetMock<IRedisDbContext>();
            var testee = AutoMockContainer.Create<RedisDbBinaryRepository>();

            // Act
            await testee.AddBlockHeader(blockHeaderParameter);

            // replacedert
            redisDbContextMock.Verify(x => x.Set(
                    It.IsAny<RedisKey>(),
                    It.IsAny<RedisValue>()),
                Times.Once);
            
            redisDbContextMock.Verify(x => x.AddToIndex(
                    It.Is<RedisIndex>(a => a == RedisIndex.BlockTimestamp),
                    It.Is<UInt256>(a => a == blockHeaderParameter.Hash),
                    It.Is<double>(a => a == blockHeaderParameter.Timestamp)),
                Times.Once);

            redisDbContextMock.Verify(x => x.AddToIndex(
                    It.Is<RedisIndex>(a => a == RedisIndex.BlockHeight),
                    It.Is<UInt256>(a => a == blockHeaderParameter.Hash),
                    It.Is<double>(a => a == blockHeaderParameter.Index)),
                Times.Once);
        }

19 Source : UtRedisDbJsonRepository.cs
with MIT License
from CityOfZion

[TestMethod]
        public async Task AddBlockHeader_ValidBlockHeader_BlockHeaderAndHeightHashSaved()
        {
            // Arrange
            var hash = UInt256.Parse("0x4520462a8c80056291f871da523bff0eb17e29d44ab4317e69ff7a42083cb39d");

            const uint index = 0;

            var timestamp = (uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            var blockHeaderParameter = new BlockHeader
            {
                Hash = hash,
                Index = index,
                Timestamp = timestamp
            };


            var expectedblockJson = $"{{\"Hash\":{hash},\"Index\":{index}}}";
            var jsonConverterMock = AutoMockContainer.GetMock<IJsonConverter>();

            jsonConverterMock
                .Setup(x => x.SerializeObject(blockHeaderParameter))
                .Returns(expectedblockJson);

            var redisDbContextMock = AutoMockContainer.GetMock<IRedisDbJsonContext>();
            var testee = AutoMockContainer.Create<RedisDbJsonRepository>();

            // Act
            await testee.AddBlockHeader(blockHeaderParameter);

            // replacedert
            redisDbContextMock.Verify(x => x.Set(
                    It.IsAny<RedisKey>(),
                    It.IsAny<RedisValue>()),
                Times.Once);

            redisDbContextMock.Verify(x => x.AddToIndex(
                    It.Is<RedisIndex>(a => a == RedisIndex.BlockTimestamp),
                    It.Is<UInt256>(a => a == blockHeaderParameter.Hash),
                    It.Is<double>(a => a == blockHeaderParameter.Timestamp)),
                Times.Once);

            redisDbContextMock.Verify(x => x.AddToIndex(
                    It.Is<RedisIndex>(a => a == RedisIndex.BlockHeight),
                    It.Is<UInt256>(a => a == blockHeaderParameter.Hash),
                    It.Is<double>(a => a == blockHeaderParameter.Index)),
                Times.Once);
        }

19 Source : XlsxTemplateTestsBase.cs
with MIT License
from ClosedXML

protected void XlTemplateTest(string tmplFileName, Action<XLTemplate> arrangeCallback, Action<XLWorkbook> replacedertCallback)
        {
            /*if (MemoryProfiler.IsActive && MemoryProfiler.CanControlAllocations)
                MemoryProfiler.EnableAllocations();*/

            //MemoryProfiler.Dump();

            var fileName = Path.Combine(TestConstants.TemplatesFolder, tmplFileName);
            using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var template = new XLTemplate(stream))
            {
                // ARRANGE
                arrangeCallback(template);

                using (var file = new MemoryStream())
                {
                    //MemoryProfiler.Dump();
                    // ACT
                    var start = DateTime.Now;
                    template.Generate();
                    Output.WriteLine(DateTime.Now.Subtract(start).ToString());
                    //MemoryProfiler.Dump();
                    template.SaveAs(file);
                    //MemoryProfiler.Dump();
                    file.Position = 0;

                    using (var wb = new XLWorkbook(file))
                    {
                        // replacedERT
                        replacedertCallback(wb);
                    }
                }
            }

            GC.Collect();
            //MemoryProfiler.Dump();
        }

19 Source : DelayDispatcher.cs
with MIT License
from CloudNimble

public void Throttle(int interval, Action<object> action, object param = null)
        {
            // kill pending timer and pending ticks
            timer?.Stop();
            timer = null;

            var dispatcher = Dispatcher.CreateDefault();

            var curTime = DateTime.UtcNow;

            // if timeout is not up yet - adjust timeout to fire 
            // with potentially new Action parameters           
            if (curTime.Subtract(TimerStarted).TotalMilliseconds < interval)
                interval -= (int)curTime.Subtract(TimerStarted).TotalMilliseconds;

            timer = new Timer(interval);
            timer.Elapsed += (s, e) =>
            {
                if (timer == null)
                    return;

                timer?.Stop();
                timer = null;
                dispatcher.InvokeAsync(() => action.Invoke(param));
            };

            timer.Start();
            TimerStarted = curTime;
        }

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

public override int Read(byte[] buffer, int offset, int count)
        {
            int origCount = count;

            while (count > 0)
            {
                if (currentEntryLength > 0 && currentEntryPosition >= currentEntryLength) // Next entry
                {
                    currentEntry++;
                    currentEntryPosition = 0;
                }

                if (currentEntry >= entries.Count) // end of archive, write zeros
                {
                    if (currentFile != null)
                    {
                        currentFile.Dispose();
                        currentFile = null;
                    }
                    long l = Math.Min(count, totalSize - position);
                    var dummy = new byte[l];
                    Array.Copy(dummy, 0, buffer, offset, l);
                    count -= (int)l;
                    position += l;
                    currentEntryPosition += l;
                    offset += (int)l;
                    break;
                }

                if (currentEntryPosition == 0) // New entry
                {
                    currentEntryLength = 512;
                    var header = new TarHeader();
                    if (entries[currentEntry] != LongLinkFlag)
                        header.FileName = entries[currentEntry].Substring(rootDirectory.Length + 1).Replace(@"\", "/");
                    if (currentFile != null)
                    {
                        currentFile.Dispose();
                        currentFile = null;
                    }
                    if (entries[currentEntry] == LongLinkFlag)
                    {
                        header.FileName = entries[currentEntry];
                        header.FileMode = "0000000";
                        var name = entries[currentEntry+1].Substring(rootDirectory.Length + 1).Replace(@"\", "/");
                        var nameBuff = Encoding.UTF8.GetBytes(name);
                        currentFile = new MemoryStream(nameBuff.Length + 1);
                        currentFile.Write(nameBuff, 0, nameBuff.Length);
                        currentFile.WriteByte(0);
                        currentFile.Seek(0, SeekOrigin.Begin);
                        currentEntryLength += currentFile.Length;
                        if (currentFile.Length % 512 != 0)
                            currentEntryLength += 512 - (currentFile.Length % 512);
                        header.FileSize = Convert.ToString(currentFile.Length, 8).PadLeft(11, '0');
                        header.LastModificationTime = "0".PadLeft(11, '0');
                        header.FileType = 'L';

                    }
                    else if (!header.FileName.EndsWith("/")) // It's a file!
                    {
                        currentFile = new FileStream(entries[currentEntry], FileMode.Open);
                        header.FileMode = "0100644";
                        currentEntryLength += currentFile.Length;
                        if (currentFile.Length % 512 != 0)
                            currentEntryLength += 512 - (currentFile.Length % 512);
                        header.FileSize = Convert.ToString(currentFile.Length, 8).PadLeft(11, '0');
                        header.LastModificationTime = Convert.ToString(
                            (long)new FileInfo(entries[currentEntry]).LastWriteTimeUtc.Subtract(new DateTime(1970, 1, 1)).TotalSeconds
                            , 8).PadLeft(11, '0');
                        header.FileType = '0';
                    }
                    else if (header.FileName.EndsWith("/")) // It's a directory...
                    {
                        header.FileMode = "0040755";
                        header.FileSize = "".PadLeft(11, '0');
                        header.LastModificationTime = Convert.ToString(
                            (long)new DirectoryInfo(entries[currentEntry]).LastWriteTimeUtc.Subtract(new DateTime(1970, 1, 1)).TotalSeconds
                            , 8).PadLeft(11, '0');
                        header.FileType = '5';
                    }
                    header.OwnerID = "0000000";
                    header.GroupID = "0000000";
                    header.UstarMagic = "ustar  ";
                    //header.UstarVersion = new char[] {'0', '0'};
                    header.CalcChecksum();
                    currentHeader = header.GetBytes();
                }

                if (currentEntryPosition < 512) // Header
                {
                    long l = Math.Min(count, 512 - currentEntryPosition);
                    Array.Copy(currentHeader, currentEntryPosition, buffer, offset, l);
                    count -= (int)l;
                    position += l;
                    currentEntryPosition += l;
                    offset += (int)l;
                }
                else // Data
                {
                    long l = Math.Min(count, currentEntryLength - currentEntryPosition);
                    currentFile.Read(buffer, offset, (int)l);
                    count -= (int)l;
                    position += l;
                    currentEntryPosition += l;
                    offset += (int)l;
                }
            }
            OnReadProgress(Position, Length);
            return origCount - count;
        }

19 Source : ConfuserLogger.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public void Finish(bool successful)
        {
            DateTime now = DateTime.Now;
            string timeString = string.Format(
                "at {0}, {1}:{2:d2} elapsed.",
                now.ToShortTimeString(),
                (int)now.Subtract(begin).TotalMinutes,
                now.Subtract(begin).Seconds);
            if (successful)
            {
                Console.replacedle = "ConfuserEx - Success";
                WriteLineWithColor(ConsoleColor.Green, "Finished " + timeString);
                ReturnValue = 0;
            }
            else
            {
                Console.replacedle = "ConfuserEx - Fail";
                WriteLineWithColor(ConsoleColor.Red, "Failed " + timeString);
                ReturnValue = 1;
            }
        }

19 Source : AnimationComponent.cs
with Apache License 2.0
from codaris

private void Events_RobotState(object sender, Events.RobotStateEventArgs e)
        {
            // If we aren't waiting for a result, return
            if (animationRunningResult == null) return;

            // If we aren't animating and 250 milliseconds has past then set the result.
            var diff = DateTime.Now.Subtract(lastAnimationStart).TotalMilliseconds;
            if (!e.Status.IsAnimating && diff > 250)
            {
                animationRunningResult.TrySetResult(true);
                animationRunningResult = null;
                OnPropertyChanged(nameof(IsAnimating));
            }
        }

19 Source : AudioComponent.cs
with Apache License 2.0
from codaris

public async Task<PlaybackResult> PlayStream(Stream stream, uint frameRate, uint volume = 50)
        {
            if (stream == null) throw new ArgumentNullException(nameof(stream));
            if (frameRate < 8000 || frameRate > 16025) throw new ArgumentOutOfRangeException(nameof(frameRate), "The frameRate must be between 8000 and 16025");
            if (volume > 100) throw new ArgumentOutOfRangeException(nameof(volume), "Volume must be between 0 and 100");

            playbackResult?.TrySetCanceled();
            playbackResult = new TaskCompletionSource<PlaybackResult>();

            // Send preparation message
            await playbackFeed.Call(new ExternalAudioStreamRequest()
            {
                AudioStreamPrepare = new ExternalAudioStreamPrepare()
                {
                    AudioFrameRate = frameRate,
                    AudioVolume = volume
                }
            }).ConfigureAwait(false);

            var startTime = DateTime.Now;
            int dataCount = 0;

            var chunkBuffer = new byte[MaxRobotAudioChunkSize];
            while (playbackFeed.IsActive)
            {
                int chunkSize = await stream.ReadAsync(chunkBuffer, 0, MaxRobotAudioChunkSize).ConfigureAwait(false);
                if (chunkSize == 0) break;
                dataCount += chunkSize;

                await playbackFeed.Call(new ExternalAudioStreamRequest()
                {
                    AudioStreamChunk = new ExternalAudioStreamChunk()
                    {
                        AudioChunkSizeBytes = (uint)chunkSize,
                        AudioChunkSamples = Google.Protobuf.ByteString.CopyFrom(chunkBuffer, 0, chunkSize)
                    }
                }).ConfigureAwait(false);
                if (chunkSize != MaxRobotAudioChunkSize) break;

                var elapsed = DateTime.Now.Subtract(startTime).TotalSeconds;
                var expectedDataCount = elapsed * frameRate * 2;
                var timeAhead = (dataCount - expectedDataCount) / frameRate;
                if (timeAhead > 1.0)
                {
                    await Task.Delay((int)((timeAhead - 0.5) * 1000)).ConfigureAwait(false);
                }
            }

            if (playbackFeed.IsActive)
            {
                await playbackFeed.Call(new ExternalAudioStreamRequest()
                {
                    AudioStreamComplete = new ExternalAudioStreamComplete()
                }).ConfigureAwait(false);
            }

            return await playbackResult.Task.ConfigureAwait(false);
        }

19 Source : FaceIndexerAddIn.cs
with MIT License
from codestackdev

public int IndexFaces(IreplacedemblyDoc replacedm)
        {
            var count = 0;

            var start = DateTime.Now;
            {
                var comps = replacedm.GetComponents(false) as object[];

                if (comps != null)
                {
                    foreach (IComponent2 comp in comps)
                    {
                        object bodyInfo;
                        var bodies = comp.GetBodies3((int)swBodyType_e.swAllBodies, out bodyInfo) as object[];

                        if (bodies != null)
                        {
                            foreach (IBody2 body in bodies)
                            {
                                var faces = body.GetFaces() as object[];

                                if (faces != null)
                                {
                                    foreach (IFace2 face in faces)
                                    {
                                        var surf = face.IGetSurface();
                                        var type = (swSurfaceTypes_e)surf.Idenreplacedy();
                                        count++;

                                        Trace.WriteLine($"Area: {face.GetArea()}. Type: {type}");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            App.SendMsgToUser($"{count} face(s) of {(replacedm as IModelDoc2).Getreplacedle()} indexed in {DateTime.Now.Subtract(start).TotalSeconds} seconds");

            return count;
        }

19 Source : DebounceDispatcher.cs
with MIT License
from coldino

public void Throttle(int interval, Action<object> action,
            object param = null,
            DispatcherPriority priority = DispatcherPriority.ApplicationIdle,
            Dispatcher disp = null)
        {
            // kill pending timer and pending ticks
            timer?.Stop();
            timer = null;

            if (disp == null)
                disp = Dispatcher.CurrentDispatcher;

            var curTime = DateTime.UtcNow;

            // if timeout is not up yet - adjust timeout to fire 
            // with potentially new Action parameters           
            if (curTime.Subtract(timerStarted).TotalMilliseconds < interval)
                interval -= (int)curTime.Subtract(timerStarted).TotalMilliseconds;

            timer = new DispatcherTimer(TimeSpan.FromMilliseconds(interval), priority, (s, e) => {
                if (timer == null)
                    return;

                timer?.Stop();
                timer = null;
                action.Invoke(param);
            }, disp);

            timer.Start();
            timerStarted = curTime;
        }

19 Source : main.cs
with GNU General Public License v3.0
from CommentViewerCollection

public static long ToUnixTime(DateTime dateTime)
        {
            // 時刻をUTCに変換
            dateTime = dateTime.ToUniversalTime();

            // unix epochからの経過秒数を求める
            return (long)dateTime.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
        }

19 Source : UnixTimeConverter.cs
with GNU General Public License v3.0
from CommentViewerCollection

public static long ToUnixTime(DateTime dateTime)
        {
            // 時刻をUTCに変換
            dateTime = dateTime.ToUniversalTime();

            // unix epochからの経過秒数を求める
            return (long)dateTime.Subtract(baseTime).TotalSeconds;
        }

19 Source : CommentProvider.cs
with GNU General Public License v3.0
from CommentViewerCollection

private void _PoipoiStockTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            var unixTimestampNow = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            List<string> processedKeys = new List<string>();
            lock (_poipoiStockDict)
            {
                foreach (KeyValuePair<string, Packet> _poipoiStock in _poipoiStockDict)
                {
                    if (_poipoiStock.Value.Created + _siteOptions.PoipoiKeepSeconds <= unixTimestampNow)
                    {
                        var messageContext = CreateMessageContext(_poipoiStock.Value, false);
                        if (messageContext != null)
                        {
                            MessageReceived?.Invoke(this, messageContext);
                        }
                        processedKeys.Add(_poipoiStock.Key);
                    }
                }
                foreach (string key in processedKeys)
                {
                    _poipoiStockDict.Remove(key);
                }
            }
        }

19 Source : BanismentHandler.cs
with MIT License
from CoreOpenMMO

public void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var ruleViolationPacket = new RuleViolationPacket(message);

            byte banDays = 0;
            var banUntilDate = DateTime.Now;

            using (var otContext = new OpenTibiaDbContext())
            {
                var playerRecord = otContext.Players.Where(p => p.Charname.Equals(ruleViolationPacket.CharacterName)).FirstOrDefault();

                if (playerRecord != null)
                {
                    var userRecord = otContext.Users.Where(u => u.Login == playerRecord.Account_Nr).FirstOrDefault();

                    if (userRecord != null)
                    {
                        // Calculate Banishment date based on number of previous banishments youger than 60 days...
                        var todayMinus60Days = DateTime.Today.AddDays(-60).ToFileTimeUtc();
                        var banCount = otContext.Banishments.Where(b => b.AccountNr == playerRecord.Account_Nr && b.Timestamp > todayMinus60Days && b.PunishmentType == 1).Count();

                        switch (banCount)
                        {
                            case 0:
                                banDays = 7;
                                break;
                            case 1:
                                banDays = 15;
                                break;
                            case 2:
                                banDays = 30;
                                break;
                            case 3:
                                banDays = 90;
                                break;
                            default:
                                banDays = 255;
                                break;
                        }

                        banUntilDate = banUntilDate.AddDays(banDays);
                        var nowUnixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                        var banUntilUnixTimestamp = (int)banUntilDate.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                        otContext.Banishments.Add(new Banishment
                        {
                            AccountId = playerRecord.Account_Id,
                            AccountNr = playerRecord.Account_Nr,
                            Ip = ruleViolationPacket.IpAddress,
                            GmId = ruleViolationPacket.GamemasterId,
                            Violation = ruleViolationPacket.Reason,
                            Comment = ruleViolationPacket.Comment,
                            Timestamp = nowUnixTimestamp,
                            BanishedUntil = banUntilUnixTimestamp,
                            PunishmentType = 1
                        });

                        userRecord.Banished = 1;
                        userRecord.Banished_Until = banUntilUnixTimestamp;

                        otContext.SaveChanges();

                        ResponsePackets.Add(new BanismentResultPacket
                        {
                            BanDays = banDays,
                            BanishedUntil = (uint)banUntilDate.ToFileTimeUtc()
                        });

                        return;
                    }
                }
            }

            ResponsePackets.Add(new DefaultErrorPacket());
        }

19 Source : NotationHandler.cs
with MIT License
from CoreOpenMMO

public void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var ruleViolationPacket = new RuleViolationPacket(message);

            using (var otContext = new OpenTibiaDbContext())
            {
                var playerRecord = otContext.Players.Where(p => p.Charname.Equals(ruleViolationPacket.CharacterName)).FirstOrDefault();

                if (playerRecord != null)
                {
                    var userRecord = otContext.Users.Where(u => u.Login == playerRecord.Account_Nr).FirstOrDefault();

                    if (userRecord != null)
                    {
                        var nowUnixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                        otContext.Banishments.Add(new Banishment
                        {
                            AccountId = playerRecord.Account_Id,
                            AccountNr = playerRecord.Account_Nr,
                            Ip = ruleViolationPacket.IpAddress,
                            GmId = ruleViolationPacket.GamemasterId,
                            Violation = ruleViolationPacket.Reason,
                            Comment = ruleViolationPacket.Comment,
                            Timestamp = nowUnixTimestamp,
                            BanishedUntil = nowUnixTimestamp,
                            PunishmentType = 0x02
                        });

                        otContext.SaveChanges();

                        ResponsePackets.Add(new NotationResultPacket
                        {
                            GamemasterId = (uint)ruleViolationPacket.GamemasterId
                        });

                        return;
                    }
                }
            }

            ResponsePackets.Add(new DefaultErrorPacket());
        }

19 Source : Utils.cs
with GNU General Public License v3.0
from Coolapk-UWP

public static (TimeIntervalType type, object time) ConvertUnixTimeStampToReadable(double time, DateTime baseTime)
        {
            TimeSpan ttime = new TimeSpan((long)time * 1000_0000);
            DateTime tdate = unixDateBase.Add(ttime);
            TimeSpan temp = baseTime.ToUniversalTime()
                                    .Subtract(tdate);

            if (temp.TotalDays > 30)
            {
                return (TimeIntervalType.MonthsAgo, tdate);
            }
            else
            {
                TimeIntervalType type;
                if (temp.Days > 0) { type = TimeIntervalType.DaysAgo; }
                else if (temp.Hours > 0) { type = TimeIntervalType.HoursAgo; }
                else if (temp.Minutes > 0) { type = TimeIntervalType.MinutesAgo; }
                else { type = TimeIntervalType.JustNow; }

                return (type, temp);
            }
        }

19 Source : Utils.cs
with GNU General Public License v3.0
from Coolapk-UWP

public static double ConvertDateTimeToUnixTimeStamp(DateTime time)
        {
            return Math.Round(
                time.ToUniversalTime()
                    .Subtract(unixDateBase)
                    .TotalSeconds);
        }

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

private static void InternalExecutedOpt(
            SqlSugarInterceptorDescriptor descriptor,
            SqlSugarClient client,
            string sql,
            SugarParameter[] @params,
            Func<string, SugarParameter[], object> executedAct = null,
            Func<string, LogEventLevel, bool> filter = null) {

            var ms = 0D;

            if (client.TempItems.TryGetValue(TimestampKey, out var startStamp) && startStamp is DateTime stamp) {
                client.TempItems.Remove(TimestampKey);
                ms = DateTime.Now.Subtract(stamp).TotalMilliseconds;
            }

            object loggingParams;
            var userInfo = executedAct?.Invoke(sql, @params) ?? string.Empty;
            var logger = descriptor.ExposeLoggingServiceProvider.GetLogger<SqlSugarClient>(filter, LogEventSendMode.Automatic, descriptor.RenderingOptions);

            if (ms > 1000) {
                if (!logger.IsEnabled(LogEventLevel.Warning))
                    return;

                var logTrack = LogTrack.Create(client.ContextID, EventIdKeys.LongTimeExecuted);
                loggingParams = new {
                    OrmName = Constants.SinkKey,
                    ContextId = client.ContextID,
                    Sql = sql,
                    SqlParams = @params.Select(param => new DbParam(param.ParameterName, param.Value, param.DbType)).ToList(),
                    UsedTime = ms,
                    UserInfo = userInfo
                };
                logger.LogWarning(logTrack, OrmTemplateStandard.LongNormal, loggingParams);
            } else {
                if (!logger.IsEnabled(LogEventLevel.Information))
                    return;

                var logTrack = LogTrack.Create(client.ContextID, EventIdKeys.Executed);
                loggingParams = new {
                    OrmName = Constants.SinkKey,
                    ContextId = client.ContextID,
                    Sql = sql,
                    UsedTime = ms,
                    UserInfo = userInfo
                };
                logger.LogInformation(logTrack, OrmTemplateStandard.Normal, loggingParams);
            }
        }

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

private static void InternalErrorOpt(
            SqlSugarInterceptorDescriptor descriptor,
            SqlSugarClient client,
            Exception exception,
            Func<Exception, object> errorAct = null,
            Func<string, LogEventLevel, bool> filter = null) {

            var ms = 0D;

            if (client.TempItems.TryGetValue(TimestampKey, out var startStamp) && startStamp is DateTime stamp) {
                client.TempItems.Remove(TimestampKey);
                ms = DateTime.Now.Subtract(stamp).TotalMilliseconds;
            }

            object userInfo = errorAct?.Invoke(exception) ?? string.Empty;
            var logger = descriptor.ExposeLoggingServiceProvider.GetLogger<SqlSugarClient>(filter, LogEventSendMode.Automatic, descriptor.RenderingOptions);

            if (!logger.IsEnabled(LogEventLevel.Error))
                return;

            var logTrack = LogTrack.Create(client.ContextID, EventIdKeys.Error);
            var realException = exception.Unwrap();
            var loggingParams = new {
                OrmName = Constants.SinkKey,
                ContextId = client.ContextID,
                Sql = "unknown",
                SqlParams = "unknown",
                ExceptionType = exception.GetType(),
                ExceptionMessage = exception.Message,
                RealExceptionType = realException.GetType(),
                RealExceptionMessage = realException.Message,
                UsedTime = ms,
                UserInfo = userInfo
            };
            logger.LogError(logTrack, exception, OrmTemplateStandard.Error, loggingParams);
        }

19 Source : ObjectExtension.cs
with MIT License
from cq-panda

public static string ToUnixTimeStamp(this DateTime date)
        {
            DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1));
            string timeStamp = date.Subtract(startTime).Ticks.ToString();
            return timeStamp.Substring(0, timeStamp.Length - 7);
        }

19 Source : InputSimulationService.cs
with MIT License
from cre8ivepark

public override void LateUpdate()
        {
            base.LateUpdate();

            var profile = InputSimulationProfile;

            // Apply hand data in LateUpdate to ensure external changes are applied.
            // HandDataLeft/Right can be modified after the services Update() call.
            if (HandSimulationMode == HandSimulationMode.Disabled)
            {
                RemoveAllHandDevices();
            }
            else
            {
                DateTime currentTime = DateTime.UtcNow;
                double msSinceLastHandUpdate = currentTime.Subtract(new DateTime(lastHandUpdateTimestamp)).TotalMilliseconds;
                // TODO implement custom hand device update frequency here, use 1000/fps instead of 0
                if (msSinceLastHandUpdate > 0)
                {
                    UpdateHandDevice(HandSimulationMode, Handedness.Left, HandDataLeft);
                    UpdateHandDevice(HandSimulationMode, Handedness.Right, HandDataRight);

                    lastHandUpdateTimestamp = currentTime.Ticks;
                }
            }
        }

19 Source : FrmMain.cs
with GNU General Public License v3.0
from Crowley2012

private void Timers()
        {
            while (true)
            {
                TimeSpan spanReset = DateTime.Now.Subtract(_resetTime);
                TimeSpan spanRefresh = DateTime.Now.Subtract(_refreshTime);
                string runningTime = spanReset.Days > 0 ? $"Running Timer: {spanReset.Days} days {spanReset.Hours}:{spanReset.Minutes:00}:{spanReset.Seconds:00}" : $"Running Timer: {spanReset.Hours}:{spanReset.Minutes:00}:{spanReset.Seconds:00}";
                string refreshTime = $"Refresh Timer: {spanRefresh.Minutes}:{spanRefresh.Seconds:00}";

                if (string.IsNullOrWhiteSpace(txtRefreshTime.Text) || txtRefreshTime.Text.ConvertToInt() < 1)
                    UpdateRefreshTime("5");

                if (UserConfigService.RefreshTime / 1000 != txtRefreshTime.Text.ConvertToInt())
                    UserConfigService.RefreshTime = txtRefreshTime.Text.ConvertToInt() * 1000;

                UpdateTimers(runningTime, refreshTime);

                Thread.Sleep(500);
            }
        }

19 Source : Utility.cs
with MIT License
from Crynners

public static Double getUnixTimestamps(DateTime time)
        {
            return (time.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc))).TotalMilliseconds;
        }

19 Source : Tools.cs
with MIT License
from Crypto-APIs

public static string ToUnixTimestamp(DateTime dateTime)
        {
            var unixTimestamp = (int)dateTime.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
            return unixTimestamp.ToString(CultureInfo.InvariantCulture);
        }

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

public static long ToUnixTimestampUtc(this DateTime self) {
            var zero = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            return Convert.ToInt64(Math.Truncate((self.ToUniversalTime().Subtract(zero)).TotalMilliseconds));
        }

19 Source : SoundFxCommand.cs
with MIT License
from csharpfritz

public Task Execute(IChatService chatService, string userName, string fullCommandText)
		{

			var cmdText = fullCommandText.Substring(1).ToLowerInvariant();
			var cmd = Effects[cmdText];

			if (!InternalCooldownCheck()) return Task.CompletedTask;

			SoundCooldowns[cmdText] = (cmd.Files != null ? CalculateMultipleFileCooldownTime(cmd, cmdText) : DateTime.Now);


			var fileToPlay = cmd.Files != null ? IdentifyMultipleEffectsFilename(cmd, cmdText) : cmd.File;

			var soundTask = this.HubContext.Clients.All.PlaySoundEffect(fileToPlay);
			var textTask = chatService.SendMessageAsync($"@{userName} - {cmd.Response}");

			return Task.WhenAll(soundTask, textTask);

			bool InternalCooldownCheck()
			{

				if (cmd.Files != null)
				{
					TimeSpan cooldownRemaining;
					if (!CheckMultipleFilesCooldown(cmd, cmdText, out cooldownRemaining))
					{
						// TODO: Something witty to indicate the message isn't available
						chatService.SendMessageAsync($"@{userName} - {cmd.CooldownMessage} - Please wait another {Math.Round(cooldownRemaining.TotalSeconds)} seconds");
						return false;
					}
					return true;
				}

				if (!SoundCooldowns.ContainsKey(cmdText)) return true;
				var cooldown = TimeSpan.FromSeconds(Effects[cmdText].Cooldown);

				var cooldownWaiting = (SoundCooldowns[cmdText].Add(cooldown).Subtract(DateTime.Now));
				if (cooldownWaiting.TotalSeconds > 0) chatService.SendMessageAsync($"The !{cmdText} is not available for another {Math.Round(cooldownWaiting.TotalSeconds)} seconds");
				return cooldownWaiting.TotalSeconds <= 0;

			}

		}

19 Source : SoundFxCommand.cs
with MIT License
from csharpfritz

private bool CheckMultipleFilesCooldown(SoundFxDefinition cmd, string cmdText, out TimeSpan cooldownRemaining)
		{

			var cooldown = TimeSpan.FromSeconds(Effects[cmdText].Cooldown);
			cooldownRemaining = TimeSpan.Zero;

			if (SoundCooldowns.ContainsKey(cmdText))
			{
				if (SoundCooldowns[cmdText].Add(cooldown) < DateTime.Now)
				{
					SoundCooldowns[cmdText] = DateTime.Now;
					MultipleFileTriggers[cmdText].Clear();
					return true;
				}
				else
				{
					cooldownRemaining = SoundCooldowns[cmdText].Add(cooldown).Subtract(DateTime.Now);
					return (MultipleFileTriggers[cmdText].Count != cmd.Files.Length);
				}
			}
			return true;
		}

19 Source : TeamCommand.cs
with MIT License
from csharpfritz

public bool CanExecute(string userName, string fullCommandText)
		{

			var u = userName.ToLowerInvariant();

			// Add check to make sure we don't notify if the chatter is the Twitch broadcaster
			if (u.Equals(_BroadcasterChannel, StringComparison.InvariantCultureIgnoreCase))
			{
				return false;
			}

			var isTeammate = _Teammates.Contains(u);
			var recentShoutout = _TeammateCooldown.ContainsKey(u) && (DateTime.UtcNow.Subtract(_TeammateCooldown[u]) < ShoutoutCooldown);

			return isTeammate && !recentShoutout;

		}

19 Source : ChatClient.cs
with MIT License
from csharpfritz

private void ReceiveMessagesOnThread()
		{

			var lastMessageReceivedTimestamp = DateTime.Now;
			var errorPeriod = TimeSpan.FromSeconds(60);

			while (true)
			{

				Thread.Sleep(50);

				if (DateTime.Now.Subtract(lastMessageReceivedTimestamp) > errorPeriod)
				{
					Logger.LogError($"Haven't received a message in {errorPeriod.TotalSeconds} seconds");
					lastMessageReceivedTimestamp = DateTime.Now;
				}

				if (_Shutdown.IsCancellationRequested)
				{
					break;
				}

				if (_TcpClient.Connected && _TcpClient.Available > 0)
				{

					var msg = ReadMessage();
					if (string.IsNullOrEmpty(msg))
					{
						continue;
					}

					lastMessageReceivedTimestamp = DateTime.Now;
					Logger.LogTrace($"> {msg}");

					// Handle the Twitch keep-alive
					if (msg.StartsWith("PING"))
					{
						Logger.LogWarning("Received PING from Twitch... sending PONG");
						SendMessage($"PONG :{msg.Split(':')[1]}");
						continue;
					}

					ProcessMessage(msg);

				} else if (!_TcpClient.Connected)
				{
					// Reconnect
					Logger.LogWarning("Disconnected from Twitch.. Reconnecting in 2 seconds");
					Thread.Sleep(2000);
					this.Init();
					return;
				}

			}

			Logger.LogWarning("Exiting ReceiveMessages Loop");

		}

19 Source : Proxy.cs
with MIT License
from csharpfritz

private async Task WaitForSlot()
		{
			var isQueued = false;
			do
			{
				// Check rate-limit
				lock (_QueueLock)
				{
					if (_RateLimitRemaining - _WaitingRequests > 0)
					{
						_WaitingRequests++;
						if (isQueued)
						{
							_QueuedRequests--;
							isQueued = false;
						}
					}
					else
					{
						if (!isQueued)
						{
							if (_QueuedRequests + 1 > MAX_QUEUED)
							{
								throw new TimeoutException("Too many requests waiting");
							}
							_QueuedRequests++;
							isQueued = true;
						}
					}
				}

				if (isQueued)
				{
					await Task.Delay(new DateTime(Volatile.Read(ref _RateLimitResetTicks)).Subtract(DateTime.UtcNow));
				}
			}
			while (isQueued);
		}

See More Examples