public string FormatStartDate(DateTimeOffset startDateTime)
 {
     var timeOfDay = startDateTime.TimeOfDay;
     return timeOfDay.Hours == 0
                 ? startDateTime.ToString(DateOnlyPattern)
                 : startDateTime.ToString(DateAndTimePattern);
 }
        /// <summary>
        /// 定义将时间点对象 <see cref="System.DateTimeOffset"/> 转换为字符串的方法。
        /// </summary>
        /// <param name="datetimeOffset"></param>
        /// <returns></returns>
        protected override string ToString(DateTimeOffset datetimeOffset)
        {
            if (datetimeOffset.HasDate())
                return datetimeOffset.HasTime() ? base.ToString(datetimeOffset) : datetimeOffset.ToString(this.Culture.DateTimeFormat.ShortDatePattern, this.Culture);
            else if (datetimeOffset.HasTime())
                return datetimeOffset.ToString(this.Culture.DateTimeFormat.ShortTimePattern, this.Culture);

            return base.ToString(datetimeOffset);
        }
Example #3
0
 public HistoryEntry(string id, DateTimeOffset timestamp, string operatorName, string alarmStatus, string alarmState, string response)
 {
     Id = id;
     Timestamp = timestamp.ToString("G", CultureInfo.CurrentCulture);
     SortableTimestamp = timestamp.ToString("s", CultureInfo.InvariantCulture);
     OperatorName = operatorName;
     AlarmStatus = alarmStatus;
     AlarmState = alarmState;
     Response = response;
 }
Example #4
0
        public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
        {
            var            c    = new CultureInfo("ja-JP");
            DateTimeOffset?date = value[0] as DateTimeOffset?;

            if (value[1] is DateTimeOffset retweetedDate)
            {
                return(retweetedDate.ToString("G", c) + "\r\nRT:" + date?.ToString("G", c));
            }
            return(date?.ToString("G", c));
        }
Example #5
0
 /// <summary>
 /// Creates an immutable Case object
 /// </summary>        
 /// <param name="id">Globally unique identifier for the case</param>
 /// <param name="title">Title of the case</param>
 /// <param name="createdBy">User who created the case</param>
 /// <param name="createdDateTime">Time and Date that the case was created</param>
 /// <param name="owner">User who owns the case</param>
 /// <param name="notes">The list of notes on the case</param>
 /// <param name="status">Status of the case</param>
 public Case(string id, string title, string createdBy, DateTimeOffset createdDateTime, string owner, IEnumerable<CaseNote> notes, CaseStatus status)
 {
     Id = id;
     Title = title;
     CreatedBy = createdBy;
     CreatedDateTime = createdDateTime;
     CreatedDateString = CreatedDateTime.ToString("d", CultureInfo.CurrentCulture);
     CreatedTimeString = CreatedDateTime.ToString("t", CultureInfo.CurrentCulture);
     CreatedDateTimeString = CreatedDateTime.ToString("g", CultureInfo.CurrentCulture);
     CreatedDateTimeSortableString = CreatedDateTime.ToString("s", CultureInfo.InvariantCulture);
     Owner = owner;
     Notes = notes.ToList();
     StatusEnum = status;
 }
