private Task<ChartData> GetSQLDatabaseChartData(TimeSpan interval) {
            var client = SQLDatabaseUsageClient.CreateServerUsagesClient(_path[0], SqlCredentialsProvider(_path[0]).Username, SqlCredentialsProvider(_path[0]).Password);
            var usages = client.GetUsages(DateTime.UtcNow.Add(interval.Negate()));

            var serverName = _path[0];
            var counter = _path[_path.Length-1];
            var database = _path[_path.Length-2];

            switch(counter) {
                case "logio":
                    return FilterSQLUsages(usages, serverName,database,"Log I/O","avg_log_write_percent");
                case "dataio":
                    return FilterSQLUsages(usages, serverName,database,"Data I/O", "avg_physical_data_read_percent", "avg_data_io_percent");
                case "cpu":
                    return FilterSQLUsages(usages, serverName,database, "CPU", "avg_cpu_percent");
                case "storage":
                    return FilterSQLUsages(usages, serverName,database,"Storage", "storage_in_megabytes");
                case "memory":
                    return FilterSQLUsages(usages, serverName,database,"Memory","active_memory_used_kb");
                case "sessions":
                    return FilterSQLUsages(usages, serverName,database,"Sessions", "active_session_count");
                default:
                    throw new Exception("Unknown counter " +counter);
            }
        }
