System.DateTime.Add(System.TimeSpan)

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

961 Examples 7

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

private bool Allow()
        {
            if (!_liveMode)
            {
                return false;
            }

            lock (_sync)
            {
                var now = DateTime.UtcNow;
                if (now > _resetTime)
                {
                    _count = 0;

                    // rate limiting set at 30/hour
                    _resetTime = now.Add(TimeSpan.FromHours(1));
                }

                if (_count < RateLimit)
                {
                    _count++;
                    return true;
                }

                return false;
            }
        }

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

public DateTime GetForexOrderExpiryDateTime(Order order)
        {
            var cutOffTimeZone = TimeZones.NewYork;
            var cutOffTimeSpan = TimeSpan.FromHours(17);

            var expiryTime = Expiry.Date.Add(cutOffTimeSpan);
            if (order.Time.Date == Expiry.Date)
            {
                // expiry date same as order date
                var orderTime = order.Time.ConvertFromUtc(cutOffTimeZone);
                if (orderTime.TimeOfDay > cutOffTimeSpan)
                {
                    // order submitted after 5 PM, expiry on next date
                    expiryTime = expiryTime.AddDays(1);
                }
            }

            return expiryTime.ConvertToUtc(cutOffTimeZone);
        }

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

public override bool CanRemoveMember(DateTime utcTime, Security security)
        {
            // can always remove securities after dispose requested
            if (DisposeRequested)
            {
                return true;
            }

            // if we haven't begun receiving data for this security then it's safe to remove
            var lastData = security.Cache.GetData();
            if (lastData == null)
            {
                return true;
            }

            if (_liveMode)
            {
                // Only remove members when they have been in the universe for a minimum period of time.
                // This prevents us from needing to move contracts in and out too fast,
                // as price moves and filtered contracts change throughout the day.
                DateTime timeAdded;

                // get the date/time this symbol was added to the universe
                if (!_addTimesBySymbol.TryGetValue(security.Symbol, out timeAdded))
                {
                    return true;
                }

                if (timeAdded.Add(_minimumTimeInUniverse) > utcTime)
                {
                    // minimum time span not yet elapsed, do not remove
                    return false;
                }

                // ok to remove
                _addTimesBySymbol.Remove(security.Symbol);

                return true;
            }

            // only remove members on day changes, this prevents us from needing to
            // fast forward contracts continuously as price moves and out filtered
            // contracts change throughout the day
            var localTime = utcTime.ConvertFromUtc(security.Exchange.TimeZone);
            return localTime.Date != lastData.Time.Date;
        }

19 Source : TokenModule.cs
with MIT License
from catcherwong

private string GetJwt(string client_id, IAppConfiguration appConfig)
        {
            var now = DateTime.UtcNow;

            var claims = new Claim[]
            {
                        new Claim(JwtRegisteredClaimNames.Sub, client_id),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)
            };

            var symmetricKeyAsBase64 = appConfig.Audience.Secret;
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);

            var jwt = new JwtSecurityToken(
                issuer: appConfig.Audience.Iss,
                audience: appConfig.Audience.Aud,
                claims: claims,
                notBefore: now,
                expires: now.Add(TimeSpan.FromMinutes(2)),
                signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                expires_in = (int)TimeSpan.FromMinutes(2).TotalSeconds
            };

            return JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented });
        }

19 Source : AuthController.cs
with MIT License
from catcherwong-archive

[HttpGet]
        public IActionResult Get(string name, string pwd)
        {
            if (name == "catcher" && pwd == "123")
            {

                var now = DateTime.UtcNow;

                var claims = new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, name),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)
                };

                var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_settings.Value.Secret));
                var tokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = signingKey,
                    ValidateIssuer = true,
                    ValidIssuer = _settings.Value.Iss,
                    ValidateAudience = true,
                    ValidAudience = _settings.Value.Aud,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                    RequireExpirationTime = true,

                };

                var jwt = new JwtSecurityToken(
                    issuer: _settings.Value.Iss,
                    audience: _settings.Value.Aud,
                    claims: claims,
                    notBefore: now,
                    expires: now.Add(TimeSpan.FromMinutes(2)),
                    signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
                );
                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
                var responseJson = new
                {
                    access_token = encodedJwt,
                    expires_in = (int)TimeSpan.FromMinutes(2).TotalSeconds
                };

                return Json(responseJson);
            }
            else
            {
                return Json("");
            }
        }

19 Source : HttpHelper.cs
with GNU General Public License v3.0
from cdians

public static DateTime ConvertLongDateTime(long d)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(d + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

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

public void AddFile(DateTime startTime,TimeSpan duration,DataFileInfo4 file)
        {
            int mon1 = startTime.Month;
            var endTime = startTime.Add(duration);
            if (mon1 == endTime.Month)
            {
                var mm = AddMonth(mon1);
                mm.AddFile(startTime, duration, file);
            }
            else
            {
                var startTime2 = new DateTime(endTime.Year, endTime.Month, endTime.Day);

                var mm = AddMonth(mon1);
                mm.AddFile(startTime, startTime2-startTime, file);
                if ((endTime - startTime).Seconds <= 1)
                {
                    return;
                }
                else
                {
                    mm = AddMonth(endTime.Month);
                    mm.AddFile(startTime2, endTime - startTime2, file);
                }
            }
            mMaxMonth = Math.Max(mon1, mMaxMonth);
        }

19 Source : AzureServiceBusTransport.cs
with MIT License
from cfrenzel

protected Task _dispatch(string messageTypeIdentifier, byte[] messageBody, IEndpoint endpoint, MessageMetaData meta = null)
        {
            var message = new Message(messageBody);
            var sender = AzureServiceBusClientCache.GetSender(endpoint.Settings.ConnectionString);
            _metaDataMapper.ApplyMetaData(message, meta, messageTypeIdentifier);

            DateTime? scheduleAtUtc = null;
            if (meta != null && meta.DispatchDelay.HasValue)
            {
                //var baseDate = meta.CreatedAtUtc.HasValue ? meta.CreatedAtUtc.Value : DateTime.UtcNow;
                var baseDate = DateTime.UtcNow;
                scheduleAtUtc = baseDate.Add(meta.DispatchDelay.Value);
            }
            if(scheduleAtUtc.HasValue)// && scheduleAtUtc > DateTime.UtcNow.AddMilliseconds(400))
                return sender.ScheduleMessageAsync(message, scheduleAtUtc.Value);
            return sender.SendAsync(message);
        }

19 Source : DateTimeExtensions.cs
with MIT License
from charlessolar

public static DateTime RandomDateTimeForward(this DateTime start, TimeSpan min, TimeSpan max)
        {
            var random = new Random();
            var offset = TimeSpan.FromSeconds((random.NextDouble() * max.TotalSeconds) + min.TotalSeconds);
            return start.Add(offset);
        }

19 Source : TypeUtil.cs
with MIT License
from chi8708

public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

19 Source : LoginController.cs
with MIT License
from chi8708

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(LoginViewModel user) 
        {
            string captcha = user.Captcha;
            if (!ModelState.IsValid)
            {
                return JavaScript("layer.msg('必填项未填写或数据格式不正确!');");
            }
            if (null != Session["Captcha"] && captcha.ToLower() != Session["Captcha"].ToString().ToLower())
            {
                return JavaScript(" layer.msg('验证码不正确');changeCaptcha();");
            }
            var dbUser = userBLL.GetList(string.Format(" StopFlag=0 AND UserName='{0}' AND UserPwd='{1}' ",
              user.UserCode,user.Preplacedword)).FirstOrDefault();

            if (dbUser == null)
            {
                return JavaScript("layer.msg('用户名或密码错误!');changeCaptcha();");
            }

            NBCZUser.WriteUser(user.UserCode);
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserCode, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), true, FormsAuthentication.FormsCookiePath);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
            cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.Path = ticket.CookiePath;
            Response.Cookies.Add(cookie);
            return JavaScript(string.Format("window.location.href='../Home/Index'"));
        }