Example #6
0
 /// <summary>
 /// Creates an immutable message object
 /// </summary>
 /// <param name="id">Message id</param>
 /// <param name="description">Message description</param>
 /// <param name="partitionId">The GUID of the partition the message occurred on</param>
 /// <param name="partitionName">The name of the partition the message occurred on</param>
 /// <param name="isPublic">True if the message is public, otherwise false</param>
 /// <param name="messageDateTime">The Date and Time the message occurred.</param>
 public Message(Guid id, string description, Guid partitionId, string partitionName, bool isPublic, DateTimeOffset messageDateTime)
 {
     Id = id;
     Description = description;
     PartitionId = partitionId;
     PartitionName = partitionName;
     IsPublic = isPublic;
     MessageDateTime = messageDateTime;
     MessageDateString = MessageDateTime.ToString("d", CultureInfo.CurrentCulture);
     MessageTimeString = MessageDateTime.ToString("t", CultureInfo.CurrentCulture);
     MessageDateTimeString = MessageDateTime.ToString("G", CultureInfo.CurrentCulture);
     MessageDateTimeSortableString = MessageDateTime.ToString("s", CultureInfo.InvariantCulture);
     MessageUtcDateTime = (long) (MessageDateTime.UtcDateTime - new DateTime(1970,1,1,0,0,0,0,DateTimeKind.Utc)).TotalMilliseconds;
 }
        public void DateTimeOffsetScenarioShouldFail()
        {
            var date = new DateTimeOffset(new DateTime(2000, 6, 1), TimeSpan.Zero);
            var dateString = date.ToString();
            var exptected = new DateTimeOffset(new DateTime(2000, 6, 1, 1, 0, 1), TimeSpan.Zero);
            var expectedDate = exptected.ToString();
            Verify.ShouldFail(() =>
date.ShouldBe(exptected, TimeSpan.FromHours(1), "Some additional context"),

errorWithSource:
$@"date
    should be within
01:00:00
    of
{expectedDate}
    but was
{dateString}

Additional Info:
    Some additional context",

errorWithoutSource:
$@"{dateString}
    should be within
01:00:00
    of
{expectedDate}
    but was not

Additional Info:
    Some additional context");
        }
        public void SerializationTests_DateTimeOffset()
        {
            // Local Kind
            DateTime inputLocalDateTime = DateTime.Now;
            DateTimeOffset inputLocal = new DateTimeOffset(inputLocalDateTime);

            DateTimeOffset outputLocal = SerializationManager.RoundTripSerializationForTesting(inputLocal);
            Assert.AreEqual(inputLocal, outputLocal, "Local time");
            Assert.AreEqual(
                inputLocal.ToString(CultureInfo.InvariantCulture),
                outputLocal.ToString(CultureInfo.InvariantCulture));
            Assert.AreEqual(inputLocal.DateTime.Kind, outputLocal.DateTime.Kind);

            // UTC Kind
            DateTime inputUtcDateTime = DateTime.UtcNow;
            DateTimeOffset inputUtc = new DateTimeOffset(inputUtcDateTime);

            DateTimeOffset outputUtc = SerializationManager.RoundTripSerializationForTesting(inputUtc);
            Assert.AreEqual(inputUtc, outputUtc, "UTC time");
            Assert.AreEqual(
                inputUtc.ToString(CultureInfo.InvariantCulture),
                outputUtc.ToString(CultureInfo.InvariantCulture));
            Assert.AreEqual(inputUtc.DateTime.Kind, outputUtc.DateTime.Kind);

            // Unspecified Kind
            DateTime inputUnspecifiedDateTime = new DateTime(0x08d27e2c0cc7dfb9);
            DateTimeOffset inputUnspecified = new DateTimeOffset(inputUnspecifiedDateTime);

            DateTimeOffset outputUnspecified = SerializationManager.RoundTripSerializationForTesting(inputUnspecified);
            Assert.AreEqual(inputUnspecified, outputUnspecified, "Unspecified time");
            Assert.AreEqual(
                inputUnspecified.ToString(CultureInfo.InvariantCulture),
                outputUnspecified.ToString(CultureInfo.InvariantCulture));
            Assert.AreEqual(inputUnspecified.DateTime.Kind, outputUnspecified.DateTime.Kind);
        }
Example #9
0
        /// <summary>
        /// Generates a token that can be used for sharing a Realm.
        /// </summary>
        /// <returns>
        /// A token that can be shared with another user, e.g. via email or message and then consumed by
        /// <see cref="AcceptPermissionOfferAsync"/> to obtain permissions to a Realm.</returns>
        /// <param name="realmPath">The Realm URL whose permissions settings should be changed. Use <c>*</c> to change the permissions of all Realms managed by this <see cref="User"/>.</param>
        /// <param name="accessLevel">
        /// The access level to grant matching users. Note that the access level setting is absolute, i.e. it may revoke permissions for users that
        /// previously had a higher access level. To revoke all permissions, use <see cref="AccessLevel.None" />
        /// </param>
        /// <param name="expiresAt">Optional expiration date of the offer. If set to <c>null</c>, the offer doesn't expire.</param>
        public async Task <string> OfferPermissionsAsync(string realmPath, AccessLevel accessLevel, DateTimeOffset?expiresAt = null)
        {
            if (string.IsNullOrEmpty(realmPath))
            {
                throw new ArgumentNullException(nameof(realmPath));
            }

            if (expiresAt < DateTimeOffset.UtcNow)
            {
                throw new ArgumentException("The expiration date may not be in the past", nameof(expiresAt));
            }

            if (accessLevel == AccessLevel.None)
            {
                throw new ArgumentException("The access level may not be None", nameof(accessLevel));
            }

            var payload = new Dictionary <string, object>
            {
                ["expiresAt"]   = expiresAt?.ToString("O"),
                ["realmPath"]   = realmPath,
                ["accessLevel"] = accessLevel.ToString().ToLower()
            };

            var result = await MakePermissionRequestAsync(HttpMethod.Post, "permissions/offers", payload);

            return(result.ToObject <PermissionOffer>().Token);
        }
Example #10
0
 public RepositoryInfo(Repository repository, DateTimeOffset commitDate, string hash)
 {
     ProjectName = repository.Name;
     ProjectId = repository.Id;
     Date = commitDate.ToString("yyyy-MM-dd");
     Hash = hash;
 }
Example #11
0
        /// <summary>
        ///   Determines if the time is in the specified time period.
        /// </summary>
        /// <param name="now">
        ///   The time to compare.
        /// </param>
        /// <param name="inclusiveStart">The inclusive start time.</param>
        /// <param name="exclusiveEnd">The exclusive end time.</param>
        /// <returns>
        ///   <b>true</b> if <paramref name="now"/> within the specified period; otherwise <b>false</b>.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">
        ///   <paramref name="exclusiveEnd"/> must be greater than <paramref name="inclusiveStart"/>.
        /// </exception>
        /// <example>
        ///   <code title="Credit Card Check" source="SepiaExamples\TimeExample.cs" region="Credit Card Check" language="C#" />
        /// </example>
        public static bool Between(this DateTimeOffset now, DateTimeOffset inclusiveStart, DateTimeOffset exclusiveEnd)
        {
            if (exclusiveEnd <= inclusiveStart)
                throw new ArgumentOutOfRangeException("end", exclusiveEnd.ToString("o"), string.Format("The end must be greater than the start '{0:o}'.", inclusiveStart));

            return inclusiveStart <= now && now < exclusiveEnd;
        }
Example #12
0
        private void LogScheduledTaskRun()
        {
            var intervalString = _intervalOrOffsetFromNow?.ToString() ??
                                 _scheduledTimeAsDateTimeOffset?.ToString() ?? _scheduledTime?.ToString() ?? _crontab;

            Console.WriteLine($"Running Scheduled Task with interval: {intervalString}");
        }
Example #13
0
        public ListAllTicketsRequest(
            ListAllTicketsFilter?filter = null,
            long?requesterId            = null,
            string?requesterEmail       = null,
            long?companyId = null,
            DateTimeOffset?updatedSince   = null,
            TicketIncludes?includes       = default,
            TicketOrderBy?orderBy         = default,
            TicketOrderDirection?orderDir = default)
        {
            var urlParams = new Dictionary <string, string?>
            {
                { "filter", filter?.QueryParameterValue() },
                { "requester_id", requesterId?.ToString() },
                { "email", requesterEmail },
                { "company_id", companyId?.ToString() },
                { "updated_since", updatedSince?.ToString("yyyy-MM-ddTHH:mm:ssZ") },
                { "include", includes?.ToString() },
                { "order_by", orderBy?.QueryParameterValue() },
                { "order_type", orderDir?.QueryParameterValue() }
            }.Where(x => x.Value != null)
            .Select(queryParam => $"{queryParam.Key}={Uri.EscapeDataString(queryParam.Value)}")
            .ToList();

            UrlWithQueryString = ListAllTicketsUrl +
                                 (urlParams.Any() ? "?" + string.Join("&", urlParams) : "");
        }
        internal void ProcessRequest(ResourceSession rpResourceSession, Session rpSession)
        {
            if (CurrentMode == CacheMode.Disabled)
                return;

            string rFilename;
            var rNoVerification = CheckFileInCache(rpResourceSession.Path, out rFilename);

            rpResourceSession.CacheFilename = rFilename;

            if (rNoVerification == null)
                return;

            if (!rNoVerification.Value)
            {
                var rTimestamp = new DateTimeOffset(File.GetLastWriteTime(rFilename));

                if (rpResourceSession.Path.OICContains("mainD2.swf") || rpResourceSession.Path.OICContains(".js") || !CheckFileVersionAndTimestamp(rpResourceSession, rTimestamp))
                {
                    rpSession.oRequest["If-Modified-Since"] = rTimestamp.ToString("R");
                    rpSession.bBufferResponse = true;

                    return;
                }
            }

            rpSession.utilCreateResponseAndBypassServer();
            LoadFile(rFilename, rpResourceSession, rpSession);
        }
Example #15
0
 internal SessionPreview(UserPreview user, string token, DateTimeOffset?expiresAt, bool?requireMfa)
 {
     this.IsAuthenticated = user != null;
     this.User            = user;
     this.Token           = token;
     this.ExpiresAt       = expiresAt?.ToString("yyyy-MM-ddTHH:mm:sszzz");
     this.RequiresMfa     = requireMfa;
 }
        public static void ConvertTo_WithContext()
        {
            DateTimeFormatInfo formatInfo = (DateTimeFormatInfo)CultureInfo.CurrentCulture.GetFormat(typeof(DateTimeFormatInfo));
            string formatWithTime = formatInfo.ShortDatePattern + " " + formatInfo.ShortTimePattern + " zzz";
            string format = formatInfo.ShortDatePattern + " zzz";
            DateTimeOffset testDateAndTime = new DateTimeOffset(new DateTime(1998, 12, 5, 22, 30, 30));

            ConvertTo_WithContext(new object[5, 3]
                {
                    { DateTimeOffsetConverterTests.s_testOffset, DateTimeOffsetConverterTests.s_testOffset.ToString(format, CultureInfo.CurrentCulture), null },
                    { testDateAndTime, testDateAndTime.ToString(formatWithTime, CultureInfo.CurrentCulture), null },
                    { DateTimeOffset.MinValue, string.Empty, null },
                    { DateTimeOffsetConverterTests.s_testOffset, DateTimeOffsetConverterTests.s_testOffset.ToString("yyyy-MM-dd zzz", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture },
                    { testDateAndTime, testDateAndTime.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture }
                },
                DateTimeOffsetConverterTests.s_converter);
        }
Example #17
0
        private string CreateNonce(DateTimeOffset?timestamp = null)
        {
            var privateKey   = Options.PrivateKey;
            var timestampStr = timestamp?.ToString() ?? DateTimeOffset.UtcNow.ToString();

            return(Convert.ToBase64String(
                       _encoding.GetBytes($"{timestampStr} {$"{timestampStr}:{privateKey}".ToMd5Hash()}")));
        }
Example #18
0
 internal static string ToAtomString(DateTimeOffset dateTime)
 {
     if (dateTime.Offset == zeroOffset)
     {
         return dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
     }
     return dateTime.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture);
 }
        private string PrintNetworkUsage(NetworkUsage networkUsage, DateTimeOffset startTime)
        {
            string result = "Usage from " + startTime.ToString() + " to " + (startTime + networkUsage.ConnectionDuration).ToString() +
                "\n\tBytes sent: " + networkUsage.BytesSent +
                "\n\tBytes received: " + networkUsage.BytesReceived + "\n";

            return result;
        }
 private string AsString(DateTimeOffset dateTime)
 {
     if (dateTime.Offset == zeroOffset)
     {
         return dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
     }
     return dateTime.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture);
 }
        public void SetVersion(DateTimeOffset version, IDictionary<string, string> metadata)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }

            metadata[VersionMetadataKey] = version.ToString("o", CultureInfo.InvariantCulture);
        }
        private string PrintNetworkUsage(AttributedNetworkUsage networkUsage, DateTimeOffset startTime, DateTimeOffset endTime)
        {
            string result = "Usage by " + networkUsage.AttributionName +
                "\n\tFrom: " + startTime.ToString() + " to " + endTime.ToString() +
                "\n\tBytes sent: " + networkUsage.BytesSent +
                "\n\tBytes received: " + networkUsage.BytesReceived + "\n";

            return result;
        }
        private string BuildCalendarUri(DateTimeOffset startDate, DateTimeOffset endDate)
        {
            string start = startDate.ToString("O");
            string end = endDate.ToString("O");

            string uri = $"calendarview?startDateTime={start}&endDateTime={end}";
            uri += "&$orderby=start/dateTime";

            return uri;
        }
        /// <summary>
        /// Wandelt eine Zeitangabe im DateTimeOffset Format um in einen String, um sie in einer
        /// SQLite Datenbank zu speichern.
        /// </summary>
        /// <param name="datetime">Das umzuwandelnde Datum mit zugehöriger Uhrzeit und Zeitzonenoffset.</param>
        /// <returns>Das Ergebnis der Umwandlung als String.</returns>
        public static string DateTimeToSQLite(DateTimeOffset datetime)
        {
            string dateTimeFormat = string.Empty;
            
            dateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzzz";
            CultureInfo cultureInfo = new CultureInfo("de-DE");
            string datetimeString = datetime.ToString(dateTimeFormat, cultureInfo);

            return datetimeString;
        }
