C# (CSharp) System. TimeSpan Code Examples

C# (CSharp) System.TimeSpan - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для System.TimeSpan, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Пример #1
0
       /// <summary>
	/// Constructor
	/// </summary>
	/// <param name="idleTTL">the idle time to live value</param>
	public IdleExpiration(TimeSpan idleTTL)
	{			
           this.SetBit(IS_VARIANT);
		_idleTimeToLive = (int)idleTTL.TotalSeconds;
           _lastTimeStamp = AppUtil.DiffSeconds(DateTime.Now);
           _hintType = ExpirationHintType.IdleExpiration;
	}
Пример #2
0
        protected override void Update(TimeSpan gameTime)
        {
            if (this.CurrentState == States.Menu)
            {
                Input input = WaveServices.Input;

                if ((input.TouchPanelState.IsConnected && input.TouchPanelState.Count > 0) ||
                    (input.KeyboardState.IsConnected &&
                    (input.KeyboardState.Space == ButtonState.Pressed ||
                     input.KeyboardState.A == ButtonState.Pressed ||
                     input.KeyboardState.S == ButtonState.Pressed ||
                     input.KeyboardState.D == ButtonState.Pressed ||
                     input.KeyboardState.W == ButtonState.Pressed ||
                     input.KeyboardState.Up == ButtonState.Pressed ||
                     input.KeyboardState.Down == ButtonState.Pressed ||
                     input.KeyboardState.Left == ButtonState.Pressed ||
                     input.KeyboardState.Right == ButtonState.Pressed)))
                {
                    this.CurrentState = States.GamePlay;
                }
            }
            else if (this.CurrentState == States.GamePlay)
            {
                if (this.player.Life <= 0)
                {
                    this.CurrentState = States.GameOver;
                }
            }
        }
Пример #3
0
        protected override void Update(TimeSpan gameTime)
        {
            input = WaveServices.Input;

            if (input.KeyboardState.IsConnected)
            {
                keyboardState = input.KeyboardState;

                if (keyboardState.W == ButtonState.Pressed)
                {
                    MoveCamera(ref forward);
                }
                if (keyboardState.S == ButtonState.Pressed)
                {
                    MoveCamera(ref back);
                }
                if (keyboardState.A == ButtonState.Pressed)
                {
                    MoveCamera(ref left);
                }
                if (keyboardState.D == ButtonState.Pressed)
                {
                    MoveCamera(ref right);
                }
            }
            var rotationMatrix = (Matrix.CreateRotationX(MathHelper.ToRadians(45.0f)) * Matrix.CreateRotationY(MathHelper.ToRadians(30.0f)));
            Vector3 transformedReference = Vector3.Transform(Vector3.Down, rotationMatrix);
            Vector3 cameraLookat = Camera.Position + transformedReference;
            var width = WaveServices.Platform.ScreenWidth / 24;
            var height = WaveServices.Platform.ScreenHeight / 24;

            //camera.Projection = Matrix.CreateOrthographic(width, height, camera.NearPlane, camera.FarPlane);
            Camera.LookAt = cameraLookat;
        }
        /// <summary>
        /// Initializes the service.
        /// </summary>
        /// <param name="pollingInterval">The polling interval. If <c>default(TimeSpan)</c>, no polling will be enabled.</param>
        /// <returns>Task.</returns>
        /// <remarks>Note that this method is optional but will start the service. If this method is not called, the service will be initialized
        /// in the <see cref="ValidateLicense" /> method.</remarks>
        public virtual void Initialize(TimeSpan pollingInterval = default(TimeSpan))
        {
            CreateLicenseListeningSockets();

            if (_pollingTimer.Enabled)
            {
                Log.Debug("Stopping network polling");

                _pollingTimer.Stop();
                _pollingTimer.Elapsed -= OnPollingTimerElapsed;
            }

            if (pollingInterval != default(TimeSpan))
            {
                if (pollingInterval < SearchTimeout)
                {
                    Log.Warning("Polling interval is smaller than SearchTimeout, defaulting to SearchTimeout + 5 seconds");

                    pollingInterval = SearchTimeout.Add(TimeSpan.FromSeconds(5));
                }

                Log.Debug("Starting network polling with an interval of '{0}'", pollingInterval);

                _pollingTimer.Interval = pollingInterval.TotalMilliseconds;
                _pollingTimer.Elapsed += OnPollingTimerElapsed;
                _pollingTimer.Start();
            }
        }