19 Source : BasicDataConversion.cs
with MIT License
from chinabeacon

public static DateTime ConvertLongDateTime(this long d)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(d + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

19 Source : BasicDataConversion.cs
with MIT License
from chinabeacon

public static DateTime? ConvertLongToNullableDateTime(this long d)
        {
            if (d <= 0) return null;
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(d + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

19 Source : HistoryExtractBuilder.cs
with Apache License 2.0
from chkr1011

static IEnumerable<HistoryExtractDataPoint> GenerateNumberBasedDataPoints(
            List<HistoryValueElement> enreplacedies,
            DateTime rangeStart,
            DateTime rangeEnd,
            TimeSpan? interval)
        {
            if (!interval.HasValue)
            {
                var dataPoints = GenerateTextBasedDataPoints(enreplacedies, rangeStart, rangeEnd);

                foreach (var dataPoint in dataPoints)
                {
                    if (double.TryParse(dataPoint.Value as string,
                        NumberStyles.Float,
                        CultureInfo.InvariantCulture,
                        out var numberValue))
                    {
                        dataPoint.Value = numberValue;
                    }
                }

                return dataPoints;
            }

            var intervalDataPoints = new List<HistoryExtractDataPoint>();

            while (rangeStart <= rangeEnd)
            {
                // Start (real) value
                var dataPointStart = new HistoryExtractDataPoint
                {
                    Timestamp = rangeStart
                };

                dataPointStart.Value = GetValue(enreplacedies, dataPointStart.Timestamp);

                // End (real) value
                var dataPointEnd = new HistoryExtractDataPoint
                {
                    Timestamp = rangeStart.Add(interval.Value * 2)
                };

                dataPointEnd.Value = GetValue(enreplacedies, dataPointEnd.Timestamp);

                // Middle (average) value
                var dataPointMiddle = new HistoryExtractDataPoint
                {
                    Timestamp = rangeStart.Add(interval.Value),
                    Value = GetAverageValue(enreplacedies, dataPointStart.Timestamp, dataPointEnd.Timestamp)
                };

                if (!intervalDataPoints.Any())
                {
                    intervalDataPoints.Add(dataPointStart);
                }

                intervalDataPoints.Add(dataPointMiddle);
                intervalDataPoints.Add(dataPointEnd);

                rangeStart += interval.Value * 3;
            }

            return intervalDataPoints;
        }

19 Source : HistoryExtractBuilder.cs
with Apache License 2.0
from chkr1011

static IEnumerable<HistoryExtractDataPoint> GenerateNumberBasedDataPoints(
            List<HistoryValueElement> enreplacedies,
            DateTime rangeStart,
            DateTime rangeEnd,
            TimeSpan? interval)
        {
            if (!interval.HasValue)
            {
                var dataPoints = GenerateTextBasedDataPoints(enreplacedies, rangeStart, rangeEnd);

                foreach (var dataPoint in dataPoints)
                {
                    if (double.TryParse(dataPoint.Value as string,
                        NumberStyles.Float,
                        CultureInfo.InvariantCulture,
                        out var numberValue))
                    {
                        dataPoint.Value = numberValue;
                    }
                }

                return dataPoints;
            }

            var intervalDataPoints = new List<HistoryExtractDataPoint>();

            while (rangeStart <= rangeEnd)
            {
                // Start (real) value
                var dataPointStart = new HistoryExtractDataPoint
                {
                    Timestamp = rangeStart
                };

                dataPointStart.Value = GetValue(enreplacedies, dataPointStart.Timestamp);

                // End (real) value
                var dataPointEnd = new HistoryExtractDataPoint
                {
                    Timestamp = rangeStart.Add(interval.Value * 2)
                };

                dataPointEnd.Value = GetValue(enreplacedies, dataPointEnd.Timestamp);

                // Middle (average) value
                var dataPointMiddle = new HistoryExtractDataPoint
                {
                    Timestamp = rangeStart.Add(interval.Value),
                    Value = GetAverageValue(enreplacedies, dataPointStart.Timestamp, dataPointEnd.Timestamp)
                };

                if (!intervalDataPoints.Any())
                {
                    intervalDataPoints.Add(dataPointStart);
                }

                intervalDataPoints.Add(dataPointMiddle);
                intervalDataPoints.Add(dataPointEnd);

                rangeStart += interval.Value * 3;
            }

            return intervalDataPoints;
        }

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

private protected static DateTime FromTimeInMS(long value)
        {
            long ticks = (value >= MaxDateTimeInMS) ? (MaxDateTimeInMS * 10000L) - 1 : value * 10000L;
            ticks = (value <= MinDateTimeInMS) ? unchecked((MinDateTimeInMS * 10000L)) : ticks;
            return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Add(new TimeSpan(ticks)).ToUniversalTime();
        }

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

protected static DateTime? ConvertFromDateTime(String value)
        {
            if (!String.IsNullOrEmpty(value))
            {
                var position = FetchDigits(value);

                if (PositionIsValidForDateTime(value, position))
                {
                    var year = Int32.Parse(value.Substring(0, position));
                    var month = Int32.Parse(value.Substring(position + 1, 2));
                    var day = Int32.Parse(value.Substring(position + 4, 2));
                    position += 6;

                    if (IsLegalDay(day, month, year) && IsTimeSeparator(value[position]))
                    {
                        var requireOffset = value[position++] == ' ';
                        var ts = ToTime(value, ref position);
                        var dt = new DateTime(year, month, day, 0, 0, 0, DateTimeKind.Utc);

                        if (ts != null)
                        {
                            dt = dt.Add(ts.Value);

                            if (position == value.Length)
                            {
                                if (requireOffset)
                                {
                                    return null;
                                }

                                return dt;
                            }

                            if (value[position] != 'Z')
                            {
                                if (IsLegalPosition(value, position))
                                {
                                    var hours = Int32.Parse(value.Substring(position + 1, 2));
                                    var minutes = Int32.Parse(value.Substring(position + 4, 2));
                                    var offset = new TimeSpan(hours, minutes, 0);

                                    if (value[position] == '+')
                                    {
                                        dt = dt.Add(offset);
                                    }
                                    else if (value[position] == '-')
                                    {
                                        dt = dt.Subtract(offset);
                                    }
                                    else
                                    {
                                        return null;
                                    }
                                }
                                else
                                {
                                    return null;
                                }
                            }
                            else if (position + 1 != value.Length)
                            {
                                return null;
                            }
                            else
                            {
                                dt = dt.ToUniversalTime();
                            }

                            return dt;
                        }
                    }
                }
            }

            return null;
        }

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

protected static DateTime? ConvertFromDateTime(String value)
        {
            if (!String.IsNullOrEmpty(value))
            {
                var position = FetchDigits(value);

                if (PositionIsValidForDateTime(value, position))
                {
                    var year = Int32.Parse(value.Substring(0, position));
                    var month = Int32.Parse(value.Substring(position + 1, 2));
                    var day = Int32.Parse(value.Substring(position + 4, 2));
                    position += 6;

                    if (IsLegalDay(day, month, year) && IsTimeSeparator(value[position]))
                    {
                        var requireOffset = value[position++] == ' ';
                        var ts = ToTime(value, ref position);
                        var dt = new DateTime(year, month, day, 0, 0, 0, DateTimeKind.Utc);

                        if (ts != null)
                        {
                            dt = dt.Add(ts.Value);

                            if (position == value.Length)
                            {
                                if (requireOffset)
                                {
                                    return null;
                                }

                                return dt;
                            }

                            if (value[position] != 'Z')
                            {
                                if (IsLegalPosition(value, position))
                                {
                                    var hours = Int32.Parse(value.Substring(position + 1, 2));
                                    var minutes = Int32.Parse(value.Substring(position + 4, 2));
                                    var offset = new TimeSpan(hours, minutes, 0);

                                    if (value[position] == '+')
                                    {
                                        dt = dt.Add(offset);
                                    }
                                    else if (value[position] == '-')
                                    {
                                        dt = dt.Subtract(offset);
                                    }
                                    else
                                    {
                                        return null;
                                    }
                                }
                                else
                                {
                                    return null;
                                }
                            }
                            else if (position + 1 != value.Length)
                            {
                                return null;
                            }
                            else
                            {
                                dt = dt.ToUniversalTime();
                            }

                            return dt;
                        }
                    }
                }
            }

            return null;
        }

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

protected static DateTime? ConvertFromDateTime(String value)
        {
            if (!String.IsNullOrEmpty(value))
            {
                var position = FetchDigits(value);

                if (PositionIsValidForDateTime(value, position))
                {
                    var year = Int32.Parse(value.Substring(0, position));
                    var month = Int32.Parse(value.Substring(position + 1, 2));
                    var day = Int32.Parse(value.Substring(position + 4, 2));
                    position += 6;

                    if (IsLegalDay(day, month, year) && IsTimeSeparator(value[position]))
                    {
                        position++;
                        var ts = ToTime(value, ref position);
                        var dt = new DateTime(year, month, day, 0, 0, 0, DateTimeKind.Local);

                        if (ts != null)
                        {
                            dt = dt.Add(ts.Value);

                            if (position == value.Length)
                            {
                                return dt;
                            }
                        }
                    }
                }
            }

            return null;
        }

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

protected static DateTime? ConvertFromTime(String value)
        {
            if (!String.IsNullOrEmpty(value))
            {
                var position = 0;
                var ts = ToTime(value, ref position);

                if (ts != null && position == value.Length)
                {
                    return new DateTime(0, DateTimeKind.Utc).Add(ts.Value);
                }
            }

            return null;
        }

19 Source : TileImageLoader.cs
with Microsoft Public License
from ClemensFischer

private static DateTime GetExpiration(TimeSpan? maxAge)
        {
            if (!maxAge.HasValue)
            {
                maxAge = DefaultCacheExpiration;
            }
            else if (maxAge.Value > MaxCacheExpiration)
            {
                maxAge = MaxCacheExpiration;
            }

            return DateTime.UtcNow.Add(maxAge.Value);
        }

19 Source : Brute.cs
with GNU General Public License v3.0
from cobbr

private static void TaskExecute(TaskingMessenger messenger, GruntTaskingMessage message, int Delay)
        {
            const int MAX_MESSAGE_SIZE = 1048576;
            string output = "";
            try
            {
                if (message.Type == GruntTaskingType.replacedembly)
                {
                    string[] pieces = message.Message.Split(',');
                    if (pieces.Length > 0)
                    {
                        object[] parameters = null;
                        if (pieces.Length > 1) { parameters = new object[pieces.Length - 1]; }
                        for (int i = 1; i < pieces.Length; i++) { parameters[i - 1] = Encoding.UTF8.GetString(Convert.FromBase64String(pieces[i])); }
                        byte[] compressedBytes = Convert.FromBase64String(pieces[0]);
                        byte[] decompressedBytes = Utilities.Decompress(compressedBytes);
                        replacedembly gruntTask = replacedembly.Load(decompressedBytes);
                        PropertyInfo streamProp = gruntTask.GetType("Task").GetProperty("OutputStream");
                        string results = "";
                        if (streamProp == null)
                        {
                            results = (string) gruntTask.GetType("Task").GetMethod("Execute").Invoke(null, parameters);
                        }
                        else
                        {
                            Thread invokeThread = new Thread(() => results = (string) gruntTask.GetType("Task").GetMethod("Execute").Invoke(null, parameters));
                            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
                            {
                                using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.GetClientHandlereplacedtring()))
                                {
                                    streamProp.SetValue(null, pipeClient, null);
                                    DateTime lastTime = DateTime.Now;
                                    invokeThread.Start();
                                    using (StreamReader reader = new StreamReader(pipeServer))
                                    {
                                        object synclock = new object();
                                        string currentRead = "";
                                        Thread readThread = new Thread(() => {
                                            int count;
                                            char[] read = new char[MAX_MESSAGE_SIZE];
                                            while ((count = reader.Read(read, 0, read.Length)) > 0)
                                            {
                                                lock (synclock)
                                                {
                                                    currentRead += new string(read, 0, count);
                                                }
                                            }
                                        });
                                        readThread.Start();
                                        while (readThread.IsAlive)
                                        {
                                            Thread.Sleep(Delay * 1000);
                                            lock (synclock)
                                            {
                                                try
                                                {
                                                    if (currentRead.Length >= MAX_MESSAGE_SIZE)
                                                    {
                                                        for (int i = 0; i < currentRead.Length; i += MAX_MESSAGE_SIZE)
                                                        {
                                                            string aRead = currentRead.Substring(i, Math.Min(MAX_MESSAGE_SIZE, currentRead.Length - i));
                                                            try
                                                            {
                                                                GruntTaskingMessageResponse response = new GruntTaskingMessageResponse(GruntTaskingStatus.Progressed, aRead);
                                                                messenger.QueueTaskingMessage(response.ToJson(), message.Name);
                                                            }
                                                            catch (Exception) {}
                                                        }
                                                        currentRead = "";
                                                        lastTime = DateTime.Now;
                                                    }
                                                    else if (currentRead.Length > 0 && DateTime.Now > (lastTime.Add(TimeSpan.FromSeconds(Delay))))
                                                    {
                                                        GruntTaskingMessageResponse response = new GruntTaskingMessageResponse(GruntTaskingStatus.Progressed, currentRead);
                                                        messenger.QueueTaskingMessage(response.ToJson(), message.Name);
                                                        currentRead = "";
                                                        lastTime = DateTime.Now;
                                                    }
                                                }
                                                catch (ThreadAbortException) { break; }
                                                catch (Exception) { currentRead = ""; }
                                            }
                                        }
                                        output += currentRead;
                                    }
                                }
                            }
                            invokeThread.Join();
                        }
                        output += results;
                    }
                }
                else if (message.Type == GruntTaskingType.Connect)
                {
                    string[] split = message.Message.Split(',');
                    bool connected = messenger.Connect(split[0], split[1]);
                    output += connected ? "Connection to " + split[0] + ":" + split[1] + " succeeded!" :
                                          "Connection to " + split[0] + ":" + split[1] + " failed.";
                }
                else if (message.Type == GruntTaskingType.Disconnect)
                {
                    bool disconnected = messenger.Disconnect(message.Message);
                    output += disconnected ? "Disconnect succeeded!" : "Disconnect failed.";
                }
            }
            catch (Exception e)
            {
                try
                {
                    GruntTaskingMessageResponse response = new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, "Task Exception: " + e.Message + Environment.NewLine + e.StackTrace);
                    messenger.QueueTaskingMessage(response.ToJson(), message.Name);
                }
                catch (Exception) { }
            }
            finally
            {
                for (int i = 0; i < output.Length; i += MAX_MESSAGE_SIZE)
                {
                    string aRead = output.Substring(i, Math.Min(MAX_MESSAGE_SIZE, output.Length - i));
                    try
                    {
                        GruntTaskingStatus status = i + MAX_MESSAGE_SIZE < output.Length ? GruntTaskingStatus.Progressed : GruntTaskingStatus.Completed;
                        GruntTaskingMessageResponse response = new GruntTaskingMessageResponse(status, aRead);
                        messenger.QueueTaskingMessage(response.ToJson(), message.Name);
                    }
                    catch (Exception) {}
                }
            }
        }