Example #25
0
 public async Task SetCurrentTimeAsync(DateTimeOffset UtcTime, int OffsetInMinute)
 {
     var req = new TimeOffset
     {
         DateTime = UtcTime.ToString("yyyy-MM-ddTHH:mm:ssZ"),
         TimeZoneOffsetMinute = OffsetInMinute,
         DstOffsetMinute = 0
     };
     await NoValue(RequestGenerator.Serialize("setCurrentTime", ApiVersion.V1_0, req)).ConfigureAwait(false); ;
 }
        private String BuildCalendarUri(DateTimeOffset startDate, DateTimeOffset endDate)
        {
            string start = startDate.ToString("O");
            string end = endDate.ToString("O");

            string uri = string.Format("calendarview?startDateTime={0}&endDateTime={1}", start, end);
            uri += "&$orderby=start/dateTime";

            return uri;
        }
 private string AsString(DateTimeOffset dateTime)
 {
     if (dateTime.Offset == Atom10FeedFormatter.zeroOffset)
     {
         return dateTime.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss Z", CultureInfo.InvariantCulture);
     }
     StringBuilder builder = new StringBuilder(dateTime.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture));
     builder.Remove(builder.Length - 3, 1);
     return builder.ToString();
 }
        internal static DateTimeOffset?RoundToSeconds(DateTimeOffset?expectedIssuedUtc)
        {
            var expectedIssuedUtcAsString = expectedIssuedUtc?.ToString("r", CultureInfo.InvariantCulture);

            var expectedResult = DateTimeOffset.TryParseExact(expectedIssuedUtcAsString, "r", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var result)
                ? new DateTimeOffset?(result)
                : new DateTimeOffset?();

            return(expectedResult);
        }