Пример #5
0
 public override void Update(TimeSpan elapsed)
 {
     if (Reflected)
         Move();
     Reflected = false;
     base.Update(elapsed);
 }
Пример #6
0
 public CommandMessage(string cmdText, TimeSpan duration, string type, string connectionGUID)
 {
     CommandText = cmdText;
     Duration = duration;
     Type = type;
     ConnectionGUID = connectionGUID;
 }
 /// <summary>
 /// <para>Await until the given condition evaluates to <c>true</c> or the timeout
 /// expires, whichever comes first.</para>
 /// <para>If no timeout is given, take it from the innermost enclosing `within`
 /// block (if inside a `within` block) or the value specified in config value "akka.test.single-expect-default". 
 /// The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor 
 /// specified in config value "akka.test.timefactor"..</para>
 /// <para>A call to <paramref name="conditionIsFulfilled"/> is done immediately, then the threads sleep
 /// for about a tenth of the timeout value, before it checks the condition again. This is repeated until
 /// timeout or the condition evaluates to <c>true</c>. To specify another interval, use the overload
 /// <see cref="AwaitCondition(System.Func{bool},System.Nullable{System.TimeSpan},System.Nullable{System.TimeSpan},string)"/>
 /// </para>
 /// </summary>
 /// <param name="conditionIsFulfilled">The condition that must be fulfilled within the duration.</param>
 /// <param name="max">The maximum duration. If undefined, uses the remaining time 
 /// (if inside a `within` block) or the value specified in config value "akka.test.single-expect-default". 
 /// The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor 
 /// specified in config value "akka.test.timefactor".</param>
 /// <param name="message">The message used if the timeout expires.</param>
 public void AwaitCondition(Func<bool> conditionIsFulfilled, TimeSpan? max, string message)
 {
     var maxDur = RemainingOrDilated(max);
     var interval = new TimeSpan(maxDur.Ticks / 10);
     var logger = _testState.TestKitSettings.LogTestKitCalls ? _testState.Log : null;
     InternalAwaitCondition(conditionIsFulfilled, maxDur, interval, (format, args) => AssertionsFail(format, args, message), logger);
 }
Пример #8
0
        public async Task<bool> Exists(string fileName, TimeSpan expiration)
        {
            try
            {
                var exists = true;

                var file = await _baseFolder.TryGetItemAsync(fileName.CleanCharacters());
                if (file != null)
                {
                    var createdAt = file.DateCreated;
                    var timeDiff = (DateTimeOffset.Now - createdAt);
                    if (timeDiff > expiration)
                        exists = false;

                    return exists;
                }
                else
                    return false;

            }
            catch (FileNotFoundException)
            {
                return false;
            }
        }
        protected void Arrange()
        {
            var random = new Random();
            _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
            _operationTimeout = TimeSpan.FromSeconds(30);
            _encoding = Encoding.UTF8;
            _disconnectedRegister = new List<EventArgs>();
            _errorOccurredRegister = new List<ExceptionEventArgs>();
            _channelDataEventArgs = new ChannelDataEventArgs(
                (uint)random.Next(0, int.MaxValue),
                new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelMock = new Mock<IChannelSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object);
            _channelMock.InSequence(_sequence).Setup(p => p.Open());
            _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true);

            _subsystemSession = new SubsystemSessionStub(
                _sessionMock.Object,
                _subsystemName,
                _operationTimeout,
                _encoding);
            _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
            _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
            _subsystemSession.Connect();
        }
 /// <summary>
 /// Creates an instance of the SplunkViaHttp context
 /// </summary>
 public SplunkContext(SplunkClient.Scheme scheme, string host, int port, string index, string username, string password, TimeSpan timeout, HttpMessageHandler handler, bool disposeHandler = true)
     : base(scheme, host, port, timeout, handler, disposeHandler)
 {
     Index = index;
     Username = username;
     Password = password;
 }
 public void Enter(TimeSpan timeout)
 {
     if (!this.TryEnter(timeout))
     {
         throw Fx.Exception.AsError(CreateEnterTimedOutException(timeout));
     }
 }
