Ejemplo n.º 1
8
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            DateTime dte = DateTime.Now;
            Debug.WriteLine("OnActionExecuted: " + dte.ToString("yyyy/MM/dd HH:mm:sss"));
            DateTime dts = Convert.ToDateTime(filterContext.Controller.ViewBag.startTime);
            TimeSpan s = new TimeSpan(dte.Ticks - dts.Ticks);
            Debug.WriteLine("ActionResult 執行的時間(毫秒): " + s.Duration().TotalMilliseconds);

            base.OnActionExecuted(filterContext);
        }
Ejemplo n.º 2
0
        public static string ToReadableString(this TimeSpan span)
        {
            span = new TimeSpan(span.Days * 24 / 8 + span.Hours / 8, span.Hours % 8, span.Minutes, 0);
            string formatted = string.Format("{0}{1}{2}",
                (span.Duration().Hours / 8) > 0 ? string.Format("{0:0}d", span.Hours/8) : string.Empty,
                span.Duration().Hours > 0 ? string.Format("{0:0}h", span.Hours) : string.Empty,
                span.Duration().Minutes > 0 ? string.Format("{0:0}m", span.Minutes) : string.Empty);

            if (string.IsNullOrEmpty(formatted)) return "-";
            return formatted;
        }
        public static string ToReadableString(TimeSpan span)
        {
            string formatted = string.Format("{0}{1}{2}{3}",
                span.Duration().Days > 0 ? string.Format("{0:0}:", span.Days) : string.Empty,
                span.Duration().Hours > 0 ? string.Format("{00:00}:", span.Hours) : string.Format("00:"),
                span.Duration().Minutes > 0 ? string.Format("{00:00}:", span.Minutes) : string.Format("00:"),
                span.Duration().Seconds > 0 ? string.Format("{00:00}", span.Seconds) : string.Format("00"));

            if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);

            if (string.IsNullOrEmpty(formatted)) formatted = "00:00";

            return formatted;
        }
Ejemplo n.º 4
0
        public static string ToReadableString(TimeSpan span)
        {
            string formatted = string.Format("{0}{1}{2}{3}",
                span.Duration().Days > 0 ? string.Format("{0:0} day{1}, ", span.Days, span.Days == 1 ? String.Empty : "s") : string.Empty,
                span.Duration().Hours > 0 ? string.Format("{0:0} hour{1}, ", span.Hours, span.Hours == 1 ? String.Empty : "s") : string.Empty,
                span.Duration().Minutes > 0 ? string.Format("{0:0} minute{1}, ", span.Minutes, span.Minutes == 1 ? String.Empty : "s") : string.Empty,
                span.Duration().Seconds > 0 ? string.Format("{0:0} second{1}", span.Seconds, span.Seconds == 1 ? String.Empty : "s") : string.Empty);

            if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);

            if (string.IsNullOrEmpty(formatted)) formatted = "0 seconds";

            return formatted;
        }