Example #29
0
        private string GetTimestampString(DateTime? timestamp)
        {
            if (timestamp.HasValue)
            {
                DateTime local =
                    new DateTimeOffset(timestamp.Value).ToLocalTime().DateTime;
                return local.ToString("g");
            }

            return string.Empty;
        }
Example #30
0
 public void TrackLastCommitTimestampQuery(string indexName, DateTimeOffset?lastCommitTimestamp, TimeSpan elapsed)
 {
     _telemetryClient.TrackMetric(
         Prefix + "LastCommitTimestampQueryMs",
         elapsed.TotalMilliseconds,
         new Dictionary <string, string>
     {
         { "IndexName", indexName },
         { "LastCommitTimestamp", lastCommitTimestamp?.ToString("O") },
     });
 }
Example #31
0
        public string GetDateNthFormat(DateTimeOffset dateTimeOffset)
        {
            var ending = string.Empty;

            if (dateTimeOffset.Day.ToString().EndsWith("1"))
            {
                ending = dateTimeOffset.Day.ToString().StartsWith("1") && dateTimeOffset.Day != 1 ? "th" : "st";
            }
            else if (dateTimeOffset.Day.ToString().EndsWith("2"))
            {
                ending = dateTimeOffset.Day.ToString().StartsWith("1") ? "th" : "nd";
            }
            else if (dateTimeOffset.Day.ToString().EndsWith("3"))
            {
                ending = dateTimeOffset.Day.ToString().StartsWith("1") ? "th" : "rd";
            }
            else
                ending = "th";
            return string.Format("{0} {1}{2}", dateTimeOffset.ToString("MMM", System.Globalization.DateTimeFormatInfo.InvariantInfo), dateTimeOffset.ToString("dd"), ending);
        }