19 Source : LiteDbDistributedLock.cs
with MIT License
from codeyu

private void Acquire(TimeSpan timeout)
        {
            try
            {
                // If result is null, then it means we acquired the lock
                var isLockAcquired = false;
                var now = DateTime.UtcNow;
                var lockTimeoutTime = now.Add(timeout);

                while (!isLockAcquired && (lockTimeoutTime >= now))
                {
                    var result = _database.DistributedLock.FindOne(x => x.Resource == _resource);
                    var distributedLock = result ?? new DistributedLock();
                    distributedLock.Resource = _resource;
                    distributedLock.ExpireAt = DateTime.UtcNow.Add(_storageOptions.DistributedLockLifetime);

                    try
                    {
                      _database.DistributedLock.Upsert(distributedLock);
                    }
                    catch (LiteException ex) when (ex.ErrorCode == LiteException.INDEX_DUPLICATE_KEY)
                    {
                        // The lock already exists preventing us from inserting.
                        continue;
                    }
                    
                    // If result is null, then it means we acquired the lock
                    if (result == null)
                    {
                        isLockAcquired = true;
                    }
                    else
                    {
                        EventWaitHandle eventWaitHandle = null;
                        var waitTime = (int)timeout.TotalMilliseconds / 10;
                        if (_isEventWaitHandleSupported)
                        {
                            try
                            {
                                // Wait on the event. This allows us to be "woken" up sooner rather than later.
                                // We wait in chunks as we need to "wake-up" from time to time and poll mongo,
                                // in case that the lock was acquired on another machine or instance.
                                eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, EventWaitHandleName);
                                eventWaitHandle.WaitOne(waitTime);
                            }
                            catch (PlatformNotSupportedException)
                            {
                                // See _isEventWaitHandleSupported definition for more info.
                                _isEventWaitHandleSupported = false;
                                eventWaitHandle = null;
                            }
                        }
                        if (eventWaitHandle == null)
                        {
                            // Sleep for a while and then check if the lock has been released.
                            Thread.Sleep(waitTime);
                        }
                        now = DateTime.UtcNow;
                    }
                }

                if (!isLockAcquired)
                {
                    throw new DistributedLockTimeoutException($"Could not place a lock on the resource \'{_resource}\': The lock request timed out.");
                }
            }
            catch (DistributedLockTimeoutException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new LiteDbDistributedLockException($"Could not place a lock on the resource \'{_resource}\': Check inner exception for details.", ex);
            }
        }