Beispiel #2
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call Negate when current TimeSpan is a positive value");

        try
        {
            long randValue = 0;

            do
            {
                randValue = TestLibrary.Generator.GetInt64(-55);
            } while (randValue <= 0);

            TimeSpan expected = new TimeSpan(randValue);
            TimeSpan res = expected.Negate();

            if (res.Ticks != (expected.Ticks * -1))
            {
                TestLibrary.TestFramework.LogError("001.1", "Call Negate when current TimeSpan is a positive value does not return a negative value");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] res.Ticks = " + res.Ticks + ", expected.Ticks = " + expected.Ticks + ", expected = " + expected + ", randValue = " + randValue);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Beispiel #3
0
 public void Update(TimeSpan total)
 {
     total = total.Subtract(Map01.start);
     if (total.Ticks < 0)
         total = total.Negate();
     time = total.Minutes + ":" + total.Seconds.ToString("00.") + ":" + total.Milliseconds;
 }
        //the limit seems to be 2880 metrics per request
		async System.Threading.Tasks.Task<ICollection<MetricValueSet>> GetMetricsForResourceId(string resourceId, TimeSpan forHistory, MetricsFilter filter) {
            var metricsResult = await MetricsClientFacade.ListDefinitionsAsync(_credentials, resourceId,null,null);

			var metrics = filter.FilterMetrics(metricsResult.MetricDefinitionCollection.Value.Where(_=>_.MetricAvailabilities.Any()).ToList());
            
			if(!metrics.Any()) {
				return new MetricValueSet[0];
			}

            var minTimeGrain = metrics.SelectMany(_=>_.MetricAvailabilities.Where(ma=>forHistory<ma.Retention).Select(a=>a.TimeGrain)).Min();

			var metricNames = metrics.Select(_=>_.Name).ToList();

            var till = DateTime.UtcNow.AddMinutes(1);
            var from = till.Add(forHistory.Negate());


			return await Fetch(new FetchData {
                ResourceId = resourceId,
                MetricNames = metricNames,
                TimeGrain = minTimeGrain,
                From = from,
                Till = till
            });
		}
 /// <summary>
 /// Returns the absolute value of the specified TimeSpan.
 /// </summary>
 /// <param name="val">The val.</param>
 /// <returns></returns>
 public static TimeSpan AbsTimeSpan(TimeSpan val)
 {
     if (IsTimeSpanNegative(val))
     {
         val = val.Negate();
     }
     return val;
 }
Beispiel #6
0
        string GetTime( TimeSpan input )
        {
            bool inThePast = input < TimeSpan.Zero;

            if ( inThePast )
                input = input.Negate();

            return string.Format( new PluralizeFormatProvider(), "{0:day/days}, {1:hour/hours}, {2:minute/minutes}, {3:second/seconds} {4}", input.Days, input.Hours, input.Minutes, input.Seconds, inThePast ? "ago" : "" );
        }
Beispiel #7
0
        /// <summary>
        /// Create molap partition
        /// </summary>
        /// <param name="measureGroup"></param>
        /// <param name="datasourceName"></param>
        /// <param name="partitionid"></param>
        /// <param name="MGdsvTableName"></param>
        /// <param name="filter_string"></param>
        /// <param name="aggregation_design_id"></param>
        /// <param name="is_real_time"></param>
        /// <param name="depended_fact_table"></param>
        internal static void CREATE_MOLAP_PARTITION(
            DB_SQLHELPER_BASE sqlHelper,
            MeasureGroup measureGroup,
            String datasourceName,
            String partitionid,
            String MGdsvTableName,
            String filter_string,
            String aggregation_design_id,
            int is_rolap_mg,
            String depended_fact_table)
        {
            Partition part = measureGroup.Partitions.FindByName(partitionid);

            if (part != null)
            {
                sqlHelper.ADD_MESSAGE_LOG(
                    String.Format("Drop Partition {0}", partitionid),
                    MESSAGE_TYPE.DIMENSION, MESSAGE_RESULT_TYPE.Succeed);
                part.Drop(DropOptions.AlterOrDeleteDependents);
            }

            part        = measureGroup.Partitions.Add(partitionid);
            part.ID     = partitionid;
            part.Name   = partitionid;
            part.Source = new QueryBinding(datasourceName, "SELECT * FROM " + MGdsvTableName + " WHERE 1=1 " + filter_string);
            if (is_rolap_mg.ToString() == "1")
            {
                part.StorageMode        = StorageMode.Rolap;
                part.CurrentStorageMode = StorageMode.Rolap;
                ProactiveCachingTablesBinding tables_binding = new ProactiveCachingTablesBinding();
                tables_binding.NotificationTechnique = NotificationTechnique.Server;
                TableNotification table_notification = new TableNotification(depended_fact_table, CONFIGURATION_HELPER.GET_METADATA_PROPERTY("db_table_schema_name"));
                tables_binding.TableNotifications.Add(table_notification);

                ProactiveCaching proactive_caching = new ProactiveCaching();
                proactive_caching.OnlineMode         = ProactiveCachingOnlineMode.Immediate;
                proactive_caching.AggregationStorage = ProactiveCachingAggregationStorage.MolapOnly;
                proactive_caching.Enabled            = true;
                proactive_caching.Source             = tables_binding;
                System.TimeSpan SilenceInterval_time = new System.TimeSpan(0, 0, 1);
                proactive_caching.SilenceInterval         = SilenceInterval_time.Negate();
                proactive_caching.SilenceOverrideInterval = proactive_caching.SilenceInterval;
                proactive_caching.ForceRebuildInterval    = proactive_caching.SilenceInterval;
                proactive_caching.Latency = System.TimeSpan.Zero;
                part.ProactiveCaching     = proactive_caching;
            }
            else
            {
                part.StorageMode = StorageMode.Molap;
            }
            part.ProcessingMode = ProcessingMode.Regular;
            if (aggregation_design_id != null)
            {
                part.AggregationDesignID = aggregation_design_id.ToString();
            }
        }
Beispiel #8
0
        private IEnumerable<Tuple<string, string>> BuildMongodumpArguments(TimeSpan timeAgo)
        {
            var epoch = new DateTime(1970, 1, 1).ToUniversalTime();
            var startTime = (long)DateTime.UtcNow.Add(timeAgo.Negate()).Subtract(epoch).TotalMilliseconds;
            yield return new Tuple<string, string>("products", string.Format("\"{{UpdateTime: {{$gt: new Date({0})}}}}\"", startTime));

            yield return new Tuple<string, string>("categories", null);

            //yield return new Tuple<string, string>("ratio_rankings", null);
        }
Beispiel #9
0
    public static void ParseExactTest(string inputTimeSpan, string format, TimeSpan expectedTimeSpan)
    {
        TimeSpan actualTimeSpan = TimeSpan.ParseExact(inputTimeSpan, format, new CultureInfo("en-US"));
        Assert.Equal(expectedTimeSpan, actualTimeSpan);

        bool parsed = TimeSpan.TryParseExact(inputTimeSpan, format, new CultureInfo("en-US"), out actualTimeSpan);
        Assert.True(parsed);
        Assert.Equal(expectedTimeSpan, actualTimeSpan);

        // TimeSpanStyles is interpreted only for custom formats
        if (format != "c" && format != "g" && format != "G")
        {
            actualTimeSpan = TimeSpan.ParseExact(inputTimeSpan, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative);
            Assert.Equal(expectedTimeSpan.Negate(), actualTimeSpan);

            parsed = TimeSpan.TryParseExact(inputTimeSpan, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out actualTimeSpan);
            Assert.True(parsed);
            Assert.Equal(expectedTimeSpan.Negate(), actualTimeSpan);
        }
    }
Beispiel #10
0
        // ----------------------------------------------------------------------
        public virtual DateTime? Subtract( DateTime start, TimeSpan offset, SeekBoundaryMode seekBoundaryMode = SeekBoundaryMode.Next )
        {
            if ( includePeriods.Count == 0 && excludePeriods.Count == 0 )
            {
                return start.Subtract( offset );
            }

            TimeSpan? remaining;
            return offset < TimeSpan.Zero ?
                CalculateEnd( start, offset.Negate(), SeekDirection.Forward, seekBoundaryMode, out remaining ) :
                CalculateEnd( start, offset, SeekDirection.Backward, seekBoundaryMode, out remaining );
        }
 static int Negate(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         System.TimeSpan obj = (System.TimeSpan)ToLua.CheckObject(L, 1, typeof(System.TimeSpan));
         System.TimeSpan o   = obj.Negate();
         ToLua.PushValue(L, o);
         ToLua.SetBack(L, 1, obj);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
 private int AcquireLock(string resource, TimeSpan timeout)
 {
     return
         _connection
             .Execute(
                 "INSERT INTO DistributedLock (Resource, CreatedAt) " +
                 "  SELECT @resource, @now " +
                 "  FROM dual " +
                 "  WHERE NOT EXISTS ( " +
                 "  		SELECT * FROM DistributedLock " +
                 "     	WHERE Resource = @resource " +
                 "       AND CreatedAt > @expired)", 
                 new
                 {
                     resource,
                     now = DateTime.UtcNow, 
                     expired = DateTime.UtcNow.Add(timeout.Negate())
                 });
 }
Beispiel #13
0
        /// <summary>
        /// <paramref name="start"/> 시각으로부터 <paramref name="offset"/> 기간을 뺀 (즉 이전의) 시각을 계산합니다.
        /// </summary>
        /// <param name="start">시작 시각</param>
        /// <param name="offset">기간(Duration)</param>
        /// <param name="seekBoundaryMode">검색시 경계에 대한 모드</param>
        /// <returns></returns>
        public virtual DateTime? Subtract(DateTime start, TimeSpan offset, SeekBoundaryMode seekBoundaryMode = SeekBoundaryMode.Next) {
            if(IsDebugEnabled)
                log.Debug("Start 시각[{0}] + Duration[{1}]의 시각을 계산합니다.... SeekBoundaryMode=[{2}]", start, offset, seekBoundaryMode);

            if(IncludePeriods.Count == 0 && ExcludePeriods.Count == 0)
                return start.Subtract(offset);

            TimeSpan? remaining;

            var end = offset < TimeSpan.Zero
                          ? CalculateEnd(start, offset.Negate(), SeekDirection.Forward, seekBoundaryMode, out remaining)
                          : CalculateEnd(start, offset, SeekDirection.Backward, seekBoundaryMode, out remaining);

            if(IsDebugEnabled)
                log.Debug("Start 시각[{0}] + Duration[{1}]의 시각 End=[{2}], remaining=[{3}] 입니다!!! SeekBoundaryMode=[{4}]",
                          start, offset, end, remaining, seekBoundaryMode);

            return end;
        }
Beispiel #14
0
        public void TestToFromTimeSpan()
        {
            Random r = new Random();

            string[] formats =
                new string[]
                    {
                        "{0}",
                        "{1}",
                        "0x{1:x16}",
                        "stuff b4{1}1morestuffafter",
                        "{2}{3} {4:d2}:{5:d2}:{6:d2}.{7:d3}ms",
                        "{2}{3}d {4}h {5}m {6}s {7}ms",
                        "{8} days",
                        "{9} hours",
                        "{10:f10} minutes",
                        "Total seconds: {11:n3}",
                        "{12}ms",
                    };

            for (int i = 0; i < 10000; i++)
            {
                long ticks = (((long)r.Next(2048) << 30) + r.Next());
                ticks -= ticks % TimeSpan.TicksPerMillisecond; // round to nearest ms
                TimeSpan value = new TimeSpan(ticks);
                foreach (var fmt in formats)
                {
                    string text = TypeConverter.Instance.ToString(value, fmt, null);
                    TimeSpan result = TypeConverter.Instance.ParseTimeSpan(text, fmt, null);

                    if (i == 0) Trace.TraceInformation("{0} => {1} == {2}", value, fmt, text);
                    Assert.AreEqual(value.Ticks, result.Ticks);

                    TimeSpan neg = value.Negate();
                    text = TypeConverter.Instance.ToString(neg, fmt, null);
                    result = TypeConverter.Instance.ParseTimeSpan(text, fmt, null);

                    if (i == 0) Trace.TraceInformation("{0} => {1} == {2}", value, fmt, text);
                    Assert.AreEqual(neg.Ticks, result.Ticks);
                }
            }
        }
Beispiel #15
0
        internal static bool BatchConvertSave(string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList<SubtitleFormat> formats, string fileName, Subtitle sub, SubtitleFormat format, bool overwrite, string pacCodePage)
        {
            // adjust offset
            if (!string.IsNullOrEmpty(offset) && (offset.StartsWith("/offset:") || offset.StartsWith("offset:")))
            {
                string[] parts = offset.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length == 5)
                {
                    try
                    {
                        TimeSpan ts = new TimeSpan(0, int.Parse(parts[1].TrimStart('-')), int.Parse(parts[2]), int.Parse(parts[3]), int.Parse(parts[4]));
                        if (parts[1].StartsWith("-"))
                            sub.AddTimeToAllParagraphs(ts.Negate());
                        else
                            sub.AddTimeToAllParagraphs(ts);
                    }
                    catch
                    {
                        Console.Write(" (unable to read offset " + offset + ")");
                    }
                }
            }

            bool targetFormatFound = false;
            string outputFileName;
            foreach (SubtitleFormat sf in formats)
            {
                if (sf.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower() || sf.Name.ToLower().Replace(" ", string.Empty) == toFormat.Replace(" ", string.Empty).ToLower())
                {
                    targetFormatFound = true;
                    sf.BatchMode = true;
                    outputFileName = FormatOutputFileNameForBatchConvert(fileName, sf.Extension, outputFolder, overwrite);
                    Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
                    if (sf.IsFrameBased && !sub.WasLoadedWithFrameNumbers)
                        sub.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate);
                    else if (sf.IsTimeBased && sub.WasLoadedWithFrameNumbers)
                        sub.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
                    File.WriteAllText(outputFileName, sub.ToText(sf), targetEncoding);
                    if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern))
                    {
                        var sami = (Sami)format;
                        foreach (string className in Sami.GetStylesFromHeader(sub.Header))
                        {
                            var newSub = new Subtitle();
                            foreach (Paragraph p in sub.Paragraphs)
                            {
                                if (p.Extra != null && p.Extra.ToLower().Trim() == className.ToLower().Trim())
                                    newSub.Paragraphs.Add(p);
                            }
                            if (newSub.Paragraphs.Count > 0 && newSub.Paragraphs.Count < sub.Paragraphs.Count)
                            {
                                string s = fileName;
                                if (s.LastIndexOf('.') > 0)
                                    s = s.Insert(s.LastIndexOf('.'), "_" + className);
                                else
                                    s += "_" + className + format.Extension;
                                outputFileName = FormatOutputFileNameForBatchConvert(s, sf.Extension, outputFolder, overwrite);
                                File.WriteAllText(outputFileName, newSub.ToText(sf), targetEncoding);
                            }
                        }
                    }
                    Console.WriteLine(" done.");
                }
            }
            if (!targetFormatFound)
            {
                var ebu = new Ebu();
                if (ebu.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower())
                {
                    targetFormatFound = true;
                    outputFileName = FormatOutputFileNameForBatchConvert(fileName, ebu.Extension, outputFolder, overwrite);
                    Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
                    ebu.Save(outputFileName, sub);
                    Console.WriteLine(" done.");
                }
            }
            if (!targetFormatFound)
            {
                var pac = new Pac();
                if (pac.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower() || toFormat.ToLower() == "pac" || toFormat.ToLower() == ".pac")
                {
                    pac.BatchMode = true;
                    if (!string.IsNullOrEmpty(pacCodePage) && Utilities.IsInteger(pacCodePage))
                        pac.CodePage = Convert.ToInt32(pacCodePage);
                    targetFormatFound = true;
                    outputFileName = FormatOutputFileNameForBatchConvert(fileName, pac.Extension, outputFolder, overwrite);
                    Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
                    pac.Save(outputFileName, sub);
                    Console.WriteLine(" done.");
                }
            }
            if (!targetFormatFound)
            {
                var cavena890 = new Cavena890();
                if (cavena890.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower())
                {
                    targetFormatFound = true;
                    outputFileName = FormatOutputFileNameForBatchConvert(fileName, cavena890.Extension, outputFolder, overwrite);
                    Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
                    cavena890.Save(outputFileName, sub);
                    Console.WriteLine(" done.");
                }
            }
            if (!targetFormatFound)
            {
                var cheetahCaption = new CheetahCaption();
                if (cheetahCaption.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower())
                {
                    targetFormatFound = true;
                    outputFileName = FormatOutputFileNameForBatchConvert(fileName, cheetahCaption.Extension, outputFolder, overwrite);
                    Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
                    cheetahCaption.Save(outputFileName, sub);
                    Console.WriteLine(" done.");
                }
            }
            if (!targetFormatFound)
            {
                var capMakerPlus = new CapMakerPlus();
                if (capMakerPlus.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower())
                {
                    targetFormatFound = true;
                    outputFileName = FormatOutputFileNameForBatchConvert(fileName, capMakerPlus.Extension, outputFolder, overwrite);
                    Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
                    capMakerPlus.Save(outputFileName, sub);
                    Console.WriteLine(" done.");
                }
            }
            if (!targetFormatFound)
            {
                Console.WriteLine(string.Format("{0}: {1} - target format '{2}' not found!", count, fileName, toFormat));
                errors++;
                return false;
            }
            else
            {
                converted++;
                return true;
            }
        }