Пример #12
0
        public static void LinearSmoothMove(Point newPosition, TimeSpan duration)
        {
            Point start = Cursor.Position;

            var rnd = new Random();
            // Find the vector between start and newPosition
            double deltaX = newPosition.X - start.X;
            double deltaY = newPosition.Y - start.Y;

            // start a timer
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            double timeFraction = 0.0;

            do
            {
                var v = rnd.Next(0, 1000);
                Trace.WriteLine(stopwatch.Elapsed.Ticks + ", " + v + ", " + (double)(stopwatch.Elapsed.Ticks + v) / duration.Ticks);
                timeFraction = (double)(stopwatch.Elapsed.Ticks + v * 5) / duration.Ticks;
                if (timeFraction > 1.0)
                    timeFraction = 1.0;

                var addX = rnd.Next(0, 10);
                var addY = rnd.Next(0, 10);
                var curPoint = new Point(start.X + (int)(timeFraction * deltaX) + addX,
                                             start.Y + (int)(timeFraction * deltaY) + addY);
                Cursor.Position = curPoint;

                Thread.Sleep(20);
            } while (timeFraction < 1.0);

            Cursor.Position = newPosition;
        }
Пример #13
0
        public Game(UserControl userControl, Canvas drawingCanvas, Canvas debugCanvas, TextBlock txtDebug)
        {
            //Initialize
            IsActive = true;
            IsFixedTimeStep = true;
            TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 16);
            Components = new List<DrawableGameComponent>();
            World = new World(new Vector2(0, 0));
            _gameTime = new GameTime();
            _gameTime.GameStartTime = DateTime.Now;
            _gameTime.FrameStartTime = DateTime.Now;
            _gameTime.ElapsedGameTime = TimeSpan.Zero;
            _gameTime.TotalGameTime = TimeSpan.Zero;

            //Setup Canvas
            DrawingCanvas = drawingCanvas;
            DebugCanvas = debugCanvas;
            TxtDebug = txtDebug;
            UserControl = userControl;

            //Setup GameLoop
            _gameLoop = new Storyboard();
            _gameLoop.Completed += GameLoop;
            _gameLoop.Duration = TargetElapsedTime;
            DrawingCanvas.Resources.Add("gameloop", _gameLoop);
        }
Пример #14
0
        /// <summary>
        /// Generate a new <see cref="Guid"/> using the comb algorithm.
        /// </summary>
        private Guid GenerateComb()
        {
            byte[] guidArray = Guid.NewGuid().ToByteArray();

            DateTime baseDate = new DateTime(1900, 1, 1);
            DateTime now = DateTime.Now;

            // Get the days and milliseconds which will be used to build the byte string
            TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);
            TimeSpan msecs = now.TimeOfDay;

            // Convert to a byte array
            // Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333
            byte[] daysArray = BitConverter.GetBytes(days.Days);
            byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));

            // Reverse the bytes to match SQL Servers ordering
            Array.Reverse(daysArray);
            Array.Reverse(msecsArray);

            // Copy the bytes into the guid
            Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
            Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);

            return new Guid(guidArray);
        }