19 Source : LiteDbDistributedLock.cs
with MIT License
from codeyu

private void Acquire(TimeSpan timeout)
        {
            try
            {
                // If result is null, then it means we acquired the lock
                var isLockAcquired = false;
                var now = DateTime.UtcNow;
                var lockTimeoutTime = now.Add(timeout);

                while (!isLockAcquired && (lockTimeoutTime >= now))
                {
                    var result = _database.DistributedLock.FindOne(x => x.Resource == _resource);
                    var distributedLock = result ?? new DistributedLock();
                    distributedLock.Resource = _resource;
                    distributedLock.ExpireAt = DateTime.UtcNow.Add(_storageOptions.DistributedLockLifetime);

                    try
                    {
                      _database.DistributedLock.Upsert(distributedLock);
                    }
                    catch (LiteException ex) when (ex.ErrorCode == LiteException.INDEX_DUPLICATE_KEY)
                    {
                        // The lock already exists preventing us from inserting.
                        continue;
                    }
                    
                    // If result is null, then it means we acquired the lock
                    if (result == null)
                    {
                        isLockAcquired = true;
                    }
                    else
                    {
                        EventWaitHandle eventWaitHandle = null;
                        var waitTime = (int)timeout.TotalMilliseconds / 10;
                        if (_isEventWaitHandleSupported)
                        {
                            try
                            {
                                // Wait on the event. This allows us to be "woken" up sooner rather than later.
                                // We wait in chunks as we need to "wake-up" from time to time and poll mongo,
                                // in case that the lock was acquired on another machine or instance.
                                eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, EventWaitHandleName);
                                eventWaitHandle.WaitOne(waitTime);
                            }
                            catch (PlatformNotSupportedException)
                            {
                                // See _isEventWaitHandleSupported definition for more info.
                                _isEventWaitHandleSupported = false;
                                eventWaitHandle = null;
                            }
                        }
                        if (eventWaitHandle == null)
                        {
                            // Sleep for a while and then check if the lock has been released.
                            Thread.Sleep(waitTime);
                        }
                        now = DateTime.UtcNow;
                    }
                }

                if (!isLockAcquired)
                {
                    throw new DistributedLockTimeoutException($"Could not place a lock on the resource \'{_resource}\': The lock request timed out.");
                }
            }
            catch (DistributedLockTimeoutException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new LiteDbDistributedLockException($"Could not place a lock on the resource \'{_resource}\': Check inner exception for details.", ex);
            }
        }

19 Source : LiteDbWriteOnlyTransaction.cs
with MIT License
from codeyu

public override void ExpireJob(string jobId, TimeSpan expireIn)
        {
            QueueCommand(x =>
            {
                var iJobId = int.Parse(jobId);
                var job = x.Job.FindOne(_ => _.Id == iJobId);
                job.ExpireAt = DateTime.UtcNow.Add(expireIn);
                x.Job.Update(job);
            });
        }

19 Source : LiteDbDistributedLock.cs
with MIT License
from codeyu

private void StartHeartBeat()
        {
            TimeSpan timerInterval = TimeSpan.FromMilliseconds(_storageOptions.DistributedLockLifetime.TotalMilliseconds / 5);

            _heartbeatTimer = new Timer(state =>
            {
                // Timer callback may be invoked after the Dispose method call,
                // so we are using lock to avoid unsynchronized calls.
                try
                {
                    var distributedLock = _database.DistributedLock.FindOne(x => x.Resource == _resource);
                    distributedLock.ExpireAt = DateTime.UtcNow.Add(_storageOptions.DistributedLockLifetime);

                    _database.DistributedLock.Update(distributedLock);
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("Unable to update heartbeat on the resource '{0}'. {1}", _resource, ex);
                }
            }, null, timerInterval, timerInterval);
        }

19 Source : LiteDbConnection.cs
with MIT License
from codeyu

public override string CreateExpiredJob(Job job, IDictionary<string, string> parameters, DateTime createdAt,
            TimeSpan expireIn)
        {
            if (job == null)
                throw new ArgumentNullException(nameof(job));

            if (parameters == null)
                throw new ArgumentNullException(nameof(parameters));

            lock (_lock)
            {
                var invocationData = InvocationData.Serialize(job);

                var jobDto = new LiteJob
                {
                    InvocationData = SerializationHelper.Serialize(invocationData, SerializationOption.User),
                    Arguments = invocationData.Arguments,
                    Parameters = parameters.ToDictionary(kv => kv.Key, kv => kv.Value),
                    CreatedAt = createdAt,
                    ExpireAt = createdAt.Add(expireIn)
                };

                Database.Job.Insert(jobDto);

                var jobId = jobDto.Id;

                return jobId.ToString();
            }
        }

19 Source : LiteDbConnection.cs
with MIT License
from codeyu

public override int RemoveTimedOutServers(TimeSpan timeOut)
        {
            if (timeOut.Duration() != timeOut)
            {
                throw new ArgumentException("The `timeOut` value must be positive.", nameof(timeOut));
            }
            var delCount = 0;
            var servers = Database.Server.FindAll();
            foreach (var server in servers)
            {
                if (server.LastHeartbeat < DateTime.UtcNow.Add(timeOut.Negate()))
                {
                    Database.Server.Delete(server.Id);
                    delCount++;
                }
            }
            return delCount;
        }

19 Source : LiteDbWriteOnlyTransaction.cs
with MIT License
from codeyu

public override void ExpireSet(string key, TimeSpan expireIn)
        {
            if (key == null) throw new ArgumentNullException(nameof(key));
            
            QueueCommand(x =>
            {
                var states = x.StateDataSet.Find(_ => _.Key == key);
                foreach(var state in states)
                {
                    state.ExpireAt = DateTime.UtcNow.Add(expireIn);
                    x.StateDataSet.Update(state);
                }
                
            });
            
        }

19 Source : LiteDbWriteOnlyTransaction.cs
with MIT License
from codeyu