Beispiel #16
0
 /// <summary>
 ///     Negates a TimeSpan.
 /// </summary>
 /// <param name="timeSpan">A TimeSpan.</param>
 /// <returns name="timeSpan">TimeSpan</returns>
 public static System.TimeSpan Negate(System.TimeSpan timeSpan)
 {
     return(timeSpan.Negate());
 }
Beispiel #17
0
        public static TimeSpan ToTimeSpan(string input)
        {
            const string pattern = @"(?<sign>[+|-])?P((?<years>\d+)Y)?((?<months>\d+)M)?((?<days>\d+)D)?(T((?<hours>\d+)H)?((?<minutes>\d+)M)?((?<seconds>\d+(\.\d+)?)S)?)?";
            var regEx = new Regex(pattern);
            var match = regEx.Match(input);
            if (!match.Success)
            {
                throw new FormatException(string.Format("JSON TimeSpan '{0}' cannot be parsed", input));
            }

            bool neg = false;
            int days = 0;
            int hours = 0;
            int minutes = 0;
            int seconds = 0;
            int milliseconds = 0;

            var sign = match.Groups["sign"];
            if (sign.Success && sign.Value == "-")
            {
                neg = true;
            }

            //currently we do not support years and months (.NET never uses them)
            if (match.Groups["years"].Success || match.Groups["months"].Success) throw new FormatException(string.Format("JSON TimeSpan '{0}' cannot be parsed, year or month included", input));

            var daysGroup = match.Groups["days"];
            if (daysGroup.Success)
            {
                days = int.Parse(daysGroup.Value);
            }

            var hoursGroup = match.Groups["hours"];
            if (hoursGroup.Success)
            {
                hours = int.Parse(hoursGroup.Value);
            }

            var minutesGroup = match.Groups["minutes"];
            if (minutesGroup.Success)
            {
                minutes = int.Parse(minutesGroup.Value);
            }

            var secondsGroup = match.Groups["seconds"];
            if (secondsGroup.Success)
            {
                var secondsAndMillis = double.Parse(secondsGroup.Value);
                seconds = (int) Math.Floor(secondsAndMillis);
                milliseconds = (int) Math.Round(((secondsAndMillis - seconds)*1000));
            }

            var timeSpan = new TimeSpan(days, hours, minutes, seconds, milliseconds);

            return neg ? timeSpan.Negate() : timeSpan;
        }
