/// <summary> /// Sets the time on the specified DateTime value using the specified time zone. /// </summary> /// <param name = "datetimeOff">The base date.</param> /// <param name = "timespan">The TimeSpan to be applied.</param> /// <param name = "localTimeZone">The local time zone.</param> /// <returns>/// The DateTimeOffset including the new time value/// </returns> public static DateTimeOffset SetTime(this DateTimeOffset datetimeOff, TimeSpan timespan, TimeZoneInfo localTimeZone) { var localDate = datetimeOff.ToLocalDateTime(localTimeZone); localDate.SetTime(timespan); return localDate.ToDateTimeOffset(localTimeZone); }
public Reglage(TimeSpan date, double lumiere, double temperatureInterieur, double temperatureExterieur, double humidite, double vent) { this.duree = date; this.lumiere = lumiere; this.temperatureInterieur = temperatureInterieur; this.humidite = humidite; this.vent = vent; }
public static PlantUmlConnection Get(TimeSpan timeout) { if (_connectionPool.Count == 0) { _availableEvent.Reset(); if (_availableEvent.WaitOne(timeout)) { return _connectionPool.Dequeue(); } else { return null; } } else { lock (_connectionPool) { if (_connectionPool.Count == 0) return null; else return _connectionPool.Dequeue(); } } }
public Reglage(ReglageViewModel rvm){ Id = rvm.IdReglage; Duree = new TimeSpan(rvm.Duree, 0, 0, 0); Lumiere = Math.Round(rvm.Lumiere, 2); TemperatureInterieur = Math.Round(rvm.TemperatureInterieur, 2); Humidite = Math.Round(rvm.Humidite, 2); }
private void RetrieveFileData(HttpContext context, string filePath, string container) { MediaFileModel resultModel = new MediaFileModel(); // only send request to imageprocessor if querystring exists; can exclude other parameters if needed if (context.Request.RawUrl.Contains("?")) { resultModel = MediaHelper.GetMediaFile(filePath, container, context.Request.RawUrl); } else { resultModel = MediaHelper.GetMediaFile(filePath, container); } if (resultModel.RedirectToAzureStorage) { context.Response.Redirect(filePath.Replace($"/{container}", $"{ConfigurationManager.AppSettings["BlobStorage"]}/{container}"), true); } var myTimeSpan = new TimeSpan(7, 0, 0, 0); context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.SetValidUntilExpires(true); context.Response.Cache.SetMaxAge(myTimeSpan); context.Response.Cache.SetLastModified(resultModel.LastModifiedDate); context.Response.Cache.SetETag(resultModel.ETag.Replace("\\\"", "")); context.Response.AddHeader("Content-MD5", resultModel.ContentMd5); context.Response.ContentType = resultModel.ContentType; // replicate properties returned by blob storage context.Response.AddHeader("Server", "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0"); context.Response.AddHeader("x-ms-request-id", Guid.NewGuid().ToString()); context.Response.AddHeader("x-ms-version", "2009-09-19"); context.Response.AddHeader("x-ms-lease-status", "unlocked"); context.Response.AddHeader("x-ms-blob-type", "BlockBlob"); context.Response.OutputStream.Write(resultModel.ImageData, 0, resultModel.ImageData.Length); context.Response.AddHeader("Content-Length", resultModel.ImageData.Length.ToString()); context.Response.Flush(); context.Response.End(); }
protected void Page_Load(object sender, EventArgs e) { string htmlstring = ""; News spfNews = new News(); int RecordCount = spfNews.LoadSpfNews(); if (RecordCount > 0) { for (int i = 0; i < RecordCount; ++i) { TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks); TimeSpan ts2 = new TimeSpan(spfNews.SpfNews[i].updateTime.Ticks); TimeSpan ts = ts1.Subtract(ts2).Duration(); // string strA = null; // if ( ts.Days/365 > 0 ) strA = (ts.Days/365).ToString() + " 年之前"; // else // { // if ( ts.Days/30 > 0 ) strA = (ts.Days/30).ToString() + " 月之前"; // else // { // if ( ts.Days > 0 ) strA = ts.Days.ToString() + " 天之前"; // else // { // if ( ts.Hours > 0 ) strA = ts.Hours.ToString() + " 小时之前"; // else // { // if ( ts.Minutes > 0 ) strA = ts.Minutes.ToString() + " 分钟之前"; // else // { // if ( ts.Seconds > 0 ) strA = ts.Seconds.ToString() + " 秒之前"; // } // } // } // } // } //string strB = Function.getDateTimeLaterThan(spfNews.SpfNews[i].updateTime.Ticks); htmlstring += "<div class=\"art-post post-94269 post type-post status-publish format-standard hentry category-camera-lens tag-canon tag-ebay\">\n" + "<div class=\"art-post-body\">\n" + "<div class=\"art-post-inner art-article\">\n" + "<div class=\"updatetime\">发布在 " + Function.getDateTimeLaterThan(spfNews.SpfNews[i].updateTime) + "</div>\n" + "<div class=\"art-article-up\">\n" + "<h2 class=\"art-postheader\">" + (i+1).ToString() + ". " + spfNews.SpfNews[i].newsTitle + "</h2>\n" + "<div class=\"art-postcontent\">\n" + spfNews.SpfNews[i].newsContent + "</div>\n" + "</div>\n" + "<div class=\"cleared\"></div>\n" + "</div>\n" + "<div class=\"cleared\"></div>\n" + "</div>\n" + "</div>\n"; } } else htmlstring += "●暂无信息\n"; this.div_post.InnerHtml = htmlstring; }
/// <summary> /// Datetime转Json时间,datetime - 1970.1.1 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static int UnixTicks(DateTime dt) { DateTime d1 = new DateTime(1970, 1, 1); DateTime d2 = dt.ToUniversalTime(); TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks); return (int)ts.TotalSeconds; }
public UserLoginSession(string sessionID, long id, TimeSpan sessionTimeout) { SessionID = sessionID; Id = id; SessionTimeout = sessionTimeout; }
public void StartCountdown(int hours, int minutes, int seconds, Action callback) { countFrom = new TimeSpan(hours, minutes, seconds); stopWatch = new Stopwatch(); cb = callback; stopWatch.Start(); }
private SceneManager() { mUpdateCallback = new EditorApplication.CallbackFunction(EditorUpdate); if (EditorApplication.update == null) { EditorApplication.update += mUpdateCallback; } else if (!EditorApplication.update.Equals(mUpdateCallback)) { EditorApplication.update += mUpdateCallback; } mRefreshThreshold = new TimeSpan(0, 0, 0, SECONDS_TO_WAIT, 0); // We force a config.xml read operation before the SceneManager is used // to avoid inconsistencies on Unity startup. mDoDeserialization = true; // Make sure that the scene is initialized whenever a new instance of // the SceneManager is created. mSceneInitialized = false; // Unity does not allow to store global editor settings in a comfortable // way so we store them in a file. ReadProperties(); }
/// <summary> /// Calculates the position of this vessel at some future universal timestamp, /// taking into account all currently predicted SOI transition patches, and also /// assuming that all the planned maneuver nodes will actually be executed precisely /// as planned. Note that this cannot "see" into the future any farther than the /// KSP orbit patches setting allows for. /// </summary> /// <param name="timeStamp">The time to predict for. Although the intention is to /// predict for a future time, it could be used to predict for a past time.</param> /// <returns>The position as a user-readable Vector in Shared.Vessel-origin raw rotation coordinates.</returns> override public Vector GetPositionAtUT(TimeSpan timeStamp) { string blockingTech; if (!Career.CanMakeNodes(out blockingTech)) throw new KOSLowTechException("use POSITIONAT on a vessel", blockingTech); double desiredUT = timeStamp.ToUnixStyleTime(); Orbit patch = GetOrbitAtUT(desiredUT); Vector3d pos = patch.getPositionAtUT(desiredUT); // This is an ugly workaround to fix what is probably a bug in KSP's API: // If looking at a future orbit patch around a child body of the current body, then // the various get{Thingy}AtUT() methods return numbers calculated incorrectly as // if the child body was going to remain stationary where it is now, rather than // taking into account where it will be later when the intercept happens. // This corrects for that case: if (Utils.BodyOrbitsBody(patch.referenceBody, Vessel.orbit.referenceBody)) { Vector3d futureSOIPosNow = patch.referenceBody.position; Vector3d futureSOIPosLater = patch.referenceBody.getPositionAtUT(desiredUT); Vector3d offset = futureSOIPosLater - futureSOIPosNow; pos = pos + offset; } return new Vector(pos - Shared.Vessel.findWorldCenterOfMass()); // Convert to ship-centered frame. }
public OpenCollectionAsyncResult(TimeSpan timeout, AsyncCallback otherCallback, object state, IList<ICommunicationObject> collection) : base(otherCallback, state) { _timeoutHelper = new TimeoutHelper(timeout); _completedSynchronously = true; _count = collection.Count; if (_count == 0) { Complete(true); return; } for (int index = 0; index < collection.Count; index++) { // Throw exception if there was a failure calling EndOpen in the callback (skips remaining items) if (_exception != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_exception); CallbackState callbackState = new CallbackState(this, collection[index]); IAsyncResult result = collection[index].BeginOpen(_timeoutHelper.RemainingTime(), s_nestedCallback, callbackState); if (result.CompletedSynchronously) { collection[index].EndOpen(result); Decrement(true); } } }
public RetryConditionHeaderValue (TimeSpan delta) { if (delta.TotalSeconds > uint.MaxValue) throw new ArgumentOutOfRangeException ("delta"); Delta = delta; }
static void Main(string[] args) { Console.Title = "Date and time after 6 hours and 30 minutes"; Thread.CurrentThread.CurrentCulture = new CultureInfo("bg-BG"); Console.ForegroundColor = ConsoleColor.Green; Console.Write("Enter a date and time: "); string dateAndTime = Console.ReadLine(); try { DateTime date = DateTime.ParseExact(dateAndTime, "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture); TimeSpan after = new TimeSpan(6, 30, 0); date = date.Add(after); Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("\nThe date after 6 hours and 30 minutes is: {0} {1:dd.MM.yyyy hh:mm:ss}", date.ToString("dddd"), date); } catch (FormatException) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\nYou have entered a wrong date or time!!!"); } finally { Console.WriteLine(); Console.ResetColor(); } }
public HttpClient (HttpMessageHandler handler, bool disposeHandler) : base (handler, disposeHandler) { buffer_size = int.MaxValue; timeout = TimeoutDefault; cts = new CancellationTokenSource (); }
public static IEnumerator GetRequest(string url, object ud, int tag, INetCallback callback, IHttpCallback httpCallback, bool showLoading) { DateTime start = DateTime.Now; HttpPackage hp = new HttpPackage(); hp.w = new WWW(url); hp.Tag = tag; hp.FuncCallback = callback; if (RequestNotify != null && showLoading) { RequestNotify(Net.Status.eStartRequest); } yield return hp.w; if (RequestNotify != null && showLoading) { RequestNotify(Net.Status.eEndRequest); } if(null != httpCallback) { TimeSpan tsStart = new TimeSpan(start.Ticks); TimeSpan tsEnd = new TimeSpan(DateTime.Now.Ticks); TimeSpan ts = tsEnd.Subtract(tsStart).Duration(); if(ts.Seconds > OVER_TIME) { hp.overTime = true; } httpCallback.OnHttpRespond(hp, ud); } else { Debug.Log("no http callback"); } }
private void SetTimerCountDownText(TimeSpan timeLeft) { var minutes = timeLeft.Minutes.ToString(); var seconds = (timeLeft.Seconds < 10) ? "0" + timeLeft.Seconds : timeLeft.Seconds.ToString(); txtTimerCountDown.Text = minutes + ":" + seconds; }
protected void btIngresar_Click(object sender, EventArgs e) { if (!validarHoras()) { return; } TimeSpan horaCitaInicio = new TimeSpan(timeSelectorHoraEmpieza.Hour, timeSelectorHoraEmpieza.Minute, 0); TimeSpan horaCitaFinaliza = new TimeSpan(timeSelectorHoraTermina.Hour, timeSelectorHoraTermina.Minute, 0); DateTime fechaCita = DateTime.Parse(txtfecha.Text); int prefijo = intIdCentro; try { BL.Citas cita = new BL.Citas(); if (cita.existeCitaTerapiaProgramada(fechaCita.Date,horaCitaInicio,horaCitaFinaliza,cmbEmpleados.Text) ) { Response.Write("<script>alert('El terapeuta ya tiene una cita en esta hora y fecha')</script>"); } else { cita.NuevaCitaTerapia(fechaCita.Date,cmbEmpleados.Text,intIdCentro,long.Parse(txtNumExpediente.Text),horaCitaInicio,horaCitaFinaliza); Response.Write("<script>alert('Se ha agregado la cita!')</script>"); } LimpiarControles(); } catch (Exception ex) { Session["Error_Msg"] = "Ha ocurrido un error al intentar agregar la cita, compruebe el número de expediente"; Response.Redirect("~/Error.aspx", true); } }
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; }
public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval, ArraySegment<byte> internalBuffer) { throw new PlatformNotSupportedException(); }
static int Main() { DateTime uepoch = new DateTime (1970, 1, 1); if (uepoch.Ticks != 621355968000000000) return 1; TimeSpan ts = new TimeSpan (1, 0, 0); Console.WriteLine (ts.Ticks); return 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; }
internal TcpConnectionPoolSettings(TcpConnectionPoolSettings tcp) { this.groupName = tcp.groupName; this.idleTimeout = tcp.idleTimeout; this.leaseTimeout = tcp.leaseTimeout; this.maxOutboundConnectionsPerEndpoint = tcp.maxOutboundConnectionsPerEndpoint; }
public bool TryAcquire(TimeSpan timeout) { long tm = (long)timeout.TotalMilliseconds; if (tm < -1 || tm > (long)Int32.MaxValue) throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); return TryAcquire((int)tm); }
internal TcpConnectionPoolSettings() { groupName = ConnectionOrientedTransportDefaults.ConnectionPoolGroupName; idleTimeout = ConnectionOrientedTransportDefaults.IdleTimeout; leaseTimeout = TcpTransportDefaults.ConnectionLeaseTimeout; maxOutboundConnectionsPerEndpoint = ConnectionOrientedTransportDefaults.MaxOutboundConnectionsPerEndpoint; }
public static string NormalizeTimpstamp0(long timpStamp) { long unixTime = timpStamp * 10000000L; TimeSpan toNow = new TimeSpan(unixTime); DateTime dt = dtStart.Add(toNow); return dt.ToString("yyyy-MM-dd"); }
public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when The parameters specify a TimeSpan value less than MinValue"); try { TimeSpan ts = new TimeSpan(Int32.MinValue, Int32.MinValue, Int32.MinValue, Int32.MinValue, Int32.MinValue); TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown when The parameters specify a TimeSpan value less than MinValue"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public bool EnterAsync(TimeSpan timeout, FastAsyncCallback callback, object state) { Fx.Assert(callback != null, "must have a non-null call back for async purposes"); AsyncWaitHandle waiter = null; lock (this.ThisLock) { if (this.aborted) { throw Fx.Exception.AsError(CreateObjectAbortedException()); } if (this.count < this.maxCount) { this.count++; return true; } waiter = new AsyncWaitHandle(); this.Waiters.Enqueue(waiter); } return waiter.WaitAsync(EnteredAsyncCallback, new EnterAsyncData(this, waiter, callback, state), timeout); }
// Default constructor. If a derived class does not invoke a base- // class constructor explicitly, the default constructor is called // implicitly. public WorkItem() { ID = 0; Title = "Default title"; Description = "Default description."; jobLength = new TimeSpan(); }
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; }
public void _TimeSpan_Const() { TestConst(TimeSpan.FromDays(5)); TestConst(null); }
public static IDotvvmServiceCollection AddDefaultTempStorages(this IDotvvmServiceCollection services, string tempPath, TimeSpan autoDeleteInterval) { return(services .AddUploadedFileStorage(Path.Combine(tempPath, "uploadedFiles"), autoDeleteInterval) .AddReturnedFileStorage(Path.Combine(tempPath, "returnedFiles"), autoDeleteInterval)); }
public static IDotvvmServiceCollection AddDefaultTempStorages(this IDotvvmServiceCollection services, string tempPath) => services.AddDefaultTempStorages(tempPath, TimeSpan.FromMinutes(30));
public async Task GetResponseAsync(HttpListenerContext context, string localBaseUrl, string remoteBaseUrl, CancellationToken ct) { string postUri = null; if (context.Request.IsWebSocketRequest) { UriBuilder ub = new UriBuilder(PostUri) { Scheme = "wss" }; postUri = ub.Uri.ToString(); } else { postUri = PostUri.ToString(); } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUri); request.Method = context.Request.HttpMethod; request.ServerCertificateValidationCallback += ValidateCertificate; if (!context.Request.IsWebSocketRequest) { SetRequestHeaders(request, context.Request.Headers, localBaseUrl, remoteBaseUrl); } // Add RTVS headers var remoteUri = GetRemoteUri(context.Request.Url, remoteBaseUrl); request.Headers.Add(CustomHttpHeaders.RTVSRequestedURL, remoteUri.ToString()); if (context.Request.ContentLength64 > 0) { using (Stream reqStream = await request.GetRequestStreamAsync()) { await context.Request.InputStream.CopyAndFlushAsync(reqStream, null, ct); } } HttpWebResponse response = null; try { response = (HttpWebResponse)await request.GetResponseAsync(); if (response != null) { if (context.Request.IsWebSocketRequest && response.StatusCode == HttpStatusCode.SwitchingProtocols) { Stream respStream = response.GetResponseStream(); string subProtocol = response.Headers[Constants.Headers.SecWebSocketProtocol]; var remoteWebSocket = CommonWebSocket.CreateClientWebSocket(respStream, subProtocol, TimeSpan.FromMinutes(10), receiveBufferSize: 65335, useZeroMask: true); var websocketContext = await context.AcceptWebSocketAsync(subProtocol, receiveBufferSize: 65335, keepAliveInterval: TimeSpan.FromMinutes(10)); await WebSocketHelper.SendReceiveAsync(websocketContext.WebSocket, remoteWebSocket, ct); } else { context.Response.StatusCode = (int)response.StatusCode; SetResponseHeaders(response, context.Response, localBaseUrl, remoteBaseUrl); using (Stream respStream = response.GetResponseStream()) using (Stream outStream = context.Response.OutputStream) { await respStream.CopyAndFlushAsync(outStream, null, ct); } response.Close(); } } } catch (WebException wex) when (wex.Status == WebExceptionStatus.ProtocolError) { response = wex.Response as HttpWebResponse; } catch (OperationCanceledException) { WebServer.Stop(remoteUri.Port); } catch (Exception ex) when (!ex.IsCriticalException()) { _log?.WriteLine(LogVerbosity.Normal, MessageCategory.Error, Resources.Error_RemoteWebServerException.FormatInvariant(ex.Message)); _console?.WriteErrorLine(Resources.Error_RemoteWebServerException.FormatInvariant(ex.Message)); WebServer.Stop(remoteUri.Port); } finally { response?.Close(); } }
private VendorRentalDuration(TimeSpan duration, int name) { this.m_Duration = duration; this.m_Name = name; }
public async Task SendToKafka(String message) { var res = await producer.ProduceAsync(topic, new Message<Null, string> { Value = message }); producer.Flush(TimeSpan.FromSeconds(10)); logger.LogInfo($"KAFKA => Delivered '{res.Value}' to '{res.TopicPartitionOffset}'"); }
public void _TimeSpan_FromString() { var x = TimeSpan.FromDays(5); TestFromString(x.ToString(), x); TestFromString(null, null); }
public void _TimeSpan_CastToString() { TestCastToString(TimeSpan.FromDays(5), "5.00:00:00"); TestCastToString(null, null); }
private async Task <T> TryConnect <T>(Func <TcpClient, Task <T> > doOperation, TimeSpan connectTimeout) { using (var client = new TcpClient()) { try { var cancelTask = Task.Delay(connectTimeout); var connectTask = client.ConnectAsync( this.Endpoint.Address, this.Endpoint.Port); await await Task.WhenAny(connectTask, cancelTask); if (cancelTask.IsCanceled) { //If cancelTask and connectTask both finish at the same time, //we'll consider it to be a timeout. throw new TaskCanceledException("Socket Operation Timed Out"); } if (client.Connected) { return(await doOperation(client)); } } catch (Exception e) when(e is TaskCanceledException || e is ObjectDisposedException || e is SocketException) { // already disposed or no listener } catch (Exception e) { this._logger.Information(e, "Caught IP Comm Client Exception"); } } return(default);
public void _TimeSpan_Implicit() { TestImplicit(TimeSpan.FromDays(5)); TestImplicit(null); }
private void StartOnServerDomain<TModulesProvider>(string connectionString, string applicationName) where TModulesProvider:ModuleBase{ var serverApplication = GetServerApplication(); serverApplication.Modules.Add(Activator.CreateInstance<TModulesProvider>()); serverApplication.ApplicationName = applicationName; serverApplication.ConnectionString = connectionString; serverApplication.Setup(); serverApplication.Logon(); var objectSpaceProvider = serverApplication.ObjectSpaceProvider; var xpoUserActivityVersionType = XpandModuleBase.GetDxBaseImplType("DevExpress.ExpressApp.Workflow.Versioning.XpoUserActivityVersion"); var engine=(WorkflowVersioningEngine) typeof(PersistentWorkflowVersioningEngine<>).MakeGenericType(xpoUserActivityVersionType).CreateInstance(objectSpaceProvider); var workflowDefinitionProvider = (IWorkflowDefinitionProvider)typeof(XpandWorkflowDefinitionProvider<>).MakeGenericType(xpoUserActivityVersionType).CreateInstance(XpandWorkFlowModule.WorkflowTypes.ToList(),engine); var xpandWorkflowServer = new XpandWorkflowServer("http://localhost:46232", workflowDefinitionProvider, objectSpaceProvider); xpandWorkflowServer.CustomizeHost += delegate (object sender, CustomizeHostEventArgs e) { // NOTE: Uncomment this section to use alternative workflow configuration. // // SqlWorkflowInstanceStoreBehavior // //e.WorkflowInstanceStoreBehavior = null; //System.ServiceModel.Activities.Description.SqlWorkflowInstanceStoreBehavior sqlWorkflowInstanceStoreBehavior = new System.ServiceModel.Activities.Description.SqlWorkflowInstanceStoreBehavior("Integrated Security=SSPI;Pooling=false;Data Source=(local);Initial Catalog=WorkflowsStore"); //sqlWorkflowInstanceStoreBehavior.RunnableInstancesDetectionPeriod = TimeSpan.FromSeconds(2); //e.Host.Description.Behaviors.Add(sqlWorkflowInstanceStoreBehavior); //e.WorkflowIdleBehavior.TimeToPersist = TimeSpan.FromSeconds(1); //e.WorkflowIdleBehavior.TimeToPersist = TimeSpan.FromSeconds(10); //e.WorkflowIdleBehavior.TimeToUnload = TimeSpan.FromSeconds(10); e.WorkflowInstanceStoreBehavior.WorkflowInstanceStore.RunnableInstancesDetectionPeriod = TimeSpan.FromSeconds(2); }; _server= xpandWorkflowServer; _server.CustomHandleException += delegate(object sender, CustomHandleServiceExceptionEventArgs e) { Tracing.Tracer.LogError(e.Exception); OnServerDomainCustomHandleException?.Invoke(this, new ExceptionEventArgs("Exception occurs:\r\n\r\n" + e.Exception.Message + "\r\n\r\n'" + e.Service.GetType() + "' service")); e.Handled = true; }; _server.Start(); }
public void _TimeSpan_Param() { TestParam(TimeSpan.FromDays(5)); TestParam(null); }
public void SetResponseTimeout(TimeSpan timeout) { responseTimeout = timeout; }
private async Task RestartSiloAfterCheckpointTestRunner(string streamNamespace, int streamCount, int eventsInStream) { List<Guid> streamGuids = Enumerable.Range(0, streamCount).Select(_ => Guid.NewGuid()).ToList(); try { await GenerateEvents(streamNamespace, streamGuids, eventsInStream, 0); await TestingUtils.WaitUntilAsync(assertIsTrue => CheckCounters(streamNamespace, streamCount, eventsInStream, assertIsTrue), TimeSpan.FromSeconds(60)); HostedCluster.RestartSilo(HostedCluster.SecondarySilos[0]); await HostedCluster.WaitForLivenessToStabilizeAsync(); await GenerateEvents(streamNamespace, streamGuids, eventsInStream, 0); await TestingUtils.WaitUntilAsync(assertIsTrue => CheckCounters(streamNamespace, streamCount, eventsInStream * 2, assertIsTrue), TimeSpan.FromSeconds(90)); } finally { var reporter = this.GrainFactory.GetGrain<IGeneratedEventReporterGrain>(GeneratedStreamTestConstants.ReporterId); reporter.Reset().Ignore(); } }
public BatchExecutor(int batchSize, Func <IReadOnlyList <TItem>, Task <IDictionary <TItem, TResult> > > batchExecutor, TimeSpan bufferFlushInterval) { _batchSize = batchSize; _counterZeroingThreshold = int.MaxValue / _batchSize * _batchSize; _batchExecutor = batchExecutor ?? throw new ArgumentNullException(nameof(batchExecutor)); _flushTimer = new Timer(BufferFlushCallback, null, bufferFlushInterval, bufferFlushInterval); }
public Task <IGrainReminder> RegisterOrUpdateReminder(string reminderName, TimeSpan dueTime, TimeSpan period) { throw new InvalidOperationException("RegisterReminder can only be called from inside a grain"); }
public static ContractAllowance GetFromCache(string emplid, DateTime effDate) { string key = emplid + "$$" + effDate; return CONTRACT_ALLOWANCE_CACHE.Get(key, () => GetContractAllowance(emplid, effDate), TimeSpan.FromHours(1)); }
public OutsideRuntimeClient(ClientConfiguration cfg, GrainFactory grainFactory, bool secondary = false) { this.grainFactory = grainFactory; this.clientId = GrainId.NewClientId(); if (cfg == null) { Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object."); throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg"); } this.config = cfg; if (!TraceLogger.IsInitialized) { TraceLogger.Initialize(config); } StatisticsCollector.Initialize(config); SerializationManager.Initialize(config.UseStandardSerializer); logger = TraceLogger.GetLogger("OutsideRuntimeClient", TraceLogger.LoggerType.Runtime); appLogger = TraceLogger.GetLogger("Application", TraceLogger.LoggerType.Application); try { LoadAdditionalAssemblies(); PlacementStrategy.Initialize(); callbacks = new ConcurrentDictionary <CorrelationId, CallbackData>(); localObjects = new ConcurrentDictionary <GuidId, LocalObjectData>(); if (!secondary) { UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException); } // Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked SerializationManager.GetDeserializer(typeof(String)); clientProviderRuntime = new ClientProviderRuntime(grainFactory); statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime); var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations) .WaitForResultWithThrow(initTimeout); if (statsProviderName != null) { config.StatisticsProviderName = statsProviderName; } responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout; BufferPool.InitGlobalBufferPool(config); var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface); // Client init / sign-on message logger.Info(ErrorCode.ClientInitializing, string.Format( "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}", BARS, config.DNSHostName, localAddress, clientId)); string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}'", BARS, RuntimeVersion.Current); startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config); logger.Info(ErrorCode.ClientStarting, startMsg); if (TestOnlyThrowExceptionDuringInit) { throw new Exception("TestOnlyThrowExceptionDuringInit"); } config.CheckGatewayProviderSettings(); var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative var gatewayListProvider = GatewayProviderFactory.CreateGatewayListProvider(config) .WithTimeout(initTimeout).Result; transport = new ProxiedMessageCenter(config, localAddress, generation, clientId, gatewayListProvider); if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver"); } } catch (Exception exc) { if (logger != null) { logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc); } ConstructorReset(); throw; } }
private static void AssemblyWatcher_Changed(object sender, FileSystemEventArgs e) { if (!SharedRuntimeState.IsActiveRuntime) { return; } lock (assemblyWatchers) { // Require 500 milliseconds between updates to avoid multiple reloads // // Note: This may result in a genuine change to be missed which means // that some user action will be needed // // PossibleFix: Make this delayed and only catch the latest one? (will slow // reloads based on delay interval) if (lastAssemblyUpdate < DateTime.Now - TimeSpan.FromMilliseconds(500) && !isAssemblyWatcherReloading) { bool complete = false; bool hasChanged = false; const int tries = 20; const int sleep = 40;// 40*20 = 800 milliseconds of attempts (due to file locks whilst being written by AssemblyRewriter) for (int i = 0; i < tries; i++) { try { if (File.Exists(e.FullPath)) { using (FileStream reader = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { if (reader.Length > 8) { reader.Position = reader.Length - 8; byte[] buffer = new byte[8]; reader.Read(buffer, 0, buffer.Length); long signature = BitConverter.ToInt64(buffer, 0); if (signature == 3110675979262317867)// "+UEsRW++" { hasChanged = true; } } } } complete = true; break; } catch (IOException) { Thread.Sleep(sleep); } catch (Exception exception) { // Some unknown exception SharedRuntimeState.LogWarning("Exception whilst hotreloading '" + e.FullPath + "'\n" + exception); complete = true; break; } } if (hasChanged) { isAssemblyWatcherReloading = true; ReloadMainContext(); lastAssemblyUpdate = DateTime.Now; isAssemblyWatcherReloading = false; } else if (!complete) { SharedRuntimeState.LogWarning("Hotreload timed out for '" + e.FullPath + "'"); } } } }
public CreateViewModel(INavigationService navigator, INotificationManager notificationManager, IDialogs dialogs) { this.notificationManager = notificationManager; this.NavToChannels = navigator.NavigateCommand("NotificationChannels"); this.WhenAnyValue ( x => x.SelectedDate, x => x.SelectedTime ) .Select(x => new DateTime( x.Item1.Year, x.Item1.Month, x.Item1.Day, x.Item2.Hours, x.Item2.Minutes, x.Item2.Seconds) ) .ToPropertyEx(this, x => x.ScheduledTime) .DisposeWith(this.DestroyWith); this.SelectedDate = DateTime.Now; this.SelectedTime = DateTime.Now.TimeOfDay.Add(TimeSpan.FromMinutes(1)); this.SendNow = ReactiveCommand.CreateFromTask(() => this.BuildAndSend( "现在测试", "这是对sendnow的测试", null )); this.Send = ReactiveCommand.CreateFromTask( async() => { await this.BuildAndSend( this.NotificationTitle, this.NotificationMessage, this.ScheduledTime ); await dialogs.Snackbar("通知发送成功"); }, this.WhenAny( x => x.NotificationTitle, x => x.NotificationMessage, x => x.ScheduledTime, (title, msg, sch) => !title.GetValue().IsEmpty() && !msg.GetValue().IsEmpty() && sch.GetValue() > DateTime.Now ) ); this.PermissionCheck = ReactiveCommand.CreateFromTask(async() => { var result = await notificationManager.RequestAccess(); await dialogs.Snackbar("权限检查结果: " + result); }); this.StartChat = ReactiveCommand.CreateFromTask(() => notificationManager.Send( "聊天室", "嗨,你的名字是?", "ChatName", DateTime.Now.AddSeconds(10) ) ); }
/// <inheritdoc cref="IEventExecutor"/> public virtual IScheduledTask Schedule(Action action, TimeSpan delay) { throw new NotSupportedException(); }
public void SetCurrentPlayTime_Async(TimeSpan value) { EnqueueWorkItem(new WorkItem(new SetPositionWorkItemDelegate(_playbackProcessor.SetPosition), value)); }
/// <inheritdoc cref="IEventExecutor"/> public virtual Task ScheduleAsync(Action <object, object> action, object context, object state, TimeSpan delay, CancellationToken cancellationToken) { throw new NotSupportedException(); }
/// <inheritdoc cref="IEventExecutor"/> public virtual IScheduledTask Schedule(Action <object, object> action, object context, object state, TimeSpan delay) { throw new NotSupportedException(); }
/// <inheritdoc cref="IEventExecutor"/> public virtual Task ScheduleAsync(Action action, TimeSpan delay, CancellationToken cancellationToken) { throw new NotSupportedException(); }
/// <inheritdoc cref="IEventExecutor"/> public abstract Task ShutdownGracefullyAsync(TimeSpan quietPeriod, TimeSpan timeout);
public void GetTimeElapsed() { TimeSpan timeElapsed = Enddate.Date - startdate.Date; resultLabel.Text = String.Format("{0} day{1} between dates", timeElapsed.Days, timeElapsed.Days == 1 ? "" : "s"); }
/// <inheritdoc cref="IEventExecutor"/> public virtual Task ScheduleAsync(Action <object, object> action, object context, object state, TimeSpan delay) => this.ScheduleAsync(action, context, state, delay, CancellationToken.None);
protected SingleThreadEventExecutorOld(IEventExecutorGroup parent, string threadName, TimeSpan breakoutInterval, IQueue <IRunnable> taskQueue) : base(parent) { _firstTask = true; _emptyEvent = new ManualResetEventSlim(false, 1); _shutdownHooks = new HashSet <Action>(); _loopAction = Loop; _loopCoreAciton = LoopCore; _terminationCompletionSource = NewPromise(); _taskQueue = taskQueue; _preciseBreakoutInterval = PreciseTimeSpan.FromTimeSpan(breakoutInterval); _scheduler = new ExecutorTaskScheduler(this); _thread = new Thread(_loopAction); if (string.IsNullOrEmpty(threadName)) { _thread.Name = DefaultWorkerThreadName; } else { _thread.Name = threadName; } _thread.Start(); }
/// <inheritdoc cref="IEventExecutor"/> public virtual Task ScheduleAsync(Action action, TimeSpan delay) => this.ScheduleAsync(action, delay, CancellationToken.None);