Пример #15
0
        public void Update()
        {
            if (_deploysRemaining > 0 && _time.Minutes % 15 == 0 && _time.Seconds == 0)
            {
                _deploysRemaining--;
                //_trains.Add(new Bullet(_stations["Glenhuntly"].GetPlatform(1)));
                //_trains.Add(new Bullet(_stations["Windsor"].GetPlatform(1)));
                //_trains.Add(new Bullet(_stations["Hawthorn"].GetPlatform(1)));
                //_trains.Add(new Bullet(_stations["Jolimont"].GetPlatform(1)));
                for (int i = 0; i < 75; i++)
                {
                    Station station = _links[MathUtils.Rand(0, _links.Count - 1)].InStation;
                    Platform platform = station.GetPlatform(MathUtils.Rand(1, station.PlatformCount));
                    if (!platform.IsOccupied)
                    {
                        Train train = Train.Generate(platform);
                        platform.Occupy(train);
                        _trains.Add(train);
                    }
                }
            }

            _time = _time.Add(new TimeSpan(0, 0, 1));
            foreach (Train train in _trains)
                train.Update();
        }
Пример #16
0
 public XNAAsyncDispatcher(TimeSpan dispatchInterval)
 {
     FrameworkDispatcher.Update();
     this._frameworkDispatcherTimer = new DispatcherTimer();
     this._frameworkDispatcherTimer.Tick += new EventHandler(frameworkDispatcherTimer_Tick);
     this._frameworkDispatcherTimer.Interval = dispatchInterval;
 }
Пример #17
0
        /// <summary>
        /// A simpler alternative to the irritatingly useless FileSystemWatcher
        /// </summary>
        /// <param name="file">The file to monitor</param>
        /// <param name="refreshPeriod">The refresh period.</param>
        /// <param name="scheduler">The scheduler.</param>
        /// <returns></returns>
        public static IObservable<FileNotification> WatchFile(this FileInfo file, TimeSpan? refreshPeriod = null,
            IScheduler scheduler = null)
        {
           return Observable.Create<FileNotification>(observer =>
            {
                var refresh = refreshPeriod ?? TimeSpan.FromMilliseconds(250);
                scheduler = scheduler ?? Scheduler.Default;

                FileNotification notification = null;
                return scheduler.ScheduleRecurringAction(refresh, () =>
                {
                    try
                    {
                        notification = notification == null
                            ? new FileNotification(file)
                            : new FileNotification(notification);

                        observer.OnNext(notification);
                    }
                    catch (Exception ex)
                    {
                        notification = new FileNotification(file, ex);
                        observer.OnNext(notification);
                    }
                });

            }).DistinctUntilChanged();
        }
Пример #18
0
        public override void Update()
        {
            time -= GameGlobals.gameTime.ElapsedGameTime;

            if (time < TimeSpan.Zero)
                ScreenManager.CurrentScreen = destination;
        }
 /// <summary>
 /// <para>Await until the given condition evaluates to <c>true</c> or until a timeout</para>
 /// <para>The timeout is taken from the innermost enclosing `within`
 /// block (if inside a `within` block) or the value specified in config value "akka.test.single-expect-default". 
 /// The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor 
 /// specified in config value "akka.test.timefactor"..</para>
 /// <para>A call to <paramref name="conditionIsFulfilled"/> is done immediately, then the threads sleep
 /// for about a tenth of the timeout value, before it checks the condition again. This is repeated until
 /// timeout or the condition evaluates to <c>true</c>. To specify another interval, use the overload
 /// <see cref="AwaitCondition(System.Func{bool},System.Nullable{System.TimeSpan},System.Nullable{System.TimeSpan},string)"/>
 /// </para>
 /// </summary>
 /// <param name="conditionIsFulfilled">The condition that must be fulfilled within the duration.</param>
 public void AwaitCondition(Func<bool> conditionIsFulfilled)
 {
     var maxDur = RemainingOrDefault;
     var interval = new TimeSpan(maxDur.Ticks / 10);
     var logger = _testState.TestKitSettings.LogTestKitCalls ? _testState.Log : null;
     InternalAwaitCondition(conditionIsFulfilled, maxDur, interval, (format, args) => _assertions.Fail(format, args), logger);
 }