Beispiel #18
0
 private static void WriteTimeZone(StringBuilder sb, TimeSpan zone)
 {
     bool negTimeZone = true;
     if (zone.Ticks < 0)
     {
         negTimeZone = false;
         zone = zone.Negate();
     }
     WriteTimeZone(sb, negTimeZone, zone.Hours, zone.Minutes);
 }
Beispiel #19
0
		public static string ToString (TimeSpan value)
		{
			if (value == TimeSpan.Zero)
				return "PT0S";

			StringBuilder builder = new StringBuilder ();
			if (value.Ticks < 0) {
				if (value == TimeSpan.MinValue)
					return "-P10675199DT2H48M5.4775808S";  // There's one fewer tick on the positive side, so we cannot Negate this value; just hard-code it
				builder.Append ('-');
				value = value.Negate ();
			}
			builder.Append ('P');
			if (value.Days > 0)
				builder.Append (value.Days).Append ('D');
			long ticks = value.Ticks % TimeSpan.TicksPerMillisecond;
			if (value.Hours > 0 || value.Minutes > 0 || value.Seconds > 0 || value.Milliseconds > 0 || ticks > 0) {
				builder.Append('T');
				if (value.Hours > 0)
					builder.Append (value.Hours).Append ('H');
				if (value.Minutes > 0) 
					builder.Append (value.Minutes).Append ('M');
				if (value.Seconds > 0 || value.Milliseconds > 0 || ticks > 0) {
					builder.Append (value.Seconds);
					bool trimZero = true;
					if (ticks > 0)
						builder.Append ('.').AppendFormat ("{0:0000000}", value.Ticks % TimeSpan.TicksPerSecond);
					else if (value.Milliseconds > 0)
						builder.Append ('.').AppendFormat ("{0:000}", value.Milliseconds);
					else
						trimZero = false;
					if (trimZero)
						while (builder [builder.Length - 1] == '0')
							builder.Remove (builder.Length - 1, 1);

					builder.Append ('S');
				}
			}
			return builder.ToString ();
		}
        public static bool ReadISO8601TimeSpan(string str, out TimeSpan ts)
        {
            const ulong TicksPerDay = 864000000000;

            const ulong TicksPerWeek = TicksPerDay * 7;
            const ulong TicksPerMonth = TicksPerDay * 30;
            const ulong TicksPerYear = TicksPerDay * 365;

            // Format goes like so:
            // - (-)P(([n]Y)([n]M)([n]D))(T([n]H)([n]M)([n]S))
            // - P[n]W

            if (str.Length == 0)
            {
                ts = default(TimeSpan);
                return false;
            }

            var ix = 0;
            var isNegative = false;

            var c = str[ix];
            if (c == '-')
            {
                isNegative = true;
                ix++;
            }

            if (ix >= str.Length)
            {
                ts = default(TimeSpan);
                return false;
            }

            c = str[ix];
            if (c != 'P')
            {
                ts = default(TimeSpan);
                return false;
            }

            ix++;   // skip 'P'

            long year, month, week, day;
            bool hasTimePart;
            if (!ISO8601TimeSpan_ReadDatePart(str, ref ix, out year, out month, out week, out day, out hasTimePart))
            {
                ts = default(TimeSpan);
                return false;
            }

            if (week != -1 && (year != -1 || month != -1 || day != -1))
            {
                ts = default(TimeSpan);
                return false;
            }

            if (week != -1 && hasTimePart)
            {
                ts = default(TimeSpan);
                return false;
            }

            if (year == -1) year = 0;
            if (month == -1) month = 0;
            if (week == -1) week = 0;
            if (day == -1) day = 0;

            ulong timeTicks;

            if (hasTimePart)
            {
                ix++;   // skip 'T'
                if (!ISO8601TimeSpan_ReadTimePart(str, ref ix, out timeTicks))
                {
                    ts = default(TimeSpan);
                    return false;
                }
            }
            else
            {
                timeTicks = 0;
            }

            ulong ticks = 0;
            if (year != 0)
            {
                ticks += ((ulong)year) * TicksPerYear;
            }

            if (month != 0)
            {
                // .NET (via XmlConvert) converts months to years
                // This isn't inkeeping with the spec, but of the bad choices... I choose this one
                var yearsFromMonths = ((ulong)month) / 12;
                var monthsAfterYears = ((ulong)month) % 12;
                ticks += (ulong)(yearsFromMonths * TicksPerYear + monthsAfterYears * TicksPerMonth);
            }

            if (week != 0)
            {
                // ISO8601 defines weeks as 7 days, so don't convert weeks to months or years (even if that may seem more sensible)
                ticks += ((ulong)week) * TicksPerWeek;
            }

            ticks += (ulong)(((ulong)day) * TicksPerDay + timeTicks);

            if (ticks >= MaxTicks && !isNegative)
            {
                ts = TimeSpan.MaxValue;
                return true;
            }

            if (ticks >= MinTicks && isNegative)
            {
                ts = TimeSpan.MinValue;
                return true;
            }

            ts = new TimeSpan((long)ticks);
            if (isNegative)
            {
                ts = ts.Negate();
            }

            return true;
        }
		private static bool ParseTimeZoneOffset(ref __DTString str, int len, ref TimeSpan result)
		{
			bool flag = true;
			int num = 0;
			int hours;
			switch (len)
			{
				case 1:
				case 2:
				{
					if (!DateTimeParse.ParseSign(ref str, ref flag))
					{
						return false;
					}
					if (!DateTimeParse.ParseDigits(ref str, len, out hours))
					{
						return false;
					}
					break;
				}
				default:
				{
					if (!DateTimeParse.ParseSign(ref str, ref flag))
					{
						return false;
					}
					if (!DateTimeParse.ParseDigits(ref str, 1, out hours))
					{
						return false;
					}
					if (str.Match(":"))
					{
						if (!DateTimeParse.ParseDigits(ref str, 2, out num))
						{
							return false;
						}
					}
					else
					{
						str.Index--;
						if (!DateTimeParse.ParseDigits(ref str, 2, out num))
						{
							return false;
						}
					}
					break;
				}
			}
			if (num < 0 || num >= 60)
			{
				return false;
			}
			result = new TimeSpan(hours, num, 0);
			if (!flag)
			{
				result = result.Negate();
			}
			return true;
		}