public override void ExpireList(string key, TimeSpan expireIn)
        {
            if (key == null) throw new ArgumentNullException(nameof(key));
         
            QueueCommand(x =>
            {
                var states = x.StateDataList.Find(_ => _.Key == key);
                foreach(var state in states)
                {
                    state.ExpireAt = DateTime.UtcNow.Add(expireIn);
                    x.StateDataList.Update(state);
                }
                
            });
        }

19 Source : LiteDbWriteOnlyTransaction.cs
with MIT License
from codeyu

public override void ExpireHash(string key, TimeSpan expireIn)
        {
            if (key == null) throw new ArgumentNullException(nameof(key));
           
            QueueCommand(x =>
            {
                var states = x.StateDataHash.Find(_ => _.Key == key);
                foreach(var state in states)
                {
                    state.ExpireAt = DateTime.UtcNow.Add(expireIn);
                    x.StateDataHash.Update(state);
                }
                
            });
        }

19 Source : LiteDbWriteOnlyTransaction.cs
with MIT License
from codeyu

public override void IncrementCounter(string key, TimeSpan expireIn)
        {
            var counter = new Counter
            {
                Id = ObjectId.NewObjectId(),
                Key = key,
                Value = +1L,
                ExpireAt = DateTime.UtcNow.Add(expireIn)
            };
            QueueCommand(x => x.StateDataCounter.Insert(counter));
        }

19 Source : LiteDbWriteOnlyTransaction.cs
with MIT License
from codeyu

public override void DecrementCounter(string key, TimeSpan expireIn)
        {
            QueueCommand(x => x.StateDataCounter.Insert(new Counter
            {
                Id = ObjectId.NewObjectId(),
                Key = key,
                Value = -1L,
                ExpireAt = DateTime.UtcNow.Add(expireIn)
            }));
        }

19 Source : PureWebSocket.cs
with GNU General Public License v3.0
from Coinigy

private void StartSender()
        {
            _logger.Log("Starting sender.");
            _senderTask = Task.Run(async () =>
            {
                _logger.Log("Entering sender loop.");
                _senderRunning = true;
                try
                {
                    while (!_disposedValue && !_reconnecting)
                    {
                        if (_ws.State == WebSocketState.Open && !_reconnecting)
                        {
                            var msg = _sendQueue.Take(_tokenSource.Token);
                            if (msg.Key.Add(_options.SendCacheItemTimeout) < DateTime.UtcNow)
                            {
                                _logger.Log($"Message expired skipping: {msg.Key} {msg.Value}.");
                                continue;
                            }

                            var buffer = msg.Value.Data;
                            try
                            {
                                _logger.Log($"Sending message: {msg.Key} {msg.Value}.");
                                var msgType = msg.Value.Type == MessageType.TEXT ? WebSocketMessageType.Text : WebSocketMessageType.Binary;
                                await _ws.SendAsync(new ArraySegment<byte>(buffer), msgType, true,
                                    _tokenSource.Token).ConfigureAwait(false);
                            }
                            catch (Exception ex)
                            {
                                _logger.Log($"Sender threw sending exception: {ex.Message}.");
                                // Most likely socket error
                                OnSendFailed?.Invoke(this, msg.Value.Data, ex);
                                _reconnectNeeded = true;
                                _ws.Abort();
                                break;
                            }
                        }

                        // limit to N ms per iteration
                        Thread.Sleep(_options.SendDelay);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Log($"Sender threw exception: {ex.Message}.");
                    OnSendFailed?.Invoke(this, Encoding.UTF8.GetBytes(string.Empty), ex);
                    OnError?.Invoke(this, ex);
                }

                _senderRunning = false;
                _logger.Log("Exiting sender.");
                return Task.CompletedTask;
            });
        }

19 Source : Extention.Int.cs
with Apache License 2.0
from Coldairarrow

public static DateTime ToDateTime_From_JsGetTime(this long jsGetTime)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(jsGetTime + "0000");  //说明下,时间格式为13位后面补加4个"0",如果时间格式为10位则后面补加7个"0",至于为什么我也不太清楚,也是仿照人家写的代码转换的
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow); //得到转换后的时间

            return dtResult;
        }

19 Source : TimeManipulationProvider.cs
with GNU General Public License v3.0
from control-net

public DateTime? GetDateTimeLocalToUser(DateTime? utcDateTime, MiunieUser user)
        {
            if (!utcDateTime.HasValue)
            {
                return utcDateTime;
            }

            if (user.UtcTimeOffset.HasValue)
            {
                return utcDateTime.Value.Add(user.UtcTimeOffset.Value);
            }

            return utcDateTime;
        }

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 : JwtToken.cs
with Apache License 2.0
from CoreUnion

public static dynamic BuildJwtToken(Claim[] claims, PermissionRequirement permissionRequirement)
        {
            var now = DateTime.Now;
            // 实例化JwtSecurityToken
            var jwt = new JwtSecurityToken(
                issuer: permissionRequirement.Issuer,
                audience: permissionRequirement.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(permissionRequirement.Expiration),
                signingCredentials: permissionRequirement.SigningCredentials
            );
            // 生成 Token
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            //打包返回前台
            var responseJson = new
            {
                success = true,
                token = encodedJwt,
                expires_in = permissionRequirement.Expiration.TotalSeconds,
                token_type = "Bearer"
            };
            return responseJson;
        }

19 Source : TimeBoundedCache.cs
with MIT License
from CoreWCF

private void PurgeStaleItems()
        {
            if (!(CacheLock.IsWriterLockHeld == true))
            {
                // we failfast here because if we don't have the lock we could corrupt the cache
                Fx.replacedert("Cache write lock is not held.");
                DiagnosticUtility.FailFast("Cache write lock is not held.");
            }
            ArrayList expiredItems = new ArrayList();
            foreach (object key in Entries.Keys)
            {
                IExpirableItem item = Entries[key] as IExpirableItem;
                if (IsExpired(item))
                {
                    // this is a stale item. Remove!
                    OnRemove(Extracreplacedem(item));
                    expiredItems.Add(key);
                }
            }
            for (int i = 0; i < expiredItems.Count; ++i)
            {
                Entries.Remove(expiredItems[i]);
            }
            CancelTimerIfNeeded();
            _nextPurgeTimeUtc = DateTime.UtcNow.Add(_purgeInterval);
        }

19 Source : DeleteOldContactsCommandHandler.cs
with MIT License
from CovidWorld

protected override async Task Handle(DeleteOldContactsCommand request, CancellationToken cancellationToken)
        {
            var interval = DateTime.UtcNow.Add(-request.DeleteInterval);
            int intervalEpoch = (int)dateTimeConvertor.DateTimeToUnixTimestamp(interval);

            await repository.DeleteContactsAsync(intervalEpoch, cancellationToken);
            await repository.UnitOfWork.SaveChangesAsync(cancellationToken);
        }

19 Source : DeleteOldLocationsCommandHandler.cs
with MIT License
from CovidWorld

protected override async Task Handle(DeleteOldLocationsCommand request, CancellationToken cancellationToken)
        {
            var toInterval = DateTime.UtcNow.Add(-request.DeleteInterval);
            await repository.DeleteLocationsAsync(toInterval, cancellationToken);
            await repository.UnitOfWork.SaveChangesAsync(cancellationToken);
        }

19 Source : Profile.cs
with MIT License
from CovidWorld

public void BeginQuarantine(TimeSpan duration)
        {
            IsInQuarantine = true;
            QuarantineBeginning = DateTime.UtcNow;
            QuarantineEnd = QuarantineBeginning.Value.Add(duration);
        }

19 Source : JsonTextReader.cs
with MIT License
from CragonGame