Example #32
0
 static string TryFormat(DateTimeOffset dateTime, string format)
 {
     try
     {
         return dateTime.ToString(format);
     }
     catch (FormatException)
     {
         return null;
     }
 }
Example #33
0
        public static string GetBugFixedDateTimeOffset(Expression expression)
        {
            string dateTimePartStr = StripCurleyBraces(expression.DataMembers.Item(2).Value);
            string offsetPartStr = StripCurleyBraces(expression.DataMembers.Item(11).Value);

            TimeSpan offset = TimeSpan.Parse(offsetPartStr);
            DateTime dateTime = DateTime.Parse(dateTimePartStr);

            DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime, offset);

            return dateTimeOffset.ToString();
        }
Example #34
0
        /// <summary>
        /// Creates an immutable Alarm object
        /// </summary>
        /// <param name="id">Event id</param>
        /// <param name="description">Description of the Alarm</param>
        /// <param name="partitionId">The Id of the partition the event occurred on</param>
        /// <param name="partitionName">The name of the partition the event occurred on</param>
        /// <param name="isPublic">True if the event is public, otherwise false</param>
        /// <param name="messageDateTime">The Date and Time the alarm occurred.</param>
        /// <param name="alarmTypeDescription">The name of the alarm type</param>
        /// <param name="category">The category of the alarm</param>
        /// <param name="priority">The alarms priority</param>
        /// <param name="isResponseRequired">True if the alarm requires a response, otherwise false</param>
        /// <param name="isAcknowledgeRequired">True if the alarm requires acknowledgement, otherwise false</param>
        /// <param name="alarmState">The ID of the AlarmState or condition</param>
        /// <param name="alarmStateDescription">The name of the AlarmState or condition</param>
        /// <param name="stateDateTime">The timestamp of the last time the AlarmState change</param>
        /// <param name="conditionSequence">incremented every time the triggering item changes state</param>
        /// <param name="site">The site object from which the alarm was generated.</param>
        /// <param name="sourceState">The ID of the source state.</param>
        /// <param name="sourceStateDescription">The source state description.</param>
        /// <param name="escalation">The escalation level of the alarm.</param>
        /// <param name="instructions">The instructions given with this alarm.</param>
        /// <param name="isPublicDescription">The text description for the IsPublic field.</param>
        /// <param name="isPending">True if the Alarm is in a Pending state, otherwise false</param>
        /// <param name="isCompletable">True if the Alarm can be Completed, otherwise false</param>
        /// <param name="isRespondable">True if one can Respond to the Alarm, otherwise false</param>
        /// <param name="isRemovable">True if the Alarm can be Removed, otherwise false</param>
        /// <param name="isCompleted">True if the Alarm can be completed, otherwise false</param>
        public Alarm(Guid id, string description, Guid partitionId, string partitionName, bool isPublic, DateTimeOffset messageDateTime,
            string alarmTypeDescription, string category, int priority, bool isResponseRequired, bool isAcknowledgeRequired,
            int alarmState, string alarmStateDescription, DateTimeOffset stateDateTime, int conditionSequence, string site,
            int sourceState, string sourceStateDescription, int escalation, string instructions, string isPublicDescription,
            bool isPending,
            bool isCompletable,
            bool isRespondable,
            bool isRemovable,
            bool isCompleted
            )
            : base(id, description, partitionId, partitionName, isPublic, messageDateTime)
        {
            AlarmState = alarmState;
            AlarmStateDescription = alarmStateDescription;
            StateDateTime = stateDateTime;
            StateDateString = StateDateTime.ToString("d", CultureInfo.CurrentCulture);
            StateTimeString = StateDateTime.ToString("t", CultureInfo.CurrentCulture);
            StateDateTimeString = StateDateTime.ToString("G", CultureInfo.CurrentCulture);
            StateDateTimeSortableString = StateDateTime.ToString("s", CultureInfo.InvariantCulture);
            ConditionSequence = conditionSequence;

            IsAcknowledgeRequired = isAcknowledgeRequired;
            IsResponseRequired = isResponseRequired;
            Priority = priority;
            Category = category;
            AlarmTypeDescription = alarmTypeDescription;
            SourceState = sourceState;
            SourceStateDescription = sourceStateDescription;
            Site = site;
            Escalation = escalation;
            Instructions = instructions;
            IsPublicDescription = isPublicDescription;

            IsPending = isPending;
            IsCompletable = isCompletable;
            IsRespondable = isRespondable;
            IsRemovable = isRemovable;
            IsCompleted = isCompleted;
        }
        public void Visit_DateTimeOffset_constant_expression_generates_correct_key()
        {
            var dateTime = DateTime.Now;
            var dateTimeOffset = new DateTimeOffset(dateTime);

            var keyGen = new ExpressionKeyGen();
            keyGen.Visit(DbExpressionBuilder.Constant(dateTimeOffset));

            var expectedKey = dateTimeOffset.ToString("o")
                + ":Edm.DateTimeOffset(Nullable=True,DefaultValue=,Precision=)";

            Assert.Equal(expectedKey, keyGen.Key);
        }
        /// <summary>
        /// Gets the currently featured map, if any.
        /// </summary>
        /// <param name="table">The Azure table to use.</param>
        /// <param name="featuredDate">The featured date to use.</param>
        /// <returns>Returns the currently featured map.</returns>
        public static async Task<MapEntity> GetFeaturedMap(this AzureTable<MapEntity> table, DateTimeOffset featuredDate)
        {
            Guard.NotNull(() => table);
            Guard.NotNull(() => featuredDate);

            TableQuery<MapEntity> query = new TableQuery<MapEntity>().Where(
                TableQuery.CombineFilters(
                    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, MapEntity.FeaturedKey),
                    TableOperators.And,
                    TableQuery.GenerateFilterCondition("FeaturedDate", QueryComparisons.Equal, featuredDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))));

            return (await table.GetFromQuery(query)).FirstOrDefault();
        }
 /// <summary>
 /// Gets the parameters.
 /// </summary>
 /// <param name="jobName">Name of the job.</param>
 /// <param name="scheduledTime">The scheduled time.</param>
 /// <returns></returns>
 private object GetParameters(string jobName,
     DateTimeOffset scheduledTime)
 {
     return new
     {
         JobJey = (RedisKey) RedisNames.JobNames,
         JobName = jobName,
         StatusKey = (RedisKey) RedisNames.Status,
         JobEventKey = (RedisKey) RedisNames.JobEvent,
         JobNameScheduled = string.Concat(jobName, "|scheduled"),
         ScheduledTime = scheduledTime.ToString(System.Globalization.CultureInfo.InvariantCulture)
     };
 }
        public ReportControllerTests()
        {
            TestCallsigns = new List<string>(Fixture.CreateMany<string>());
            TestCallsign = TestCallsigns.First();
            TestReadingsSet1 = new List<LocationRecord>(Fixture.CreateMany<LocationRecord>());
            TestReadingsSet2 = new List<LocationRecord>(Fixture.CreateMany<LocationRecord>());
            TestDate = Fixture.Create<DateTimeOffset>().Date;
            TestDateString = TestDate.ToString("yyyyMMdd");
            BadDate = Fixture.Create<string>();

            TestLogEntries = new List<LogEntry>(Fixture.Build<LogEntry>().With(p => p.Type, LogEventType.UserLogIn).Without(l => l.Properties).CreateMany());
            TestLogEntries.AddRange(Fixture.Build<LogEntry>().With(p => p.Type, LogEventType.UnknownEvent).Without(l => l.Properties).With(l => l.Date, DateTimeOffset.Now.Date).CreateMany());
        }