Beispiel #22
0
        /*=================================ParseTimeZoneOffset==================================
        **Action: Parse the string formatted using "z", "zz", "zzz" in DateTime.Format().
        **Returns: the TimeSpan for the parsed timezone offset.
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **              len: the repeated number of the "z"
        **Exceptions: FormatException if errors in parsing.
        ==============================================================================*/

        private static bool ParseTimeZoneOffset(ref __DTString str, int len, ref TimeSpan result) {
            bool isPositive = true;
            int hourOffset;
            int minuteOffset = 0;

            switch (len) {
                case 1:
                case 2:
                    if (!ParseSign(ref str, ref isPositive)) {
                        return (false);
                    }
                    if (!ParseDigits(ref str, len, out hourOffset)) {
                        return (false);
                    }
                    break;
                default:
                    if (!ParseSign(ref str, ref isPositive)) {
                        return (false);
                    }

                    // Parsing 1 digit will actually parse 1 or 2.
                    if (!ParseDigits(ref str, 1, out hourOffset)) {
                        return (false);
                    }
                    // ':' is optional.
                    if (str.Match(":")) {
                        // Found ':'
                        if (!ParseDigits(ref str, 2, out minuteOffset)) {
                            return (false);
                        }
                    } else {
                        // Since we can not match ':', put the char back.
                        str.Index--;
                        if (!ParseDigits(ref str, 2, out minuteOffset)) {
                            return (false);
                        }
                    }
                    break;
            }
            if (minuteOffset < 0 || minuteOffset >= 60) {
                return false;
            }

            result = (new TimeSpan(hourOffset, minuteOffset, 0));
            if (!isPositive) {
                result = result.Negate();
            }
            return (true);
        }