private void ParseDate(string text)
    {
      string value = text.Substring(6, text.Length - 8);
      DateTimeKind kind = DateTimeKind.Utc;

      int index = value.IndexOf('+', 1);

      if (index == -1)
        index = value.IndexOf('-', 1);

      TimeSpan offset = TimeSpan.Zero;

      if (index != -1)
      {
        kind = DateTimeKind.Local;
        offset = ReadOffset(value.Substring(index));
        value = value.Substring(0, index);
      }

      long javaScriptTicks = long.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture);

      DateTime utcDateTime = JsonConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks);

      if (_readType == ReadType.ReadAsDateTimeOffset)
      {
        SetToken(JsonToken.Date, new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset));
      }
      else
      {
        DateTime dateTime;

        switch (kind)
        {
          case DateTimeKind.Unspecified:
            dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified);
            break;
          case DateTimeKind.Local:
            dateTime = utcDateTime.ToLocalTime();
            break;
          default:
            dateTime = utcDateTime;
            break;
        }

        SetToken(JsonToken.Date, dateTime);
      }
    }

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

public static void TryExec(Action action, TimeSpan timeout)
        {
            var timer = DateTime.UtcNow.Add(timeout);

            do
            {
                try
                {
                    action();
                    return;
                }
                catch (IOException ex)
                {
                    ex.WaitIfLocked(25);
                }
            }
            while (DateTime.UtcNow < timer);

            throw UltraLiteException.LockTimeout(timeout);
        }

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 : ChatClient.cs
with MIT License
from csharpfritz

private TimeSpan? CheckThrottleStatus()
		{

			var throttleDuration = TimeSpan.FromSeconds(30);
			var maximumCommands = 100;

			if (_NextReset == null)
			{
				_NextReset = DateTime.UtcNow.Add(throttleDuration);
			} else if (_NextReset < DateTime.UtcNow)
			{
				_NextReset = DateTime.UtcNow.Add(throttleDuration);
			}

			// TODO: FInish checking and enforcing the chat throttling

			return null;


		}

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

public static DateTime ConvertToDateTime(string chromeTime)
        {
            // helper that converts Chrome's stupid timestamp format
            // https://stackoverflow.com/questions/20458406/what-is-the-format-of-chromes-timestamps
            // https://linuxsleuthing.blogspot.com/2011/06/decoding-google-chrome-timestamps-in.html
            DateTime epoch = new DateTime(1601, 1, 1);
            try
            {
                double dateCreatedRaw = double.Parse(chromeTime);
                double secsFromEpoch = dateCreatedRaw / 1000000;
                if (secsFromEpoch > TimeSpan.MaxValue.TotalSeconds)
                {
                    // handle timestamps over the allowed range
                    return new DateTime(DateTime.MaxValue.Ticks);
                }
                if (secsFromEpoch < 0)
                {
                    secsFromEpoch = 0;
                }
                return epoch.Add(TimeSpan.FromSeconds(secsFromEpoch)).ToLocalTime();
            }
            catch
            {
                // in case the parsing fails
                return epoch;
            }
        }

19 Source : NOAA.cs
with GNU General Public License v3.0
from cumulusmx