Пример #20
0
        public static ITcpConnection CreateConnectingTcpConnection(Guid connectionId, 
                                                                   IPEndPoint remoteEndPoint, 
                                                                   TcpClientConnector connector, 
                                                                   TimeSpan connectionTimeout,
                                                                   Action<ITcpConnection> onConnectionEstablished, 
                                                                   Action<ITcpConnection, SocketError> onConnectionFailed,
                                                                   bool verbose)
        {
            var connection = new TcpConnectionLockless(connectionId, remoteEndPoint, verbose);
// ReSharper disable ImplicitlyCapturedClosure
            connector.InitConnect(remoteEndPoint,
                                  (_, socket) =>
                                  {
                                      if (connection.InitSocket(socket))
                                      {
                                          if (onConnectionEstablished != null)
                                              onConnectionEstablished(connection);
                                          connection.StartReceive();
                                          connection.TrySend();
                                      }
                                  },
                                  (_, socketError) =>
                                  {
                                      if (onConnectionFailed != null)
                                          onConnectionFailed(connection, socketError);
                                  }, connection, connectionTimeout);
// ReSharper restore ImplicitlyCapturedClosure
            return connection;
        }
Пример #21
0
 static Configuration()
 {
     AnnounceDir = ConfigurationSettings.AppSettings["AnnounceDir"].ToString();
     IconDir = ConfigurationSettings.AppSettings["IconDir"].ToString();
     AudioDir = "";
     AnnouncementMaxDuration = new TimeSpan(0, 20, 0);
 }
        internal async Task<SerialDevice> GetSerialDeviceAsync(string identifier, int baudRate, TimeSpan readTimeout, TimeSpan writeTimeout)
        {
            var deviceInformationCollection = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector());
            var selectedPort = deviceInformationCollection.FirstOrDefault(d => d.Id.Contains(identifier) || d.Name.Equals(identifier));

            if (selectedPort == null)
            {
                return null;
            }

            var serialDevice = await SerialDevice.FromIdAsync(selectedPort.Id);

            if (serialDevice == null)
            {
                return null;
            }

            serialDevice.ReadTimeout = readTimeout;
            serialDevice.WriteTimeout = writeTimeout;
            serialDevice.BaudRate = (uint)baudRate;
            serialDevice.Parity = SerialParity.None;
            serialDevice.StopBits = SerialStopBitCount.One;
            serialDevice.DataBits = 8;
            serialDevice.Handshake = SerialHandshake.None;

            Debug.WriteLine($"Found - {identifier}");

            return serialDevice;
        }
 public bool Wait(TimeSpan timeout)
 {
     SpinWait s = new SpinWait();
     bool waitResult = true;
     while (m_state == 0)
     {
         if (s.Spin() >= s_spinCount)
         {
             if (m_eventObj == null)
             {
                 ManualResetEvent newEvent =
                     new ManualResetEvent(m_state == 1);
                 if (Interlocked.CompareExchange<EventWaitHandle>(
                         ref m_eventObj, newEvent, null) == null)
                 {
                     // If someone set the flag before seeing the new
                     // event obj, we must ensure it’s been set.
                     if (m_state == 1)
                         m_eventObj.Set();
                 }
                 else
                 {
                     // Lost the race w/ another thread. Just use
                     // its event.
                     newEvent.Close();
                 }
             }
             waitResult = m_eventObj.WaitOne(timeout);
         }
     }
     return waitResult;
 }