Beispiel #23
0
        // output the 'K' format, which is for round-tripping the data
        private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result) {
        
            // The objective of this format is to round trip the data in the type
            // For DateTime it should round-trip the Kind value and preserve the time zone. 
            // DateTimeOffset instance, it should do so by using the internal time zone.                        
            
            if (offset == NullOffset) {
                // source is a date time, so behavior depends on the kind.
                switch (dateTime.Kind) {
                    case DateTimeKind.Local: 
                        // This should output the local offset, e.g. "-07:30"
                        offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
                        // fall through to shared time zone output code
                        break;
                    case DateTimeKind.Utc:
                        // The 'Z' constant is a marker for a UTC date
                        result.Append("Z");
                        return;
                    default:
                        // If the kind is unspecified, we output nothing here
                        return;
                }            
            }
            if (offset >= TimeSpan.Zero) {
                result.Append('+');                
            }
            else {
                result.Append('-');
                // get a positive offset, so that you don't need a separate code path for the negative numbers.
                offset = offset.Negate();
            }

            result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}:{1:00}", offset.Hours, offset.Minutes);
        }
Beispiel #24
0
        public static TimeSpan GetTimespanFromS5TimeorTime(string time)
        {
            time = time.ToLower().Replace("s5t#", "").Replace("t#", "").Replace("\t", "");
            //need another text for ms (because it could be minute)
            time = time.Replace("ms", "a");

            int d = 0, h = 0, m = 0, s = 0, ms = 0;
            int val = 0;
            bool negativ = false;
            foreach (char tmp in time)
            {
                if (tmp == 'd')
                {
                    d = val;
                    val = 0;
                }
                else if (tmp == 'h')
                {
                    h = val;
                    val = 0;
                }
                else if (tmp == 'm')
                {
                    m = val;
                    val = 0;
                }
                else if (tmp == 's')
                {
                    s = val;
                    val = 0;
                }
                else if (tmp == 'a') //ms are converted to a!
                {
                    ms = val;
                    val = 0;
                }
                else if (tmp == '-')
                {
                    negativ = true;
                }
                else if (tmp == '\t')
                {

                }
                else
                {
                    val *= 10;
                    val += int.Parse(tmp.ToString());
                }
            }

            TimeSpan retVal = new TimeSpan(d, h, m, s, ms);
            /*TimeSpan max = new TimeSpan(0, 2, 46, 30);
            TimeSpan min = new TimeSpan(0, 0, 0, 0, 10);

            if (retVal > max)
                return max;
            if (retVal < min)
                return min;*/
            return negativ ? retVal.Negate() : retVal;
        }