Example #39
0
        private void logOutOfBoundsDate(DateTimeOffset?oldTime, DateTimeOffset?newTime, string startOrStopDate, string source)
        {
            var properties = new Dictionary <string, string>
            {
                { "Old Time", oldTime?.ToString() },
                { "New Time", newTime?.ToString() },
                { "Start or Stop", startOrStopDate },
                { "Source", source }
            };
            var exception = new OutOfBoundsDateTimeCreatedException("An out of bounds date was created", Environment.StackTrace);

            analyticsService.Track(exception, properties);
        }
Example #40
0
        public async Task Stats()
        {
            try {
                IUser user = Context.User;

                string uname     = user.Username ?? "?";
                string nick      = (user as IGuildUser).Nickname ?? "/";
                string createdAt = user.CreatedAt.ToString("d") ?? "/";

                DateTimeOffset?joinedAtDate = (user as IGuildUser).JoinedAt;
                string         joinedAt;
                if (joinedAtDate != null)
                {
                    joinedAt = joinedAtDate?.ToString("d");
                }
                else
                {
                    joinedAt = "/";
                }
                string status       = user.Status.ToString() ?? "/";
                Game?  nullableGame = user.Game;
                string game;
                if (nullableGame != null)
                {
                    game = nullableGame?.ToString();
                }
                else
                {
                    game = "/";
                }
                string xp = XpManager.Get(user).Xp.ToString();

                EmbedBuilder builder = new EmbedBuilder {
                    Author = new EmbedAuthorBuilder {
                        Name    = user.IsBot ? $"{uname} (Bot)" : $"{uname}",
                        IconUrl = user.GetAvatarUrl()
                    },
                    Color = new Color(50, 125, 0)
                };
                builder.AddField("Nickname", nick);
                builder.AddField("Created At", createdAt);
                builder.AddField("Joined At", joinedAt);
                builder.AddField("Status", status);
                builder.AddField("Game", game);
                builder.AddField("XP", xp);

                await ReplyAsync("", embed : builder.Build());
            } catch (Exception ex) {
                await ReplyAsync($"Error! ({ex.Message})");
            }
        }