Пример #24
0
	    public SubscriptionClient(IServiceBus bus, SubscriptionRouter router, Uri subscriptionServiceUri,
		                          TimeSpan startTimeout)
		{
			_bus = bus;
			_router = router;
			_subscriptionServiceUri = subscriptionServiceUri;
			_startTimeout = startTimeout;
			_network = router.Network;

			if (_log.IsDebugEnabled)
				_log.DebugFormat("Starting SubscriptionClient using {0}", subscriptionServiceUri);

			VerifyClientAndServiceNotOnSameEndpoint(bus);

			_ready.Reset();

			var consumerInstance = new SubscriptionMessageConsumer(_router, _network);

			_unsubscribeAction = _bus.ControlBus.SubscribeInstance(consumerInstance);
		    _unsubscribeAction += _bus.ControlBus.SubscribeContextHandler<SubscriptionRefresh>(Consume);

		    _subscriptionEndpoint = _bus.GetEndpoint(subscriptionServiceUri);
		    _producer = new SubscriptionServiceMessageProducer(router, _subscriptionEndpoint);

			WaitForSubscriptionServiceResponse();
		}
        /// <summary>
        /// 非同步刷新最新資訊
        /// </summary>
        /// <returns></returns>
        public async Task RefreshAsync() {
            HttpClient client = new HttpClient();
            HtmlDocument HTMLDoc = new HtmlDocument();
            HTMLDoc.LoadHtml(await client.GetStringAsync(DataSource));

            var script = HTMLDoc.DocumentNode.Descendants("script")
                .Where(x => x.InnerHtml?.Length > 0).Select(x => x.InnerHtml).ToArray();

            var tempAry = script.First()
                .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                .Select((x, i) => new { index = i, item = x })
                .GroupBy(x => Math.Floor(x.index / 4.0));

            this.LastPassed = null;
            this.Delay = new TimeSpan();

            foreach (var item in tempAry) {
                string[] temp = item.Select(x=>x.item).ToArray();
                if(temp[3] == "TRSearchResult.push('x')") {
                    this.LastPassed = await Station.GetStationByNameAsync(
                        innerString(temp[0],"'","'")
                        );
                }                
            }

            var time = new TimeSpan(0, int.Parse(innerString(script.Last(), "=", ";")),0);
            this.Delay= time;
        }
Пример #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GlimpseRequest" /> class.
        /// </summary>
        /// <param name="requestId">The request id.</param>
        /// <param name="requestMetadata">The request metadata.</param>
        /// <param name="tabData">The plugin data.</param>
        /// <param name="displayData">The display data</param>
        /// <param name="duration">The duration.</param>
        public GlimpseRequest(Guid requestId, IRequestMetadata requestMetadata, IDictionary<string, TabResult> tabData, IDictionary<string, TabResult> displayData, TimeSpan duration)
            : this()
        {
            RequestId = requestId;
            TabData = tabData;
            DisplayData = displayData;
            Duration = duration;

            RequestHttpMethod = requestMetadata.RequestHttpMethod;
            RequestIsAjax = requestMetadata.RequestIsAjax;
            RequestUri = requestMetadata.RequestUri;
            ResponseStatusCode = requestMetadata.ResponseStatusCode;
            ResponseContentType = requestMetadata.ResponseContentType;
            ClientId = requestMetadata.GetCookie(Constants.ClientIdCookieName) ?? requestMetadata.ClientId;
            UserAgent = requestMetadata.GetHttpHeader(Constants.UserAgentHeaderName);

            Guid parentRequestId;

#if NET35
            if (RequestIsAjax && Glimpse.Core.Backport.Net35Backport.TryParseGuid(requestMetadata.GetHttpHeader(Constants.HttpRequestHeader), out parentRequestId))
            {
                ParentRequestId = parentRequestId;
            }
#else
            if (RequestIsAjax && Guid.TryParse(requestMetadata.GetHttpHeader(Constants.HttpRequestHeader), out parentRequestId))
            {
                ParentRequestId = parentRequestId;
            }
#endif
        }
Пример #27
0
 /// <summary> Creates a ShutdownParams object with given parameters.
 /// <param name="customReason"/> and <param name="initiatedBy"/> may be null. </summary>
 public ShutdownParams(ShutdownReason reason, TimeSpan delay,
                       bool restart, [CanBeNull] string customReason,
                       [CanBeNull] Player initiatedBy)
     : this(reason, delay, restart) {
     customReasonString = customReason;
     InitiatedBy = initiatedBy;
 }