public List<string> CreateMonthlyReport(DateTime thedate)
		{
			var output = new List<string>();

			CultureInfo culture = replacedulus.NOAAconf.UseDotDecimal ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture;

			Tdaysummary[] dayList = new Tdaysummary[32];

			for (int i = 1; i < 32; i++)
			{
				dayList[i].valid = false;
				dayList[i].totalwindspeed = 0;
				dayList[i].windsamples = 0;
				dayList[i].winddomdir = 0;
				dayList[i].totalwinddirX = 0;
				dayList[i].totalwinddirY = 0;
			}

			double totalheating = 0;
			double totalcooling = 0;
			double totalmeantemp = 0;
			double totalrain = 0;
			double totalwindspeed = 0;
			int windsamples = 0;
			int daycount = 0;
			int maxtempday = 0;
			int mintempday = 0;
			int highwindday = 0;
			double maxtemp = -999;
			double mintemp = 999;
			double meantemp;
			double highwind = 0;
			double totalwinddirX = 0;
			double totalwinddirY = 0;
			int maxtempcount1 = 0;
			int maxtempcount2 = 0;
			int mintempcount1 = 0;
			int mintempcount2 = 0;
			double maxrain = 0;
			int maxrainday = 0;
			int raincount1 = 0;
			int raincount2 = 0;
			int raincount3 = 0;

			int month = thedate.Month;
			int year = thedate.Year;
			int linenum = 0;
			int idx = 0;
			List<string> st = new List<string>();

			try
			{
				var lines = File.ReadAllLines(replacedulus.DayFileName);

				foreach (var line in lines)
				{
					linenum++;
					var sep = Utils.GetLogFileSeparator(line, replacedulus.ListSeparator);
					st = new List<string>(line.Split(sep[0]));
					idx = 0;

					var dateStr = st[0];
					var dat = Utils.ddmmyyStrToDate(dateStr);
					if (dat.Month != month || dat.Year != year)
						continue;

					// entry is for this month (month and year match)
					int daynumber = dat.Day;

					if (dayList[daynumber].valid)
					{
						// already had this date - error!
						replacedulus.LogMessage($"Duplicate entry at line {linenum} of dayfile.txt: {dateStr}. Please correct this by editing the file");
						continue;
					}

					// haven't had this entry yet

					// max temp
					idx = 6;
					dayList[daynumber].maxtemp = double.Parse(st[idx]);
					idx = 7;
					string timestr = st[idx];
					int hour = Convert.ToInt32(timestr.Substring(0, 2));
					int minute = Convert.ToInt32(timestr.Substring(3, 2));
					dayList[daynumber].maxtemptimestamp = DateTime.MinValue.Date.Add(new TimeSpan(hour, minute, 0));
					if (dayList[daynumber].maxtemp > maxtemp)
					{
						maxtemp = dayList[daynumber].maxtemp;
						maxtempday = daynumber;
					}
					if (GreaterThanOrEqual(dayList[daynumber].maxtemp, replacedulus.NOAAconf.MaxTempComp1))
					{
						maxtempcount1++;
					}
					if (LessThanOrEqual(dayList[daynumber].maxtemp, replacedulus.NOAAconf.MaxTempComp2))
					{
						maxtempcount2++;
					}

					// min temp
					idx = 4;
					dayList[daynumber].mintemp = double.Parse(st[idx]);
					idx = 5;
					timestr = st[idx];
					hour = Convert.ToInt32(timestr.Substring(0, 2));
					minute = Convert.ToInt32(timestr.Substring(3, 2));
					dayList[daynumber].mintemptimestamp = DateTime.MinValue.Date.Add(new TimeSpan(hour, minute, 0));
					if (dayList[daynumber].mintemp < mintemp)
					{
						mintemp = dayList[daynumber].mintemp;
						mintempday = daynumber;
					}
					if (LessThanOrEqual(dayList[daynumber].mintemp, replacedulus.NOAAconf.MinTempComp1))
					{
						mintempcount1++;
					}
					if (LessThanOrEqual(dayList[daynumber].mintemp, replacedulus.NOAAconf.MinTempComp2))
					{
						mintempcount2++;
					}

					// mean temp
					if (replacedulus.NOAAconf.UseMinMaxAvg)
					{
						meantemp = (dayList[daynumber].maxtemp + dayList[daynumber].mintemp) / 2.0;
						totalmeantemp += meantemp;
						dayList[daynumber].meantemp = meantemp;
					}
					else if ((st.Count > 15) && (st[15].Length > 0))
					{
						idx = 15;
						meantemp = double.Parse(st[idx]);
						totalmeantemp += meantemp;
						dayList[daynumber].meantemp = meantemp;
					}
					else
					{
						// average temp field not present
						meantemp = -1000;
						dayList[daynumber].meantemp = -1000;
						dayList[daynumber].heatingdegdays = 0;
						dayList[daynumber].coolingdegdays = 0;
					}

					if (meantemp > -1000)
					{
						// heating degree day
						idx = 40;
						if ((st.Count > idx) && (st[idx].Length > 0))
						{
							// read HDD from dayfile.txt
							dayList[daynumber].heatingdegdays = double.Parse(st[idx]);
							totalheating += double.Parse(st[idx]);
						}
						else if (meantemp < replacedulus.NOAAconf.HeatThreshold)
						{
							dayList[daynumber].heatingdegdays = replacedulus.NOAAconf.HeatThreshold - meantemp;
							totalheating += replacedulus.NOAAconf.HeatThreshold - meantemp;
						}
						else
						{
							dayList[daynumber].heatingdegdays = 0;
						}

						// cooling degree days
						idx = 41;
						if ((st.Count > idx) && (st[idx] != string.Empty))
						{
							// read HDD from dayfile.txt
							dayList[daynumber].coolingdegdays = double.Parse(st[idx]);
							totalcooling += double.Parse(st[idx]);
						}
						else if (meantemp > replacedulus.NOAAconf.CoolThreshold)
						{
							dayList[daynumber].coolingdegdays = meantemp - replacedulus.NOAAconf.CoolThreshold;
							totalcooling += meantemp - replacedulus.NOAAconf.CoolThreshold;
						}
						else
						{
							dayList[daynumber].coolingdegdays = 0;
						}
					}

					// rain
					idx = 14;
					dayList[daynumber].rain = double.Parse(st[idx]);
					totalrain += double.Parse(st[idx]);
					if (dayList[daynumber].rain > maxrain)
					{
						maxrain = dayList[daynumber].rain;
						maxrainday = daynumber;
					}

					if (GreaterThanOrEqual(dayList[daynumber].rain, replacedulus.NOAAconf.RainComp1))
					{
						raincount1++;
					}
					if (GreaterThanOrEqual(dayList[daynumber].rain, replacedulus.NOAAconf.RainComp2))
					{
						raincount2++;
					}
					if (GreaterThanOrEqual(dayList[daynumber].rain, replacedulus.NOAAconf.RainComp3))
					{
						raincount3++;
					}

					// high wind speed
					idx = 1;
					dayList[daynumber].highwindspeed = double.Parse(st[idx]);
					idx = 3;
					timestr = st[idx];
					hour = Convert.ToInt32(timestr.Substring(0, 2));
					minute = Convert.ToInt32(timestr.Substring(3, 2));
					dayList[daynumber].highwindtimestamp = DateTime.MinValue.Date.Add(new TimeSpan(hour, minute, 0));
					if (dayList[daynumber].highwindspeed > highwind)
					{
						highwind = dayList[daynumber].highwindspeed;
						highwindday = daynumber;
					}

					// dominant wind bearing
					idx = 39;
					if ((st.Count > idx) && (st[idx] != string.Empty))
					{
						dayList[daynumber].winddomdir = Convert.ToInt32((st[idx]));
					}

					daycount++;
					dayList[daynumber].valid = true;
				}
			}
			catch (Exception ex)
			{
				replacedulus.LogMessage($"Error at line {linenum}, column {idx}, value '{(st.Count >= idx ? st[idx] : "")}' of dayfile.txt: " + ex.Message);
				replacedulus.LogMessage("Please edit the file to correct the error");
			}

			// Calculate average wind speed from log file
			// Use the second of the month in case of 9am roll-over
			var logFile = replacedulus.GetLogFileName(new DateTime(thedate.Year, thedate.Month, 2));

			if (File.Exists(logFile))
			{
				idx = 0;
				int daynumber = 1;

				try
				{
					linenum = 0;
					var lines = File.ReadAllLines(logFile);

					foreach (var line in lines)
					{
						// now process each record in the file
						linenum++;
						var sep = Utils.GetLogFileSeparator(line, replacedulus.ListSeparator);
						st = new List<string>(line.Split(sep[0]));

						idx = 0;
						int entryday = Convert.ToInt32(st[idx].Substring(0, 2));
						int entrymonth = Convert.ToInt32(st[idx].Substring(3, 2));
						int entryyear = Convert.ToInt32(st[idx].Substring(6, 2));
						idx = 1;
						int entryhour = Convert.ToInt32(st[idx].Substring(0, 2));
						int entryminute = Convert.ToInt32(st[idx].Substring(3, 2));

						DateTime entrydate = new DateTime(entryyear, entrymonth, entryday, entryhour, entryminute, 0);

						entrydate = entrydate.AddHours(replacedulus.GetHourInc(entrydate));

						daynumber = entrydate.Day;

						if (!dayList[daynumber].valid)
							continue;

						idx = 5;
						double windspeed = double.Parse(st[idx]);

						// add in wind speed sample for this day
						dayList[daynumber].windsamples++;
						dayList[daynumber].totalwindspeed += windspeed;

						// add in wind speed sample for whole month
						windsamples++;
						totalwindspeed += windspeed;

						// add in direction if (not done already
						if (dayList[daynumber].winddomdir == 0)
						{
							idx = 7;
							int winddir = Convert.ToInt32(st[idx]);
							dayList[daynumber].totalwinddirX += (windspeed * Math.Sin(Trig.DegToRad(winddir)));
							dayList[daynumber].totalwinddirY += (windspeed * Math.Cos(Trig.DegToRad(winddir)));
						}
					}
				}
				catch (Exception ex)
				{
					replacedulus.LogMessage($"Error at line {linenum}, column {idx}, value '{(st.Count >= idx ? st[idx] : "")}' of {logFile} : {ex}");
					replacedulus.LogMessage("Please edit the file to correct the error");
					// set the days after this error as invalid
					for (var i = daynumber; i < dayList.Length - 1; i++)
					{
						dayList[i].valid = false;
					}
				}
			}

			double avgwindspeed;
			if (windsamples > 0)
			{
				avgwindspeed = totalwindspeed/windsamples;
			}
			else
			{
				avgwindspeed = -1000;
			}

			for (int i = 1; i < 32; i++)
			{
				if (dayList[i].windsamples > 0)
					dayList[i].avgwindspeed = dayList[i].totalwindspeed / dayList[i].windsamples;
				else
					dayList[i].avgwindspeed = -1000;

				// calculate dominant wind bearing if (required
				if (dayList[i].winddomdir == 0)
				{
					if (dayList[i].totalwinddirX == 0)
						dayList[i].winddomdir = 0;
					else
					{
						try
						{
							dayList[i].winddomdir = CalcAvgBearing(dayList[i].totalwinddirX, dayList[i].totalwinddirY);// 90 - (int)Math.Floor(RadToDeg(Math.Atan2(DayList[i].totalwinddirY, DayList[i].totalwinddirX)));
								//(int)Math.Floor(RadToDeg(Math.Atan(DayList[i].totalwinddirY / DayList[i].totalwinddirX)));
						}
						catch
						{
							replacedulus.LogMessage("Error in NOAA dominant wind direction calculation ");
						}

						if (dayList[i].winddomdir == 0)
						{
							dayList[i].winddomdir = 360;
						}
					}
				}

				// add up vectors for overall dom dir
				if (dayList[i].windsamples > 0)
					// there"s an average speed available
				{
					totalwinddirX += (dayList[i].avgwindspeed*Math.Sin(Trig.DegToRad(dayList[i].winddomdir)));
					totalwinddirY += (dayList[i].avgwindspeed*Math.Cos(Trig.DegToRad(dayList[i].winddomdir)));
				}
			}

			int overalldomdir;
			try
			{
				overalldomdir = CalcAvgBearing(totalwinddirX, totalwinddirY);

				if (overalldomdir == 0)
					overalldomdir = 360;
			}
			catch
			{
				replacedulus.LogMessage("Error in NOAA dominant wind direction calculation ");
				overalldomdir = 0;
			}

			// Now output everything

			output.Add($"                   Monthly Climatological Summary for {thedate:MMM} {year}");
			output.Add("");
			output.Add($"Name: {replacedulus.NOAAconf.Name}   City: {replacedulus.NOAAconf.City}   State: {replacedulus.NOAAconf.State}");
			string elev;
			if (replacedulus.AlreplacedudeInFeet)
			{
				elev = replacedulus.Alreplacedude + " ft";
			}
			else
			{
				elev = replacedulus.Alreplacedude + " m";
			}

			int latdeg;
			int latmin;
			int latsec;
			DecodeLatLong(Math.Abs(replacedulus.Lareplacedude), out latdeg, out latmin, out latsec);
			int londeg;
			int lonmin;
			int lonsec;
			DecodeLatLong(Math.Abs(replacedulus.Longitude), out londeg, out lonmin, out lonsec);

			var lathem = replacedulus.Lareplacedude > 0 ? "N" : "S";
			var lonhem = replacedulus.Longitude > 0 ? "E" : "W";

			latdeg = Math.Abs(latdeg);
			londeg = Math.Abs(londeg);

			output.Add($"Elevation: {elev}  Lat: {string.Format("{0} {1,2:D2}° {2,2:D2}' {3,2:D2}\"", lathem, latdeg, latmin, latsec)}   Lon: {string.Format("{0} {1,3:D3}° {2,2:D2}' {3,2:D2}\"", lonhem, londeg, lonmin, lonsec)}");
			output.Add("");
			output.Add($"                  Temperature ({replacedulus.Units.TempText}), Rain ({replacedulus.Units.RainText}), Wind Speed ({replacedulus.Units.WindText})");
			output.Add("");
			output.Add("                                      Heat  Cool        Avg");
			output.Add("    Mean                              Deg   Deg         Wind                 Dom");
			output.Add("Day Temp  High   Time   Low    Time   Days  Days  Rain  Speed High   Time    Dir");
			output.Add("----------------------------------------------------------------------------------");

			var repLine = new StringBuilder(200);

			var timeFormat = replacedulus.NOAAconf.Use12hour ? "h:mmtt" : "HH:mm";

			for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++)
			{
				if (dayList[i].valid)
				{
					repLine.Clear();
					repLine.Append(i.ToString("D2"));
					if (dayList[i].meantemp < -999)
					{
						repLine.Append("  ----");
					}
					else
					{
						repLine.Append(string.Format(culture, "{0,6:F1}",dayList[i].meantemp));
					}
					;
					repLine.Append(string.Format(culture, "{0,6:F1}", dayList[i].maxtemp));
					string timestr = dayList[i].maxtemptimestamp.ToString(timeFormat);
					repLine.Append(string.Format("{0,8}", timestr));
					repLine.Append(string.Format(culture, "{0,6:F1}", dayList[i].mintemp));
					timestr = dayList[i].mintemptimestamp.ToString(timeFormat);
					repLine.Append(string.Format("{0,8}", timestr));

					if (dayList[i].meantemp < -999)
					{
						repLine.Append("  ----");
					}
					else
					{
						repLine.Append(string.Format(culture, "{0,6:F1}", dayList[i].heatingdegdays));
						repLine.Append(string.Format(culture, "{0,6:F1}", dayList[i].coolingdegdays));
					}
					repLine.Append(string.Format("{0,6}", dayList[i].rain.ToString(replacedulus.RainFormat, culture)));

					if (dayList[i].avgwindspeed < -999)
						repLine.Append("  ----");
					else
						repLine.Append(string.Format(culture, "{0,6:F1}", dayList[i].avgwindspeed));

					repLine.Append(string.Format(culture, "{0,6:F1}", dayList[i].highwindspeed));
					timestr = dayList[i].highwindtimestamp.ToString(timeFormat);
					repLine.Append(string.Format("{0,8}", timestr));
					repLine.Append(string.Format("{0,6}", CompreplacedPoint(dayList[i].winddomdir)));
					output.Add(repLine.ToString());
				}
			}
			output.Add("----------------------------------------------------------------------------------");

			// Build summary line
			repLine.Clear();
			if (daycount == 0)
			{
				repLine.Append("    ----");
			}
			else
			{
				repLine.Append(string.Format(culture, "{0,8:F1}", totalmeantemp/daycount));
			}

			if (maxtempday == 0)
			{
				repLine.Append("  ----    --");
			}
			else
			{
				repLine.Append(string.Format(culture, "{0,6:F1}", maxtemp));
				repLine.Append(string.Format(culture, "{0,6:D}", maxtempday));
			}

			if (mintempday == 0)
			{
				repLine.Append("    ----    --");
			}
			else
			{
				repLine.Append(string.Format(culture, "{0,8:F1}", mintemp));
				repLine.Append(string.Format(culture, "{0,6:D}", mintempday));
			}

			repLine.Append(string.Format(culture, "{0,8:F1}", totalheating));
			repLine.Append(string.Format(culture, "{0,6:F1}", totalcooling));

			repLine.Append(string.Format("{0,6}", totalrain.ToString(replacedulus.RainFormat, culture)));

			if (avgwindspeed < -999)
			{
				repLine.Append("  ----");
			}
			else
			{
				repLine.Append(string.Format(culture, "{0,6:F1}", avgwindspeed));
			}
			;

			repLine.Append(string.Format(culture, "{0,6:F1}", highwind));
			repLine.Append(string.Format(culture, "{0,6:D}", highwindday));

			repLine.Append(string.Format("{0,8}", CompreplacedPoint(overalldomdir)));

			output.Add(repLine.ToString());

			output.Add("");

			// now do the max/min/days of rain items
			output.Add(string.Format(culture, "Max >={0,6:F1}{1,3:D}", replacedulus.NOAAconf.MaxTempComp1, maxtempcount1));
			output.Add(string.Format(culture, "Max <={0,6:F1}{1,3:D}", replacedulus.NOAAconf.MaxTempComp2, maxtempcount2));
			output.Add(string.Format(culture, "Min <={0,6:F1}{1,3:D}", replacedulus.NOAAconf.MinTempComp1, mintempcount1));
			output.Add(string.Format(culture, "Min <={0,6:F1}{1,3:D}", replacedulus.NOAAconf.MinTempComp2, mintempcount2));

			output.Add($"Max Rain: {maxrain.ToString(replacedulus.RainFormat, culture)} on day {maxrainday}");

			output.Add($"Days of Rain: {raincount1} (>= {replacedulus.NOAAconf.RainComp1.ToString(replacedulus.RainFormat, culture)} {replacedulus.Units.RainText})  {raincount2} (>= {replacedulus.NOAAconf.RainComp2.ToString(replacedulus.RainFormat, culture)} {replacedulus.Units.RainText})  {raincount3} (>= {replacedulus.NOAAconf.RainComp3.ToString(replacedulus.RainFormat, culture)} {replacedulus.Units.RainText})");
			output.Add($"Heat Base: {replacedulus.NOAAconf.HeatThreshold.ToString(replacedulus.TempFormat, culture)}  Cool Base: {replacedulus.NOAAconf.CoolThreshold.ToString(replacedulus.TempFormat, culture)}  Method: Integration");

			return output;
		}