Example #41
0
 public static Uri DayAveragePrice(
     string fsym,
     string tsym,
     string e,
     DateTimeOffset?toTs,
     CalculationType?avgType,
     int?UTCHourDiff,
     bool?tryConversion)
 {
     return(new Uri(MinApiEndpoint, "dayAvg").ApplyParameters(
                new Dictionary <string, string>
     {
         { nameof(fsym), fsym },
         { nameof(tsym), tsym },
         { nameof(e), e },
         { nameof(toTs), toTs?.ToString() },
         { nameof(avgType), avgType?.ToString() },
         { nameof(UTCHourDiff), UTCHourDiff?.ToString() },
         { nameof(tryConversion), tryConversion?.ToString() },
     }));
 }
        public ListAllContactsRequest(
            string email                = null,
            string mobile               = null,
            string phone                = null,
            long?companyId              = null,
            ContactState?contactState   = null,
            DateTimeOffset?updatedSince = null)
        {
            var urlParams = new Dictionary <string, string>
            {
                { "email", email },
                { "mobile", mobile },
                { "phone", phone },
                { "companyId", companyId?.ToString() },
                { "state", contactState?.GetQueryStringValue() },
                { "updated_since", updatedSince?.ToString("yyyy-MM-ddTHH:mm:ssZ") }
            }.Where(x => x.Value != null)
            .Select(queryParam => $"{queryParam.Key}={Uri.EscapeDataString(queryParam.Value)}")
            .ToList();

            UrlWithQueryString = ListAllContactsUrl +
                                 (urlParams.Any() ? "?" + string.Join("&", urlParams) : "");
        }
        private async Task GetLogEntries(DateTimeOffset?date)
        {
            var controller = CreateController();

            var result = await controller.LogEntries(date?.ToString("yyyyMMdd"));

            var actualDate     = date ?? DateTimeOffset.Now.Date;
            var expectedResult = TestLogEntries.Where(l => l.Date == actualDate.Date).ToList();

            Assert.IsType <JsonResult <IEnumerable <LogEntryViewModel> > >(result);

            var res = result as JsonResult <IEnumerable <LogEntryViewModel> >;

            Assert.NotNull(res);

            foreach (var r in res.Content)
            {
                var original = expectedResult.First(l => l.Id == r.Id);

                Assert.Equal(original.Date, r.Date);
                Assert.Equal(LogFormatter.FormatLogEntry(original), r.Message);
                Assert.Equal(original.SourceUser, r.User);
            }
        }
 public TimeEntriesTotalsParameters(long userId, DateTimeOffset startDate, DateTimeOffset?endDate)
 {
     this.userId = userId;
     StartDate   = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
     EndDate     = endDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
 }
Example #45
0
 public string ToString(DateTimeOffset?date)
 {
     return(date?.ToString(CultureInfo.InvariantCulture));
 }
Example #46
0
 internal string FormatHeader(DateTimeOffset?expires)
 {
     return(expires?.ToString("R"));
 }
 public ProjectsSummaryParameters(DateTimeOffset startDate, DateTimeOffset?endDate)
 {
     StartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
     EndDate   = endDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
 }
Example #48
0
 /// <summary>
 /// 显示为yyyy-MM-dd HH:mm:ss。
 /// </summary>
 /// <param name="dateTime">当前日期实例。</param>
 /// <returns>返回yyyy-MM-dd HH:mm:ss格式的日期字符串。</returns>
 public static string ToNormalString(this DateTimeOffset?dateTime) => dateTime?.ToString("G");
Example #49
0
 public ApiException(string message, DateTimeOffset?dateTimeOffset)
     : base(message)
 {
     Uuid = null;
     Name = dateTimeOffset?.ToString("g", CultureInfo.CurrentCulture);
 }
Example #50
0
 private void WriteDowntimeDebugMessage(DateTimeOffset?downtimeEvent, string downtimeEventDescription)
 {
     Utilities.WriteDebug($"Downtime {downtimeEventDescription} {downtimeEvent?.ToString() ?? "not"} found.", Log, LogLevel);
 }