Пример #28
0
        internal APNGFrame(GraphicsDevice graphicsDevice, Frame frame)
        {
            if (frame.fcTLChunk != null)
            {
                X = (int) frame.fcTLChunk.XOffset;
                Y = (int) frame.fcTLChunk.YOffset;
                Width = (int) frame.fcTLChunk.Width;
                Height = (int) frame.fcTLChunk.Height;
                BlendOp = frame.fcTLChunk.BlendOp;
                DisposeOp = frame.fcTLChunk.DisposeOp;
                DelayTime = new TimeSpan(
                    TimeSpan.TicksPerSecond*frame.fcTLChunk.DelayNum/frame.fcTLChunk.DelayDen);
            }
            else
            {
                X = 0;
                Y = 0;
                Width = frame.IHDRChunk.Width;
                Height = frame.IHDRChunk.Height;
                BlendOp = BlendOps.APNGBlendOpSource;
                DisposeOp = DisposeOps.APNGDisposeOpNone;
                DelayTime = TimeSpan.Zero;
            }

            // frame.GetStream() is not seekable, so we build a new MemoryStream.
            FrameTexture = Texture2D.FromStream(
                graphicsDevice, new MemoryStream(frame.GetStream().ToArray()));
            MultiplyAlpha(FrameTexture);
        }
Пример #29
0
    /// <summary>
    /// Reads from the stream.
    /// </summary>
    /// <param name="timeout">The timeout.</param>
    /// <returns>Any text read from the stream.</returns>
    public string Read(TimeSpan timeout)
#endif
    {
      if (!this.byteStream.Connected || this.internalCancellation.Token.IsCancellationRequested)
      {
        return string.Empty;
      }

      StringBuilder sb = new StringBuilder();
      this.byteStream.ReceiveTimeout = (int)timeout.TotalMilliseconds;
      DateTime endInitialTimeout = DateTime.Now.Add(timeout);
      DateTime rollingTimeout = ExtendRollingTimeout(timeout);
      do
      {
        if (this.ParseResponse(sb))
        {
          rollingTimeout = ExtendRollingTimeout(timeout);
        }
      }
      while (!this.internalCancellation.Token.IsCancellationRequested && (this.IsResponsePending || IsWaitForInitialResponse(endInitialTimeout, sb) ||
#if ASYNC
                                                                                              await
#endif
                                                                                                    IsWaitForIncrementalResponse(rollingTimeout)));
      if (DateTime.Now >= rollingTimeout)
      {
        System.Diagnostics.Debug.Print("RollingTimeout exceeded {0}", DateTime.Now.ToString("ss:fff"));
      }

      return sb.ToString();
    }
Пример #30
0
        /// <summary>
        /// Calculates the indicator's components
        /// </summary>
        public override void Calculate(SlotTypes slotType)
        {
            // Calculation
            double[] adClosePrice = new double[Bars];

            for (int iBar = 1; iBar < Bars; iBar++)
                if (Time[iBar - 1].Day != Time[iBar].Day)
                    adClosePrice[iBar - 1] = Close[iBar - 1];

            // Check the last bar
            TimeSpan tsBarClosing = Time[Bars - 1].TimeOfDay.Add(new TimeSpan(0, (int)Period, 0));
            TimeSpan tsDayClosing = new TimeSpan(24, 0, 0);
            if (tsBarClosing == tsDayClosing)
                adClosePrice[Bars - 1] = Close[Bars - 1];

            // Saving the components
            Component = new IndicatorComp[1];

            Component[0]           = new IndicatorComp();
            Component[0].CompName  = "Closing price of the day";
            Component[0].DataType  = IndComponentType.ClosePrice;
            Component[0].ChartType = IndChartType.NoChart;
            Component[0].FirstBar  = 2;
            Component[0].Value     = adClosePrice;

            return;
        }