19 Source : MicrosoftAppCredentials.cs
with MIT License
from CXuesong

public static void TrustServiceUrl(string serviceUrl, DateTime expirationTime = default(DateTime))
        {
            try
            {
                if (expirationTime == default(DateTime))
                {
                    // by default the service url is valid for one day
                    var extensionPeriod = TimeSpan.FromDays(1);
                    TrustedHostNames.AddOrUpdate(new Uri(serviceUrl).Host, DateTime.UtcNow.Add(extensionPeriod), (key, oldValue) =>
                    {
                        var newExpiration = DateTime.UtcNow.Add(extensionPeriod);
                        // try not to override expirations that are greater than one day from now
                        if (oldValue > newExpiration)
                        {
                            // make sure that extension can be added to oldValue and ArgumentOutOfRangeException
                            // is not thrown
                            if (oldValue >= DateTime.MaxValue.Subtract(extensionPeriod))
                            {
                                newExpiration = oldValue;
                            }
                            else
                            {
                                newExpiration = oldValue.Add(extensionPeriod);
                            }
                        }
                        return newExpiration;
                    });
                }
                else
                {
                    TrustedHostNames.AddOrUpdate(new Uri(serviceUrl).Host, expirationTime, (key, oldValue) => expirationTime);
                }
            }
            catch (Exception)
            {
#if NET45
                Trace.TraceWarning($"Service url {serviceUrl} is not a well formed Uri!");
#endif
            }
        }

See More Examples