Example #51
0
 public TimeEntriesTotalsParameters(DateTimeOffset startDate, DateTimeOffset?endDate)
 {
     StartDate = startDate.ToString("yyyy-MM-dd");
     EndDate   = endDate?.ToString("yyyy-MM-dd");
 }
Example #52
0
        public static async Task <ICommandResult> Analytics(DiscordUserMessageContext context, bool includeMessageText = false)
        {
            await(await context.Channel.SendMessageAsync("This is going to take a while")).AddReactionAsync(CommandTools.LoadingEmote);

            using (context.Channel.EnterTypingState())
            {
                // Channel Name => User Name => Date => Hour
                List <string> data = new List <string>();
                data.Add($"MessageID\tChannel\tUser\tIsBot\tTimestamp\tUnixTimestamp\tEditedTimestamp\tUnixEditedTimestamp\tMessageLength\tEmbedType\tHasAttachment\tReactionCount{(includeMessageText ? "\tMessage Text" : "")}");
                var channels = await context.Guild.GetTextChannelsAsync();

                foreach (ITextChannel channel in channels)
                {
                    ChannelPermissions permissions = (await context.Guild.GetCurrentUserAsync()).GetPermissions(channel);
                    if (!permissions.ViewChannel || !permissions.ReadMessageHistory)
                    {
                        continue;
                    }

                    var pages = channel.GetMessagesAsync(int.MaxValue);
                    pages.ForEach(
                        page =>
                    {
                        foreach (IMessage message in page)
                        {
                            var timestampLocal = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(message.Timestamp, context.Bot.DefaultTimeZone);
                            DateTimeOffset?editedTimestampLocal = null;
                            if (message.EditedTimestamp != null)
                            {
                                editedTimestampLocal = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(message.EditedTimestamp.Value, context.Bot.DefaultTimeZone);
                            }
                            data.Add($"{message.Id}\t{message.Channel.Name}\t{message.Author}\t{message.Author.IsBot}\t{timestampLocal.DateTime:G}\t{timestampLocal.ToUnixTimeSeconds()}\t{editedTimestampLocal?.ToString("G") ?? ""}\t{editedTimestampLocal?.ToUnixTimeSeconds().ToString() ?? ""}\t{new System.Globalization.StringInfo(message.Content).LengthInTextElements}\t{message.Embeds.FirstOrDefault()?.Type.ToString() ?? ""}\t{message.Attachments.Count > 0}\t{(message as IUserMessage)?.Reactions.Count ?? 0}{(includeMessageText ? $"\t{message.Content.Replace("\n", "␊").Replace("\r", "")}" : "")}");
                        }
                    });
                }

                File.WriteAllLines(Config.BasePath + $"analytics-{context.Guild.Id}.txt", data);

                if (!includeMessageText)
                {
                    using (var stream = File.OpenRead(Config.BasePath + $"analytics-{context.Guild.Id}.txt"))
                    {
                        await context.Channel.SendFileAsync(stream, $"analytics-{context.Guild.Id}-{DateTimeOffset.Now.ToUnixTimeSeconds()}.txt");
                    }
                }
                else
                {
                    await context.Reply($"Finished creating analytics file. Saved as `analytics-{context.Guild.Id}.txt` ({Math.Round(new FileInfo(Config.BasePath + $"analytics-{context.Guild.Id}.txt").Length / 1048576d, 2)} MB)");
                }
            }
            return(new SuccessResult());
        }
Example #53
0
 ///<inheritdoc/>
 public void SetExpire(DateTimeOffset?value)
 {
     _context.Response.Headers["Expires"] = value?.ToString("r", CultureInfo.InvariantCulture);
 }
Example #54
0
 public static string Serialize(DateTimeOffset?value)
 {
     return(value?.ToString("o"));
 }
 public ProjectsSummaryParameters(DateTimeOffset startDate, DateTimeOffset?endDate)
 {
     StartDate = startDate.ToString("yyyy-MM-dd");
     EndDate   = endDate?.ToString("yyyy-MM-dd");
 }
Example #56
0
 public static string ToNaString(this DateTimeOffset?date, string format)
 {
     return(date?.ToString(format) ?? "n/a");
 }
        //public string publisher;
        //public string platform;
        //public string genre;

        public override string ToString()
        {
            return($"Game: {video_gameLabel.Substring(0, Math.Min(video_gameLabel.Length, 40)),-40} published {publication_date?.ToString("yyyy-MM-dd")}");
        }
Example #58
0
 public static string PrintDateTimeOffset(DateTimeOffset?value)
 {
     return(value?.ToString(DateTimeTzFormat));
 }
Example #59
0
 public static string FormatValue(DateTimeOffset?value, CultureInfo culture = null) => value?.ToString(culture ?? CultureInfo.CurrentCulture);
Example #60
0
 public static string ToFormattedString(this DateTimeOffset?dateTimeOffset)
 => dateTimeOffset?.ToString("r");