Ejemplo n.º 5
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call Duration on a TimeSpan instance whose value is 0");

        try
        {
            TimeSpan expected = new TimeSpan(0);
            TimeSpan actual = expected.Duration();

            if (actual.Ticks != expected.Ticks)
            {
                TestLibrary.TestFramework.LogError("001.1", "Calling Duration on a TimeSpan instance whose value is 0");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual.Ticks = " + actual.Ticks + ", expected.Ticks = " + expected.Ticks);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Ejemplo n.º 6
0
    public bool PosTest2()
    {
        bool retVal = true;
        long randValue = 0;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Call Duration on a TimeSpan instance whose value is a positive value");

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

            TimeSpan expected = new TimeSpan(randValue);
            TimeSpan actual = expected.Duration();

            if (actual.Ticks != expected.Ticks)
            {
                TestLibrary.TestFramework.LogError("002.1", "Calling Duration on a TimeSpan instance whose value is a positive value");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual.Ticks = " + actual.Ticks + ", expected.Ticks = " + expected.Ticks + ", randValue = " + randValue);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] randValue = " + randValue);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Ejemplo n.º 7
0
        /// <summary>
        /// Returns the number of seconds since midnight
        /// <example>
        /// Example:
        /// double nTotalSeconds = VFPToolkit.dates.Seconds();
        /// </example>
        /// </summary>
        /// <returns></returns>
        public static double Seconds()
        {
            //Create the timespan object get the time between the dates
            System.TimeSpan st = System.DateTime.Now.Subtract(System.DateTime.Today);

            //Return the number of seconds
            return(st.Duration().TotalMilliseconds / 1000);
        }
Ejemplo n.º 8
0
        private Retry(bool shouldBeRetried, TimeSpan retryAfter)
        {
            if (retryAfter != TimeSpan.Zero && retryAfter != retryAfter.Duration()) throw new ArgumentOutOfRangeException("retryAfter");
            if (!shouldBeRetried && retryAfter != TimeSpan.Zero) throw new ArgumentException("Invalid combination");

            ShouldBeRetried = shouldBeRetried;
            RetryAfter = retryAfter;
        }
        public static string ToReadableString(this TimeSpan span)
        {
            string formatted = string.Format("{0}{1}{2}{3}",
                                             span.Duration().Days > 0 ? string.Format("{0:0} day{1}, ", span.Days, span.Days == 1 ? String.Empty : "s") : string.Empty,
                                             span.Duration().Hours > 0 ? string.Format("{0:0} hour{1}, ", span.Hours, span.Hours == 1 ? String.Empty : "s") : string.Empty,
                                             span.Duration().Minutes > 0 ? string.Format("{0:0} minute{1}, ", span.Minutes, span.Minutes == 1 ? String.Empty : "s") : string.Empty,
                                             span.Duration().Seconds > 0 ? string.Format("{0:0} second{1}", span.Seconds, span.Seconds == 1 ? String.Empty : "s") : string.Empty);

            if (formatted.EndsWith(", "))
            {
                formatted = formatted.Substring(0, formatted.Length - 2);
            }

            if (string.IsNullOrEmpty(formatted))
            {
                formatted = "0 seconds";
            }

            return(formatted);
        }
        private static void ThrowIfValueIsNotPositive(TimeSpan value, string fieldName)
        {
            var message = $"The {fieldName} property value should be positive. Given: {value}.";

            if (value == TimeSpan.Zero)
            {
                throw new ArgumentException(message, nameof(value));
            }
            if (value != value.Duration())
            {
                throw new ArgumentException(message, nameof(value));
            }
        }
        private static IEnumerable<string> GetNonZeroFragments(TimeSpan timeSpan)
        {
            TimeSpan absoluteTimespan = timeSpan.Duration();

            var fragments = new List<string>();

            AddDaysIfNotZero(absoluteTimespan, fragments);
            AddHoursIfNotZero(absoluteTimespan, fragments);
            AddMinutesIfNotZero(absoluteTimespan, fragments);
            AddSecondsIfNotZero(absoluteTimespan, fragments);

            return fragments;
        }
Ejemplo n.º 12
0
		public static TimeVal FromTimeSpan (TimeSpan span) {
			TimeVal tv = new TimeVal();
			long nanoseconds;

			/* make sure we're dealing with a positive TimeSpan */
			span = span.Duration();

			nanoseconds = span.Ticks * 100;

			tv.tv_sec = (int)(nanoseconds / 1E+09);
			tv.tv_usec = (int)((nanoseconds % 1E+09) / 1000);

			return tv;
		}
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            string line = "14:01:57 12:47:11";

            string []       times     = line.Split(' ');                 // separating the two times
            System.DateTime endTime   = System.DateTime.Parse(times[0]); // changes the string into a time
            System.DateTime startTime = System.DateTime.Parse(times[1]);

            System.TimeSpan timeDiff = endTime - startTime;

            System.Console.WriteLine(timeDiff.Duration());  // writeline = one result per line
            // CodeEval is looking for the absolute value of the two number EX: -3 and + 3 = absolute value of 6
            // there is a Method of TimeSpan Called Duration, this goes on our timeDiff variable
        }
Ejemplo n.º 14
0
 static int Duration(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         System.TimeSpan obj = (System.TimeSpan)ToLua.CheckObject(L, 1, typeof(System.TimeSpan));
         System.TimeSpan o   = obj.Duration();
         ToLua.PushValue(L, o);
         ToLua.SetBack(L, 1, obj);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Ejemplo n.º 15
0
 static void Main(string[] args)
 {
     using (StreamReader reader = File.OpenText(args[0]))
         while (!reader.EndOfStream)
         {
             string line = reader.ReadLine();
             if (null == line)
             {
                 continue;
             }
             string[]        times    = line.Split(' ');
             System.DateTime endTime  = System.DateTime.Parse(times[0]);
             System.DateTime starTime = System.DateTime.Parse(times[1]);
             System.TimeSpan timeDiff = endTime - starTime;
             System.Console.WriteLine(timeDiff.Duration());
         }
 }
Ejemplo n.º 16
0
        private atriumDB.ActivityRow GetClosestActivity(FileManager fmCur, DateTime activityDate, string officeFileNo, string officeId, CodesDB.DisbursementTypeRow disbTypeR, DateTime disbDate, string fileId, ref bool encounteredError)
        {
            string concat        = "";
            string activityQuery = "officeid = " + officeId + " and fileid = " + fileId + " and (";

            //foreach (ActivityConfig.ACDisbRow acdr in disbTypeR.GetACDisbRows())
            //{
            //    activityQuery +=concat+ " activitycodeid = " + acdr.ActivityCodeId  ;
            //    concat = " or ";
            //}

            activityQuery += ")";

            atriumDB.ActivityRow[] drActivityArr = (atriumDB.ActivityRow[])fmCur.DB.Activity.Select(activityQuery);

            atriumDB.ActivityRow drClosest = null;

            if (drActivityArr.Length == 0)
            {
                WriteErrorLog(officeFileNo, activityDate, disbTypeR.DisbursementType, disbDate, Resources.FileDoesNotHaveRequiredActivity);
                encounteredError = true;
            }
            else if (drActivityArr.Length == 1)
            {
                drClosest = drActivityArr[0];
            }
            else //if (drActivityArr.Length == 2)
            {
                for (int i = 0; i < drActivityArr.Length; i++)
                {
                    DateTime t2 = drActivityArr[i].ActivityDate;
                    DateTime t3 = drClosest == null ? DateTime.MinValue : drClosest.ActivityDate;

                    System.TimeSpan ts1 = activityDate - t2;
                    System.TimeSpan ts2 = activityDate - t3;


                    if (ts1.Duration() <= ts2.Duration())
                    {
                        drClosest = drActivityArr[i];
                    }
                }
            }

            return(drClosest);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Initializes a <see cref="RateGate"/> with a rate of <paramref name="occurrences"/>
        /// per <paramref name="timeUnit"/>.
        /// </summary>
        /// <param name="occurrences">Number of occurrences allowed per unit of time.</param>
        /// <param name="timeUnit">Length of the time unit.</param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="occurrences"/> or <paramref name="timeUnit"/> is negative.
        /// </exception>
        public RateGate(int occurrences, TimeSpan timeUnit)
        {
            if (occurrences <= 0) throw new ArgumentOutOfRangeException("occurrences", "Number of occurrences must be a positive integer");
            if (timeUnit != timeUnit.Duration()) throw new ArgumentOutOfRangeException("timeUnit", "Time unit must be a positive span of time");
            if (timeUnit >= TimeSpan.FromMilliseconds(UInt32.MaxValue)) throw new ArgumentOutOfRangeException("timeUnit", "Time unit must be less than 2^32 milliseconds");

            Occurrences = occurrences;
            TimeUnitMilliseconds = (int)timeUnit.TotalMilliseconds;

            // Create the semaphore, with the number of occurrences as the maximum count.
            _semaphore = new SemaphoreSlim(Occurrences, Occurrences);

            // Create a queue to hold the semaphore exit times.
            _exitTimes = new ConcurrentQueue<int>();

            // Create a timer to exit the semaphore. Use the time unit as the original
            // interval length because that's the earliest we will need to exit the semaphore.
            _exitTimer = new Timer(ExitTimerCallback, null, TimeUnitMilliseconds, -1);
        }
Ejemplo n.º 18
0
		public DifferenceIn GetDifference(TimeSpan span)
		{
			span = span.Duration();

			DifferenceIn diff;
			if (span.Days > 365)
				diff = DifferenceIn.Year;
			else if (span.Days > 0)
				diff = DifferenceIn.Day;
			else if (span.Hours > 0)
				diff = DifferenceIn.Hour;
			else if (span.Minutes > 0)
				diff = DifferenceIn.Minute;
			else if (span.Seconds > 0)
				diff = DifferenceIn.Second;
			else
				diff = DifferenceIn.Millisecond;

			return diff;
		}
        public virtual DifferenceIn GetDifference(TimeSpan span)
        {
            span = span.Duration();

            DifferenceIn diff;
            if (span.Days /2> 365)
                diff = DifferenceIn.Year;
            else if (span.Days/2 > 30)
                diff = DifferenceIn.Month;
            else if (span.Days/2 > 0)
                diff = DifferenceIn.Day;
            else if (span.Hours/2 > 0)
                diff = DifferenceIn.Hour;
            else if (span.Minutes/2 > 0)
                diff = DifferenceIn.Minute;
            else if (span.Seconds/2 > 0)
                diff = DifferenceIn.Second;
            else
                diff = DifferenceIn.Millisecond;

            return diff;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// The background process is complete. We need to inspect
        /// our response to see if an error occurred, a cancel was
        /// requested or if we completed successfully.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FetchAsync_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            buttonFetch.Text    = "Fetch";
            buttonFetch.Enabled = true;

            // Check to see if an error occurred in the background process.
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
                return;
            }

            // Check to see if the background process was cancelled.
            if (e.Cancelled)
            {
                //Log("Search has been cancelled!");
            }
            else
            {
                //Log("Search has been completed!");

                // Everything completed normally.  process the response using e.Result

                System.TimeSpan Length = Start.Subtract(DateTime.Now);
                textBoxTimer.Text = Length.Duration().ToString();

                // update the progress bar to 100 percent
                progressBar1.Value = 100;

                dataGridViewResults.DataSource = TempSet.CardSet;
                UpdateGrid();

                // turn the mouse cursor to hourglass for the wait
                Cursor.Current = Cursors.Default;
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Returns a new <see cref="TimeSpan2"/> object whose value is the absolute value of the current <see cref="TimeSpan2"/> object.
 /// </summary>
 /// <returns>A new <see cref="TimeSpan2"/> object whose value is the absolute value of the current <see cref="TimeSpan2"/> object.</returns>
 public TimeSpan2 Duration() => new TimeSpan2(core.Duration());
        private static IEnumerable <string> TimeSpanToString(TimeSpan ts)
        {
            var readable = new List <string>();

            if (ts == TimeSpan.MaxValue || ts == TimeSpan.MinValue || ts == TimeSpan.Zero)
            {
                return(readable);
            }

            // get absolute timespan
            ts = ts.Duration();
            const int MaxItems = 3;

            if (ts.TotalDays > DaysInYear)
            {
                var whole = Convert.ToInt32(Math.Floor(ts.TotalDays / DaysInYear));
                ts = ts.Subtract(new TimeSpan(whole * DaysInYear, 0, 0, 0));
                readable.Add(whole + " year" + Plural(whole));
                if (readable.Count >= MaxItems)
                {
                    return(readable);
                }
            }

            if (ts.TotalDays > DaysInMonth)
            {
                var whole = Convert.ToInt32(Math.Floor(ts.TotalDays / DaysInMonth));
                ts = ts.Subtract(new TimeSpan(whole * DaysInMonth, 0, 0, 0));
                readable.Add(whole + " month" + Plural(whole));
                if (readable.Count >= MaxItems)
                {
                    return(readable);
                }
            }

            if (ts.TotalDays > DaysInWeek)
            {
                var whole = Convert.ToInt32(Math.Floor(ts.TotalDays / DaysInWeek));
                ts = ts.Subtract(new TimeSpan(whole * DaysInWeek, 0, 0, 0));
                readable.Add(whole + " week" + Plural(whole));
                if (readable.Count >= MaxItems)
                {
                    return(readable);
                }
            }

            if (ts.Days > 0)
            {
                readable.Add(ts.Days + " day" + Plural(ts.Days));
                if (readable.Count >= MaxItems)
                {
                    return(readable);
                }
            }

            if (ts.Hours > 0)
            {
                readable.Add(ts.Hours + " hour" + Plural(ts.Hours));
                if (readable.Count >= MaxItems)
                {
                    return(readable);
                }
            }

            if (ts.Minutes > 0)
            {
                readable.Add(ts.Minutes + " minute" + Plural(ts.Minutes));
                if (readable.Count >= MaxItems)
                {
                    return(readable);
                }
            }

            if (ts.Seconds > 0)
            {
                readable.Add(ts.Seconds + " second" + Plural(ts.Seconds));
                if (readable.Count >= MaxItems)
                {
                    return(readable);
                }
            }

            if (ts.Milliseconds > 0)
            {
                readable.Add(ts.Milliseconds + " ms");
                if (readable.Count >= MaxItems)
                {
                    return(readable);
                }
            }

            return(readable);
        }
Ejemplo n.º 23
0
        public override int RemoveTimedOutServers(TimeSpan timeOut)
        {
            if (timeOut.Duration() != timeOut) {
                throw new ArgumentException("The `timeOut` value must be positive.", "timeOut");
            }

            using (var repository = new Repository()) {
                var heartBeatCutOff = DateTime.UtcNow.Add(timeOut.Negate());

                var results = repository.Session.Query<RavenServer>()
                                .Where(t => t.LastHeartbeat < heartBeatCutOff)
                                .ToList();

                foreach (var item in results) {
                    repository.Delete(item);
                }

                return results.Count;
            }
        }
Ejemplo n.º 24
0
 public void DurationWorks()
 {
     var time1 = new TimeSpan(-3, -2, -1, -5, -4);
     var time2 = new TimeSpan(2, 1, 5, 4, 3);
     TimeSpan actual1 = time1.Duration();
     TimeSpan actual2 = time2.Duration();
     Assert.True((object)time1 is TimeSpan, "Should be TimeSpan");
     Assert.AreEqual(actual1.TotalMilliseconds, (((((3 * 24) + 2) * 60 + 1) * 60) + 5) * 1000 + 4, "Negative should be negated");
     Assert.AreEqual(actual2.TotalMilliseconds, (((((2 * 24) + 1) * 60 + 5) * 60) + 4) * 1000 + 3, "Positive should be preserved");
 }
Ejemplo n.º 25
0
        private string CalculateGmtOffset()
        {
            char sign = '+';
            DateTime time = ToDateTime();

            #if SILVERLIGHT
            long offset = time.Ticks - time.ToUniversalTime().Ticks;
            if (offset < 0)
            {
                sign = '-';
                offset = -offset;
            }
            int hours = (int)(offset / TimeSpan.TicksPerHour);
            int minutes = (int)(offset / TimeSpan.TicksPerMinute) % 60;
            #else
            // Note: GetUtcOffset incorporates Daylight Savings offset

            //TODO: SUSTITUIDO
            //TimeSpan offset =  TimeZone.CurrentTimeZone.GetUtcOffset(time);
            TimeSpan offset = new TimeSpan();
            if (offset.CompareTo(TimeSpan.Zero) < 0)
            {
                sign = '-';
                offset = offset.Duration();
            }
            int hours = offset.Hours;
            int minutes = offset.Minutes;
            #endif

            return "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
        }
Ejemplo n.º 26
0
Archivo: POut.cs Proyecto: mnisl/OD
		///<summary>Timespans that might be invalid time of day.  Can be + or - and can be up to 800+ hours.  Stored in Oracle as varchar2.  Never encapsulates</summary>
		public static string TSpan(TimeSpan myTimeSpan) {
			if(myTimeSpan==System.TimeSpan.Zero) {
				return "00:00:00"; ;
			}
			try {
				string retval="";
				if(myTimeSpan < System.TimeSpan.Zero) {
					retval+="-";
					myTimeSpan=myTimeSpan.Duration();
				}
				int hours=(myTimeSpan.Days*24)+myTimeSpan.Hours;
				retval+=hours.ToString().PadLeft(2,'0')+":"+myTimeSpan.Minutes.ToString().PadLeft(2,'0')+":"+myTimeSpan.Seconds.ToString().PadLeft(2,'0');
				return retval;
			} 
			catch {
				return "00:00:00";
			}
		}
        private static string ObterTempoLegível(TimeSpan tempo)
        {
            string formatado = string.Format("{0}{1}{2}{3}",
                tempo.Duration().Days > 0 ? string.Format("{0:0} dia{1}, ", tempo.Days, tempo.Days == 1 ? String.Empty : "s") : string.Empty,
                tempo.Duration().Hours > 0 ? string.Format("{0:0} hora{1}, ", tempo.Hours, tempo.Hours == 1 ? String.Empty : "s") : string.Empty,
                tempo.Duration().Minutes > 0 ? string.Format("{0:0} minuto{1}, ", tempo.Minutes, tempo.Minutes == 1 ? String.Empty : "s") : string.Empty,
                tempo.Duration().Seconds > 0 ? string.Format("{0:0} segundo{1}", tempo.Seconds, tempo.Seconds == 1 ? String.Empty : "s") : string.Empty);

            if (formatado.EndsWith(", ")) formatado = formatado.Substring(0, formatado.Length - 2);

            if (string.IsNullOrEmpty(formatado)) formatado = "0 segundos";

            return formatado;
        }
		public MFTestResults Duration_Test10(  )
		{
            /// <summary>
            /// 1. Test the Duration property with several random TimeSpans
            /// </summary>
            ///
            Log.Comment("Testing Duration property");
			bool testResult = true;
			Random random = new Random();
			for( int i = 0; i<5; i++ )
			{
				bool b = true;
				int hours = random.Next(23);
				int minutes = random.Next(59);
				int seconds = random.Next(59);
				TimeSpan ts = new TimeSpan( -hours, -minutes, -seconds );
				testResult &= ts.Duration() == new TimeSpan( hours, minutes, seconds );
				ts = new TimeSpan( hours, minutes, seconds );
				testResult &= ts.Duration() == new TimeSpan( hours, minutes, seconds );
				testResult &= b;
			}

			return (testResult? MFTestResults.Pass: MFTestResults.Fail);
		}
        public int RemoveTimedOutServers(TimeSpan timeOut)
        {
            if (timeOut.Duration() != timeOut)
            {
                throw new ArgumentException("The `timeOut` value must be positive.", "timeOut");
            }

            return _connection.Execute(
                string.Format(@"
DELETE FROM """ + _options.SchemaName + @""".""server"" 
WHERE ""lastheartbeat"" < (NOW() AT TIME ZONE 'UTC' - INTERVAL '{0} MILLISECONDS');
", (long)timeOut.TotalMilliseconds));
        }
Ejemplo n.º 30
0
 public virtual bool runTest()
   {
   int iCountErrors = 0;
   int iCountTestcases = 0;
   Console.Error.WriteLine( strName + ": " + strTest + " runTest started..." );
   TimeSpan	ts;
   int iDays = -1;
   int iHours = -1;
   int iMinutes = -1;
   int iSeconds = -1;
   do
     {
     ++iCountTestcases;
     Console.Error.WriteLine( "[]  Construct TimeSpan object using positive hours, month and seconds" );
     try
       {
       iDays = 4;
       iHours = 12;
       iMinutes = 23;
       iSeconds = 34;
       ts = new TimeSpan( iDays, iHours, iMinutes, iSeconds );
       TimeSpan tsDuration = ts.Duration();
       if ( iDays != tsDuration.Days )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Days <" + iDays + "> ";
	 strInfo = strInfo + "Returned Days <" + tsDuration.Days + "> ";
	 Console.WriteLine( strTest+ "E_101a: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       if ( iHours != tsDuration.Hours )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Hours <" + iHours + "> ";
	 strInfo = strInfo + "Returned Hours <" + tsDuration.Hours + "> ";
	 Console.WriteLine( strTest+ "E_101a: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       if ( iMinutes != tsDuration.Minutes )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Minutes <" + iMinutes + "> ";
	 strInfo = strInfo + "Returned Minutes <" + tsDuration.Minutes + "> ";
	 Console.WriteLine( strTest+ "E_101b: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       if ( iSeconds != tsDuration.Seconds )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Seconds <" + iSeconds + "> ";
	 strInfo = strInfo + "Returned Seconds <" + tsDuration.Seconds + "> ";
	 Console.WriteLine( strTest+ "E_101c: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       }
     catch (Exception ex)
       {
       Console.WriteLine( strTest+ "E_10001: Unexpected Exception: " + ex.ToString() );
       ++iCountErrors;
       break;
       }
     ++iCountTestcases;
     Console.Error.WriteLine( "[]  Construct TimeSpan object using negative hours, month and seconds" );
     try
       {
       iDays = -4;
       iHours = -12;
       iMinutes = -23;
       iSeconds = -34;
       ts = new TimeSpan( iDays, iHours, iMinutes, iSeconds );
       TimeSpan tsDuration = ts.Duration();
       if ( iDays != -tsDuration.Days )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Days <" + -iDays + "> ";
	 strInfo = strInfo + "Returned Days <" + tsDuration.Days + "> ";
	 Console.WriteLine( strTest+ "E_101a: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       if ( iHours != -tsDuration.Hours )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Hours <" + -iHours + "> ";
	 strInfo = strInfo + "Returned Hours <" + tsDuration.Hours + "> ";
	 Console.WriteLine( strTest+ "E_202a: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       if ( iMinutes != -tsDuration.Minutes )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Minutes <" + -iMinutes + "> ";
	 strInfo = strInfo + "Returned Minutes <" + tsDuration.Minutes + "> ";
	 Console.WriteLine( strTest+ "E_202b: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       if ( iSeconds != -tsDuration.Seconds )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Seconds <" + -iSeconds + "> ";
	 strInfo = strInfo + "Returned Seconds <" + tsDuration.Seconds + "> ";
	 Console.WriteLine( strTest+ "E_202c: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       }
     catch (Exception ex)
       {
       Console.WriteLine( strTest+ "E_20202: Unexpected Exception: " + ex.ToString() );
       ++iCountErrors;
       break;
       }
     ++iCountTestcases;
     Console.Error.WriteLine( "[]  Construct TimeSpan object using zero hours, month and seconds" );
     try
       {
       iDays = 0;
       iHours = 0;
       iMinutes = 0;
       iSeconds = 0;
       ts = new TimeSpan( iDays, iHours, iMinutes, iSeconds );
       TimeSpan tsDuration = ts.Duration();
       if ( iDays != tsDuration.Days )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Days <" + iDays + "> ";
	 strInfo = strInfo + "Returned Days <" + tsDuration.Days + "> ";
	 Console.WriteLine( strTest+ "E_101a: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       if ( iHours != ts.Hours )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Hours <" + iHours + "> ";
	 strInfo = strInfo + "Returned Hours <" + ts.Hours + "> ";
	 Console.WriteLine( strTest+ "E_303a: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       if ( iMinutes != ts.Minutes )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Minutes <" + iMinutes + "> ";
	 strInfo = strInfo + "Returned Minutes <" + ts.Minutes + "> ";
	 Console.WriteLine( strTest+ "E_303a: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       if ( iSeconds != ts.Seconds )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected Seconds <" + iSeconds + "> ";
	 strInfo = strInfo + "Returned Seconds <" + ts.Seconds + "> ";
	 Console.WriteLine( strTest+ "E_303a: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       }
     catch (Exception ex)
       {
       Console.WriteLine( strTest+ "E_30303: Unexpected Exception: " + ex.ToString() );
       ++iCountErrors;
       break;
       }
     }
   while ( false );
   Console.Error.Write( strName );
   Console.Error.Write( ": " );
   if ( iCountErrors == 0 )
     {
     Console.Error.WriteLine( strTest + " iCountTestcases==" + iCountTestcases + " paSs" );
     return true;
     }
   else
     {
     System.String strFailMsg = null;
     Console.WriteLine( strTest+ strPath );
     Console.WriteLine( strTest+ "FAiL" );
     Console.Error.WriteLine( strTest + " iCountErrors==" + iCountErrors );
     return false;
     }
   }
Ejemplo n.º 31
0
 public void UpdateTimeout(TimeSpan timeout)
 {
     created = DateTime.UtcNow;
     if (timeout != TimeSpan.Zero) this.timeout = timeout.Duration();
 }
Ejemplo n.º 32
0
        public override int RemoveTimedOutServers(TimeSpan timeOut)
        {
            if (timeOut.Duration() != timeOut)
            {
                throw new ArgumentException("The `timeOut` value must be positive.", nameof(timeOut));
            }

            return _storage.UseConnection(connection => connection.Execute(
                $@"delete from [{_storage.SchemaName}].Server where LastHeartbeat < @timeOutAt",
                new { timeOutAt = DateTime.UtcNow.Add(timeOut.Negate()) }));
        }
Ejemplo n.º 33
0
 public static void TestDuration(TimeSpan timeSpan, TimeSpan expected)
 {
     Assert.Equal(expected, timeSpan.Duration());
 }
Ejemplo n.º 34
0
		public override int RemoveTimedOutServers(TimeSpan timeOut)
		{
			if (timeOut.Duration() != timeOut)
			{
				throw new ArgumentException("The `timeOut` value must be positive.", "timeOut");
			}

			return _connection.Execute(
				@"delete from [HangFire.Server] where LastHeartbeat < @timeOutAt",
				new { timeOutAt = DateTime.UtcNow.Add(timeOut.Negate()) });
		}
Ejemplo n.º 35
0
        public string GetTimeSpan(DateTime PostedDate)
        {
            string strTimeSpan = string.Empty;
            TimeSpan timeSpan = new TimeSpan();
            try
            {
                timeSpan = DateTime.Now.Subtract(PostedDate);
                timeSpan.Duration();

                if (timeSpan.Days >= 1)
                {
                    strTimeSpan = timeSpan.Days.ToString() + " days ago";
                }
                else if (timeSpan.Hours >= 1)
                {
                    strTimeSpan = timeSpan.Hours.ToString() + " hours ago";
                }
                else
                {
                    strTimeSpan = timeSpan.Minutes.ToString() + " mins ago";
                }
            }
            catch (Exception ex)
            {
            }

            return strTimeSpan;
        }
        public string TimeSpanToOWLDateTimeDatatypeStr(TimeSpan date)
        {
            // TODO: add 0 to left of H, M, S if length is 1.
            date = date.Duration();
            string owlDateTime = "\"00-00" + "-" + date.Days + "T";    // TODO: 00-00 Testing
            if (date.Hours.ToString().Length < 2)
                owlDateTime = owlDateTime + "0" + date.Hours;
            else owlDateTime = owlDateTime + date.Hours;

            if (date.Minutes.ToString().Length < 2)
                owlDateTime = owlDateTime + ":0" + date.Minutes;
            else owlDateTime = owlDateTime + ":" + date.Minutes;

            if (date.Seconds.ToString().Length < 2)
                owlDateTime = owlDateTime + ":0" + date.Seconds;
            else owlDateTime = owlDateTime + ":" + date.Seconds;
            owlDateTime = owlDateTime + "\"ˆˆxsd:dateTime";

            return owlDateTime;
        }
        public string TimeSpanToOWLDateTimeStr (TimeSpan date)
        {
            
            date = date.Duration();
            string owlDateTime = "\"00-00" + "-" + date.Days + "T";  // TODO: 00-00 Testing
            if (date.Hours.ToString().Length < 2)
                owlDateTime = owlDateTime + "0" + date.Hours;
            else owlDateTime = owlDateTime + date.Hours;

            if (date.Minutes.ToString().Length < 2)
                owlDateTime = owlDateTime + ":0" + date.Minutes;
            else owlDateTime = owlDateTime + ":" + date.Minutes;

            if (date.Seconds.ToString().Length < 2)
                owlDateTime = owlDateTime + ":0" + date.Seconds;
            else owlDateTime = owlDateTime + ":" + date.Seconds; 
            return owlDateTime;
        }
Ejemplo n.º 38
0
 /// <summary>
 /// Returns an absolute timespan.
 /// </summary>
 public TimeSpan duration()
 {
     return((TimeSpan)_timeSpan.Duration());
 }
Ejemplo n.º 39
0
        public virtual TimeSpan WorkedTime(DateTime stDate, DateTime endDate)
        {
            NHibernate.ISession s = SessionFactory.GetSession();
            ICriteria crit = s.CreateCriteria(typeof(BL.Event));
            crit.Add(Expression.Eq("Event32", 28));
            crit.Add(Expression.Gt("Date_event", stDate));
            crit.Add(Expression.Le("Date_event", endDate));
            crit.Add(Expression.Eq("Emp.Id", Id));
            crit.Add(Expression.Eq("Zone_code", 8));
            //crit.Add(Expression.Sql(" HozOrgan = some (select e.Id from pList as e where e.Section not in (" + settings.Excluded + "))"));
            Order ord = new Order("Date_event", true);
            crit.AddOrder(ord);
            //System.Collections.IList listEv = crit.List();
            IList<BL.Event> l1 = crit.List<BL.Event>();

            //int res;
            if (l1.Count > 0) //Если есть события входа и выхода за данный период
            {
                //TimeSpan wt = l1.First().Date_event - l1.Last().Date_event;

                int wtMinutes;

                List<Period> PeriodList = new List<Period>();
                Period Period = new Period();
                foreach (Event ev in l1)
                {

                    if (ev.Event_code == 1) //Если событие вход
                    {
                        if (Period.date_start_assigned == false)
                        {
                            Period.Date_start = ev.Date_event;
                        }
                    }

                    else // Событие выход
                    {
                        if (Period.date_start_assigned == true & Period.date_end_assigned == false)
                        {
                            Period.Date_end = ev.Date_event;
                        }
                    }

                    if (Period.date_start_assigned == true & Period.date_end_assigned == true)
                    {
                        PeriodList.Add(new Period(Period.Date_start, Period.Date_end));
                        Period.date_start_assigned = false;
                        Period.date_end_assigned = false;
                    }

                }

                TimeSpan wtAll = new TimeSpan();
                TimeSpan wtPer = new TimeSpan();
                //TimeSpan wtPer1 = new TimeSpan(); //Промежуточная переменная

                foreach (Period per in PeriodList)
                {

                    wtPer = per.Date_end - per.Date_start;
                    if (wtPer.Duration().Hours < 16 & wtPer.Duration().Days < 1)
                    {
                        wtAll = wtAll.Duration().Add(wtPer.Duration());
                    }
                    else
                    {
                    }

                }
                return wtAll;
            }
            else // Если событий нет возвращаем 0
            {
                return new TimeSpan();
            }
        }
Ejemplo n.º 40
0
 public static void GetDelayColor(TimeSpan tsDelay, out Color clrHi, out Color clrLo)
 {
     clrHi = Color.FromArgb(0xff, 0, 200, 0);
     clrLo = Color.FromArgb(0xff, 0, 0x40, 0);
     if (tsDelay.Duration().TotalSeconds <= OnTimeThreshold)
     {
         clrHi = Color.FromArgb(0xff, 0, 200, 0);
         clrLo = Color.FromArgb(0xff, 0, 0x40, 0);
     }
     else if (tsDelay.TotalSeconds > 0.0)
     {
         if (tsDelay.Duration().TotalSeconds <= TooSlowThreshold)
         {
             clrHi = Color.FromArgb(0xff, 0xff, 0x80, 0);
             clrLo = Color.FromArgb(0xff, 0x80, 0x40, 0);
         }
         else
         {
             clrHi = Color.FromArgb(0xff, 0xff, 0, 0);
             clrLo = Color.FromArgb(0xff, 0x40, 0, 0);
         }
     }
     else if (tsDelay.Duration().TotalSeconds <= TooSlowThreshold)
     {
         clrHi = Color.FromArgb(0xff, 0, 0, 0xff);
         clrLo = Color.FromArgb(0xff, 0, 0, 0x80);
     }
     else
     {
         clrHi = Color.FromArgb(0xff, 0, 200, 0xff);
         clrLo = Color.FromArgb(0xff, 0, 0, 0xff);
     }
 }