Beispiel #25
0
        // output the 'z' famliy of formats, which output a the offset from UTC, e.g. "-07:30"
        private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, String format, Int32 tokenLen, Boolean timeOnly, StringBuilder result) {
            // See if the instance already has an offset
            Boolean dateTimeFormat = (offset == NullOffset);
            if (dateTimeFormat) {
                // No offset. The instance is a DateTime and the output should be the local time zone
                
                if (timeOnly && dateTime.Ticks < Calendar.TicksPerDay) {
                    // For time only format and a time only input, the time offset on 0001/01/01 is less 
                    // accurate than the system's current offset because of daylight saving time.
                    offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime);
                } else if (dateTime.Kind == DateTimeKind.Utc) {
#if FEATURE_CORECLR
                    offset = TimeSpan.Zero;
#else // FEATURE_CORECLR
                    // This code path points to a bug in user code. It would make sense to return a 0 offset in this case.
                    // However, because it was only possible to detect this in Whidbey, there is user code that takes a 
                    // dependency on being serialize a UTC DateTime using the 'z' format, and it will work almost all the
                    // time if it is offset by an incorrect conversion to local time when parsed. Therefore, we need to 
                    // explicitly emit the local time offset, which we can do by removing the UTC flag.
                    InvalidFormatForUtc(format, dateTime);
                    dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Local);
                    offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
#endif // FEATURE_CORECLR
                } else {
                    offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
                }
            }
            if (offset >= TimeSpan.Zero) {
                result.Append('+');                
            }
            else {
                result.Append('-');
                // get a positive offset, so that you don't need a separate code path for the negative numbers.
                offset = offset.Negate();
            }

            if (tokenLen <= 1) {
                // 'z' format e.g "-7"
                result.AppendFormat(CultureInfo.InvariantCulture, "{0:0}", offset.Hours);
            }
            else {
                // 'zz' or longer format e.g "-07"
                result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}", offset.Hours);
                if (tokenLen >= 3) {
                    // 'zzz*' or longer format e.g "-07:30"
                    result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes);
                }
            }        
        }
Beispiel #26
0
 public static DateTimeOffset Subtract(this DateTimeOffset dateTimeOffset, TimeSpan timeSpan, TimeZoneInfo timeZone)
 {
     return(dateTimeOffset.Add(timeSpan.Negate(), timeZone));
 }
 private void UpdateValue()
 {
     var ts = new TimeSpan(this.Days, this.Hours, this.Minutes, this.Seconds, this.MiliSeconds);
     if (this.Neagtive)
         ts = ts.Negate();
     PropertyNode.Value = ts;
 }
Beispiel #28
0
 public static void TestNegate(TimeSpan timeSpan, TimeSpan expected)
 {
     Assert.Equal(expected, timeSpan.Negate());
     Assert.Equal(expected, -timeSpan);
 }
Beispiel #29
0
        /*=================================ParseTimeZone==========================
        **Action: Parse the timezone offset in the following format:
        **          "+8", "+08", "+0800", "+0800"
        **        This method is used by DateTime.Parse().
        **Returns:      The TimeZone offset.
        **Arguments:
        **      str the parsing string
        **Exceptions:
        **      FormatException if invalid timezone format is found.
        ============================================================================*/

        private static bool ParseTimeZone(ref __DTString str, ref TimeSpan result) {
            // The hour/minute offset for timezone.
            int hourOffset = 0;
            int minuteOffset = 0;
            DTSubString sub;

            // Consume the +/- character that has already been read
            sub = str.GetSubString();
            if (sub.length != 1) {
                return false;
            }
            char offsetChar = sub[0];
            if (offsetChar != '+' && offsetChar != '-') {
                return false;
            }
            str.ConsumeSubString(sub);

            sub = str.GetSubString();
            if (sub.type != DTSubStringType.Number) {
                return false;
            }
            int value = sub.value;
            int length = sub.length;
            if (length == 1 || length == 2) {
                // Parsing "+8" or "+08"
                hourOffset = value;
                str.ConsumeSubString(sub);
                // See if we have minutes
                sub = str.GetSubString();
                if (sub.length == 1 && sub[0] == ':') {
                    // Parsing "+8:00" or "+08:00"
                    str.ConsumeSubString(sub);
                    sub = str.GetSubString();
                    if (sub.type != DTSubStringType.Number || sub.length < 1 || sub.length > 2) {
                        return false;
                    }
                    minuteOffset = sub.value;
                    str.ConsumeSubString(sub);
                }
            }
            else if (length == 3 || length == 4) {
                // Parsing "+800" or "+0800"
                hourOffset = value / 100;
                minuteOffset = value % 100;
                str.ConsumeSubString(sub);
            }
            else {
                // Wrong number of digits
                return false;
            }
            Contract.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99");
            Contract.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99");
            if (minuteOffset < 0 || minuteOffset >= 60) {
                return false;
            }

            result = new TimeSpan(hourOffset, minuteOffset, 0);
            if (offsetChar == '-') {
                result = result.Negate();
            }
            return true;
        }
Beispiel #30
0
    public static void TestParseExact(string input, string format, TimeSpan expected)
    {
        TimeSpan result;
        Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US")));

        Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result));
        Assert.Equal(expected, result);

        // TimeSpanStyles is interpreted only for custom formats
        if (format != "c" && format != "g" && format != "G")
        {
            Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative));

            Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out result));
            Assert.Equal(expected.Negate(), result);
        }
    }
		private static bool ParseTimeZone(ref __DTString str, ref TimeSpan result)
		{
			int hours = 0;
			int num = 0;
			DTSubString subString = str.GetSubString();
			if (subString.length != 1)
			{
				return false;
			}
			char c = subString[0];
			if (c != '+' && c != '-')
			{
				return false;
			}
			str.ConsumeSubString(subString);
			subString = str.GetSubString();
			if (subString.type != DTSubStringType.Number)
			{
				return false;
			}
			int value = subString.value;
			int length = subString.length;
			if (length == 1 || length == 2)
			{
				hours = value;
				str.ConsumeSubString(subString);
				subString = str.GetSubString();
				if (subString.length == 1 && subString[0] == ':')
				{
					str.ConsumeSubString(subString);
					subString = str.GetSubString();
					if (subString.type != DTSubStringType.Number || subString.length < 1 || subString.length > 2)
					{
						return false;
					}
					num = subString.value;
					str.ConsumeSubString(subString);
				}
			}
			else
			{
				if (length != 3 && length != 4)
				{
					return false;
				}
				hours = value / 100;
				num = value % 100;
				str.ConsumeSubString(subString);
			}
			if (num < 0 || num >= 60)
			{
				return false;
			}
			result = new TimeSpan(hours, num, 0);
			if (c == '-')
			{
				result = result.Negate();
			}
			return true;
		}
        /// <summary>
        /// Creates a xml schema duration from a TimeSpan
        /// </summary>
        /// <param name="timeSpan">A TimeSpan containing the time value used to create the duration.</param>
        /// <returns>A string contining the duration in Xml Schema format.</returns>
        public string ToString(TimeSpan timeSpan)
        {
            string dur;
            if (timeSpan.Ticks < 0)
            {
                dur = "-P";
                timeSpan = timeSpan.Negate();
            }
            else
                dur = "P";

            int years = timeSpan.Days / 365;
            int days = timeSpan.Days - years * 365;
            dur += (years > 0 ? years + "Y" : "");
            dur += (days > 0 ? days + "D" : "");
            dur += (timeSpan.Hours > 0 || timeSpan.Minutes > 0 || timeSpan.Seconds > 0 || timeSpan.Milliseconds > 0 ? "T" : "");
            dur += (timeSpan.Hours > 0 ? timeSpan.Hours + "H" : "");
            dur += (timeSpan.Minutes > 0 ? timeSpan.Minutes + "M" : "");
            dur += (timeSpan.Seconds > 0 ? timeSpan.Seconds.ToString() : "");
            dur += (timeSpan.Milliseconds > 0 ? (timeSpan.Milliseconds * 0.001).ToString().Substring(1) + "S" : (timeSpan.Seconds > 0 ? "S" : ""));
            return dur;
        }
Beispiel #33
0
        private static bool TryReadOffset(StringReference offsetText, int startIndex, out TimeSpan offset)
        {
            bool negative = (offsetText[startIndex] == '-');

            int hours;
            if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 1, 2, out hours) != ParseResult.Success)
            {
                offset = default(TimeSpan);
                return false;
            }

            int minutes = 0;
            if (offsetText.Length - startIndex > 5)
            {
                if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 3, 2, out minutes) != ParseResult.Success)
                {
                    offset = default(TimeSpan);
                    return false;
                }
            }

            offset = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes);
            if (negative)
            {
                offset = offset.Negate();
            }

            return true;
        }
        /// <summary>
        /// Parses a duration string and assigns duration properties.
        /// </summary>
        /// <param name="duration">A string containing a valid duration value.</param>
        /// <remarks>A valid duration string conforms to the format: P#Y#M#DT#H#M#S.</remarks>
        private TimeSpan ParseDuration(string duration)
        {
            int multiplier = duration[0] == '-' ? -1 : 1;
            int start = multiplier == -1 ? 1 : 0;

            // Check for mandatory start sentinal
            if (duration[start] != 'P')
                throw new ArgumentException("Invalid duration format.");
            ++start;

            string sentinals = "PYMDTHMS";
            int[] durationBuf = { 0, 0, 0, 0, 0, 0, 0, 0 };
            string fieldValue;
            double seconds = 0;
            int fldIndex;
            int lastFldIndex = 0;
            for (int i = start; i < duration.Length; ++i)
            {
                char curChar = duration[i];

                if (curChar == '.')
                {
                    for (i = i + 1; i < duration.Length; ++i)
                    {
                        curChar = duration[i];
                        if (curChar == 'S')
                            break;
                    }

                    if (curChar != 'S')
                        throw new ArgumentException("Invalid duration format.");
                }

                if (curChar < '0' || curChar > '9')
                {
                    if ((fldIndex = sentinals.Substring(lastFldIndex).IndexOf(curChar)) == -1)
                        throw new ArgumentException("Invalid duration format.");
                    fldIndex += lastFldIndex;
                    lastFldIndex = fldIndex;

                    // Skip T sentinal
                    if (sentinals[fldIndex] == 'T')
                    {
                        start = i + 1;
                        continue;
                    }

                    // Check for blank fields
                    if (i - start < 1)
                        throw new ArgumentException("Invalid duration format.");

                    fieldValue = duration.Substring(start, i - start);
                    if (fldIndex == 7)
                        seconds = Convert.ToDouble(fieldValue);
                    else
                        durationBuf[fldIndex] = Convert.ToInt32(fieldValue);

                    start = i + 1;
                }
            }

            // Assign duration properties
            // days = years * 365 days + months * 31 days + days;
            int days = durationBuf[1] * 365 + durationBuf[2] * 31 + durationBuf[3];

            // Note: Adding 0.0001 temporarily fixes a double/rounding problem
            int milliseconds = (int)(((seconds - (int)seconds) + 0.0001) * 1000.00);
            if ((ulong)((((long)days * 86400L + (long)durationBuf[5] * 3600L + (long)durationBuf[6] * 60L + (long)(seconds)) * TimeSpan.TicksPerSecond) + (long)(milliseconds * TimeSpan.TicksPerMillisecond)) > long.MaxValue)
                throw new ArgumentOutOfRangeException("Durations value exceeds TimeSpan.MaxValue.");
            TimeSpan tempTs = new TimeSpan(days, durationBuf[5], durationBuf[6], (int)seconds, milliseconds);
            return multiplier == -1 ? tempTs.Negate() : tempTs;
        }