public void Add(Timeout newTimeout) { lock (listLock) { timeouts.Add(newTimeout); } }
public void Add(Timeout newTimeout) { using (var connection = new SqlConnection(connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = string.Format( @"insert into [{0}] (time_to_return, correlation_id, reply_to) values (@time_to_return, @correlation_id, @reply_to)", timeoutsTableName); command.Parameters.AddWithValue("time_to_return", newTimeout.TimeToReturn); command.Parameters.AddWithValue("correlation_id", newTimeout.CorrelationId); command.Parameters.AddWithValue("reply_to", newTimeout.ReplyTo); try { command.ExecuteNonQuery(); } catch (SqlException ex) { if (ex.Number != PrimaryKeyViolationNumber) throw; } } } }
public ProcessorCommand(object command, Timeout timeout) { Argument.RequiresNotNull(command, nameof(command)); this.CommandID = Guid.NewGuid(); this.Command = command; this.Timeout = timeout; }
public UnicornLauncher(Timeout _timeout, bool useTinfoilShielding) { Timeout = _timeout; if(useTinfoilShielding) { shieldtype = "tinfoil"; } }
public TimeoutData(Timeout.Core.TimeoutData data) { Destination = data.Destination; SagaId = data.SagaId; State = data.State; Time = data.Time; OwningTimeoutManager = data.OwningTimeoutManager; Headers = data.Headers; }
public static Timeout RunMax(TimeSpan timeSpan, LockingThreadTimeoutDelegate lockingThreadTimeoutDelegate) { Timeout toReturn = new Timeout(); toReturn.Thread = Thread.CurrentThread; toReturn.LockingThreadTimeoutDelegate = lockingThreadTimeoutDelegate; toReturn.Timer = new Timer(toReturn.HandleTimeout, null, Convert.ToInt32(timeSpan.TotalMilliseconds), System.Threading.Timeout.Infinite); return toReturn; }
public News() { try { _hideDetailTimeout = new Timeout(() => HideDetail()); _hideDetailTimeout.Duration = TimeSpan.FromMinutes(5); } catch { // Also used in background thread. } }
public void AddTimeout(Timeout timeout) { int i; for (i = 0; i < timeouts.Count; i++) { if (timeouts [i].expires > timeout.expires) break; } if (i == timeouts.Count) timeouts.Add (timeout); else timeouts.Insert (0, timeout); }
public void Check(IProbe probe) { var timeout = new Timeout(_timeoutMillis); while (!probe.IsSatisfied) { if (timeout.HasTimedOut()) { Assert.Fail(DescribeFailureOf(probe)); } Thread.Sleep(_pollDelayMillis); probe.Sample(); } }
private void AddTimeout(Timeout timeout) { LinkedListNode<Timeout> currentNode; lock (_locker) { for (currentNode = _timeouts.First; currentNode != null; currentNode = currentNode.Next) { if (timeout.ElapseTime > currentNode.Value.ElapseTime) continue; _timeouts.AddBefore(currentNode, timeout); break; } if (currentNode == null) _timeouts.AddLast(timeout); ResetTimer(); } }
public void GetNextChunkReturnsOneTimeoutWhenCollectionHasOneTimeout( MongoTimeoutPersister sut, MongoDatabaseFactory factory, Timeout.Core.TimeoutData timeoutData) { factory.ResetTimeoutCollection(); timeoutData.Time = DateTime.UtcNow.AddMinutes(-1); sut.Add(timeoutData); var startSlice = DateTime.UtcNow.AddMinutes(-5); DateTime nextTimeToRunQuery; var result = sut.GetNextChunk(startSlice, out nextTimeToRunQuery); result.Should().HaveCount(1); nextTimeToRunQuery.Should().BeOnOrAfter(timeoutData.Time); }
public void WhenUsingValidTimeoutMillis_ResultsInValidTimeoutInstance() { var r = new Random(); for (ushort i = 0; i < ushort.MaxValue; ++i) { var millis = r.Next(int.MaxValue); var t = new Timeout(millis); Assert.AreEqual(millis, (int)t); Assert.AreEqual(millis, (uint)t); Assert.AreEqual(TimeSpan.FromMilliseconds(millis), (TimeSpan)t); var t2 = new Timeout(millis); Assert.AreEqual(t2, t); } }
public override void AddTimeout(Timeout timeout) { TimerWatcher t = new TimerWatcher (timeout.begin, timeout.span, evloop, HandleTimeout); t.UserData = timeout; t.Start (); }
public Room() { seats = new List<Seat>(); timeout = Lobby.Timeout.FifteenSeconds; }
private IEnumerable<Event> TestSharedTimeout(Environment env, Timeout timeout, int id, Dictionary<int, DateTime> log) { yield return timeout; log.Add(id, env.Now); }
void AddTimeout(TimeSpan time, Timeout timeout) { timeouts.Add((DateTime.UtcNow + time).Ticks, timeout); }
public async Task Defer(DateTimeOffset approximateDueTime, Dictionary<string, string> headers, byte[] body) { var newTimeout = new Timeout(headers, body, approximateDueTime.UtcDateTime); _log.Debug("Deferring message with ID {0} until {1} (doc ID {2})", headers.GetValue(Headers.MessageId), approximateDueTime, newTimeout.Id); _timeouts.Insert(newTimeout); }
public void ManualIntervention() { bool? done = null; Timeout timeout = new Timeout(10000); timeout.Then(()=> { done = true; }, () => { done = false; }); Assert.AreEqual(null,done); timeout.Stop(true); Assert.AreEqual(true, done); done = null; timeout = new Timeout(10000); timeout.Then(() => { done = true; }, () => { done = false; }); timeout.Stop(); Assert.AreEqual(false, done); }
void AddTimeout(TimeSpan time, Timeout timeout) { timeouts.Add ((DateTime.UtcNow + time).Ticks, timeout); }
public static async Task <bool> SpellQueueMethod() { if (!InSpellQueue) { Logger.WriteInfo("Starting Spell Queue"); Casting.LastSpell = null; } Debug.Instance.Queue = new AsyncObservableCollection <QueueSpell>(SpellQueue); InSpellQueue = true; if (CancelSpellQueue.Invoke()) { SpellQueue.Clear(); Timeout.Reset(); Logger.WriteInfo("Had To Cancel Spell Queue"); InSpellQueue = false; return(true); } var spell = SpellQueue.Peek(); if (NeedToDequeueSuccessfulCast) { if (Casting.LastSpell != null && Casting.LastSpell.Id == spell.Spell.Id) { SpellQueue.Dequeue(); NeedToDequeueSuccessfulCast = false; if (!SpellQueue.Any()) { Logger.WriteInfo("Spell Queue Complete"); Timeout.Reset(); InSpellQueue = false; } return(true); } } if (spell.SleepBefore) { await Coroutine.Sleep(spell.SleepMilliseconds); } if (spell.Wait != null) { if (await Coroutine.Wait(spell.Wait.WaitTime, spell.Wait.Check)) { Logger.Write($"Spell Queue Wait: {spell.Wait.Name}"); } else { SpellQueue.Dequeue(); return(true); } } if (spell.Checks.Any(x => !x.Check.Invoke())) { SpellQueue.Dequeue(); Logger.Write($"Removing {spell.Spell.LocalizedName} From The Spell Queue Because It Failed It's Checks."); foreach (var check in spell.Checks.Where(x => !x.Check.Invoke())) { if (!check.SilentMode) { Logger.Write($"Failed Check: {check.Name}"); } } return(true); } var target = spell.Target(); if (target == null) { return(SpellQueue.Any()); } if (!await spell.Spell.Cast(target)) { return(SpellQueue.Any()); } Logger.WriteInfo($@"Queue Cast: {spell.Spell.LocalizedName}"); NeedToDequeueSuccessfulCast = true; return(SpellQueue.Any()); }
/// <summary> /// This is used internally by the SensorNetworkServer to tell what kind of data the Sensor Network /// is sending. It may send data, in which case a transit ID will be present, or it may ask for /// an initialization. /// </summary> /// <param name="data">The data we are interpreting.</param> /// <param name="receivedDataSize">This will be used to tell if our data is complete.</param> private bool InterpretData(byte[] data, int receivedDataSize) { bool success = false; if (Encoding.ASCII.GetString(data, 0, receivedDataSize).Equals("Send Sensor Configuration")) { // Reaching here means that we've received a request for sensor initialization Status = SensorNetworkStatusEnum.Initializing; // If the init sending fails, set status to reflect that if (!InitializationClient.SendSensorInitialization()) { Status = SensorNetworkStatusEnum.InitializationSendingFailed; if (Timeout.Enabled) { Timeout.Stop(); } pushNotification.sendToAllAdmins("Sensor Network Error", $"Status: {Status}"); } else { logger.Info($"{Utilities.GetTimeStamp()}: Successfully sent sensor initialization to the Sensor Network."); success = true; } } else { Status = SensorNetworkStatusEnum.ReceivingData; // Bytes 1-3 of the data contain the overall size of the packet UInt32 expectedDataSize = (UInt32)(data[1] << 24 | data[2] << 16 | data[3] << 8 | data[4]); // Check that the data we received is the same size as what we expect if (expectedDataSize == receivedDataSize) { // Byte 0 contains the transmit ID int receivedTransitId = data[0]; // Verify that the first byte contains the "success" code (transit ID) if (receivedTransitId == SensorNetworkConstants.TransitIdSuccess) { // At this point, we may begin parsing the data // Sensor statuses and error codes BitArray sensorStatus = new BitArray(new byte[] { data[5] }); // sensor statuses UInt32 sensorErrors = (UInt32)(data[6] << 16 | data[7] << 8 | data[8]); // sensor self-tests | adxl error codes and azimuth encoder error code | temp sensor error codes // Acquire the sample sizes for each sensor UInt16 elAcclSize = (UInt16)(data[9] << 8 | data[10]); UInt16 azAcclSize = (UInt16)(data[11] << 8 | data[12]); UInt16 cbAcclSize = (UInt16)(data[13] << 8 | data[14]); UInt16 elTempSensorSize = (UInt16)(data[15] << 8 | data[16]); UInt16 azTempSensorSize = (UInt16)(data[17] << 8 | data[18]); UInt16 elEncoderSize = (UInt16)(data[19] << 8 | data[20]); UInt16 azEncoderSize = (UInt16)(data[21] << 8 | data[22]); // TODO: Outside of right here, we aren't doing anything with the sensor statuses. These should // be updated along with the sensor data on the diagnostics form. How this looks is up to you. (issue #353) SensorStatuses = ParseSensorStatuses(sensorStatus, sensorErrors); // This is the index we start reading sensor data int k = 23; // If no data comes through for a sensor (i.e. the size is 0), then it will not be updated, // otherwise the UI value would temporarily be set to 0, which would be inaccurate // Accelerometer 1 (elevation) if (elAcclSize > 0) { //Create array of acceleration objects CurrentElevationMotorAccl = GetAccelerationFromBytes(ref k, data, elAcclSize, SensorLocationEnum.EL_MOTOR); AccBlob.BuildAccelerationString(CurrentElevationMotorAccl); } // Accelerometer 2 (azimuth) if (azAcclSize > 0) { CurrentAzimuthMotorAccl = GetAccelerationFromBytes(ref k, data, azAcclSize, SensorLocationEnum.AZ_MOTOR); AccBlob.BuildAccelerationString(CurrentAzimuthMotorAccl); } // Accelerometer 3 (counterbalance) if (cbAcclSize > 0) { CurrentCounterbalanceAccl = GetAccelerationFromBytes(ref k, data, cbAcclSize, SensorLocationEnum.COUNTERBALANCE); AccBlob.BuildAccelerationString(CurrentCounterbalanceAccl); } // Elevation temperature if (elTempSensorSize > 0) { CurrentElevationMotorTemp = GetTemperatureFromBytes(ref k, data, elTempSensorSize, SensorLocationEnum.EL_MOTOR); Database.DatabaseOperations.AddSensorData(CurrentElevationMotorTemp); } // Azimuth temperature if (azTempSensorSize > 0) { CurrentAzimuthMotorTemp = GetTemperatureFromBytes(ref k, data, azTempSensorSize, SensorLocationEnum.AZ_MOTOR); Database.DatabaseOperations.AddSensorData(CurrentAzimuthMotorTemp); } // Elevation absolute encoder if (elEncoderSize > 0) { CurrentAbsoluteOrientation.Elevation = GetElevationAxisPositionFromBytes(ref k, data, AbsoluteOrientationOffset.Elevation, CurrentAbsoluteOrientation.Elevation); } // Azimuth absolute encoder if (azEncoderSize > 0) { CurrentAbsoluteOrientation.Azimuth = GetAzimuthAxisPositionFromBytes(ref k, data, AbsoluteOrientationOffset.Azimuth, CurrentAbsoluteOrientation.Azimuth); } success = true; } // This may be replaced with different errors at some point (that have different transit IDs), // though there are currently no plans for this. Right now, it is treated as an error overall: // We should NOT be receiving anything other than TransitIdSuccess. else { if (Status != SensorNetworkStatusEnum.TransitIdError) { logger.Error($"{Utilities.GetTimeStamp()}: Transit ID error: Expected " + $"ID {SensorNetworkConstants.TransitIdSuccess}, received ID {receivedTransitId})"); Status = SensorNetworkStatusEnum.TransitIdError; } } } } return(success); }
/// <summary> /// Returns a <see cref="String"/> that represents this <see cref="Manager"/>. /// </summary> /// <returns></returns> public override string ToString() { return(string.Format(CultureInfo.InvariantCulture, "SNMP manager: timeout: {0}; version: {1}", Timeout.ToString(CultureInfo.InvariantCulture), DefaultVersion)); }
private void InitializeInstanceFields() { RuleChain = RuleChain.outerRule(Timeout.seconds(TEST_TIMEOUT_SECONDS)).around(_dir); }
protected override void Execute(NativeActivityContext context) { var selector = Selector.Get(context); selector = OpenRPA.Interfaces.Selector.Selector.ReplaceVariables(selector, context.DataContext); var sel = new NMSelector(selector); var timeout = Timeout.Get(context); var from = From.Get(context); var maxresults = MaxResults.Get(context); var minresults = MinResults.Get(context); if (maxresults < 1) { maxresults = 1; } NMElement[] elements = { }; var sw = new Stopwatch(); sw.Start(); string browser = sel.browser; if (WaitForReady.Get(context)) { if (from != null) { browser = from.browser; } DoWaitForReady(browser); } var allelements = context.GetValue(_allelements); if (allelements == null) { allelements = new NMElement[] { } } ; var s = new NMSelectorItem(sel[0]); if (!string.IsNullOrEmpty(s.url)) { var tab = NMHook.tabs.Where(x => x.browser == browser && x.url.ToLower().StartsWith(s.url.ToLower())).FirstOrDefault(); if (tab != null) { if (!tab.highlighted || !tab.selected) { var _tab = NMHook.selecttab(browser, tab.id); } } } do { elements = NMSelector.GetElementsWithuiSelector(sel, from, maxresults); Log.Selector("BEGIN:: I have " + elements.Count() + " elements, and " + allelements.Count() + " in all elements"); // allelements = allelements.Concat(elements).ToArray(); if (allelements.Length > 0) { var newelements = new List <NMElement>(); for (var i = elements.Length - 1; i >= 0; i--) { var element = elements[i]; if (!allelements.Contains(element)) { newelements.Insert(0, element); } } elements = newelements.ToArray(); //if(elements.Count() > 20) //{ // for(var i=0; i < allelements.Length && i < elements.Length; i++) // { // if (!eq.Equals(allelements[i], elements[i]) || allelements[i].GetHashCode() != elements[i].GetHashCode()) // { // Log.Output(allelements[i].GetHashCode() + " / " + elements[i].GetHashCode()); // } // } //} } } while (elements.Count() == 0 && sw.Elapsed < timeout); if (elements.Count() > maxresults) { elements = elements.Take(maxresults).ToArray(); } if ((elements.Length + allelements.Length) < minresults) { Log.Selector(string.Format("Windows.GetElement::Failed locating " + minresults + " item(s) {0:mm\\:ss\\.fff}", sw.Elapsed)); throw new ElementNotFoundException("Failed locating " + minresults + " item(s)"); } IEnumerator <NMElement> _enum = elements.ToList().GetEnumerator(); bool more = _enum.MoveNext(); //if (lastelements.Length == elements.Length && lastelements.Length > 0) //{ // var eq = new Activities.NMEqualityComparer(); // more = !System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(lastelements, elements); //} if (more) { allelements = allelements.Concat(elements).ToArray(); var eq = new Activities.NMEqualityComparer(); allelements = allelements.Distinct(eq).ToArray(); //var allelementslength = allelements.Length; //Array.Resize(ref allelements, allelements.Length + elements.Length); //Array.Copy(elements, 0, allelements, allelementslength, elements.Length); } context.SetValue(_allelements, allelements); context.SetValue(Elements, allelements); Log.Selector("END:: I have " + elements.Count() + " elements, and " + allelements.Count() + " in all elements"); if (more) { context.SetValue(_elements, _enum); context.ScheduleAction(Body, _enum.Current, OnBodyComplete); } }
// public ActivityAction<UIElement> LoopAction { get; set; } protected override void Execute(NativeActivityContext context) { var sw = new Stopwatch(); sw.Start(); Log.Selector(string.Format("Windows.GetElement::begin {0:mm\\:ss\\.fff}", sw.Elapsed)); UIElement[] elements = null; var selector = Selector.Get(context); selector = OpenRPA.Interfaces.Selector.Selector.ReplaceVariables(selector, context.DataContext); var sel = new WindowsSelector(selector); var timeout = Timeout.Get(context); var maxresults = MaxResults.Get(context); var minresults = MinResults.Get(context); if (maxresults < 1) { maxresults = 1; } var interactive = Interactive.Get(context); var from = From.Get(context); // double _timeout = 250; double _timeout = 5000; if (PluginConfig.search_descendants) { _timeout = 5000; } #if DEBUG _timeout = TimeSpan.FromDays(1).TotalMilliseconds; #endif int failcounter = 0; do { if (PluginConfig.get_elements_in_different_thread) { elements = OpenRPA.AutomationHelper.RunSTAThread <UIElement[]>(() => { try { Log.Selector(string.Format("Windows.GetElement::GetElementsWithuiSelector in non UI thread {0:mm\\:ss\\.fff}", sw.Elapsed)); return(WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults)); } catch (System.Threading.ThreadAbortException) { } catch (Exception ex) { Log.Error(ex, ""); } return(new UIElement[] { }); }, TimeSpan.FromMilliseconds(_timeout)).Result; } else { Log.Selector(string.Format("Windows.GetElement::GetElementsWithuiSelector using UI thread {0:mm\\:ss\\.fff}", sw.Elapsed)); elements = WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults); } //elements = WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults); if (elements == null) { elements = new UIElement[] { }; } if (elements.Length == 0) { Log.Selector(string.Format("Windows.GetElement::Found no elements {0:mm\\:ss\\.fff}", sw.Elapsed)); failcounter++; } if (failcounter > 2) { WindowsSelectorItem.ClearCache(); } } while (elements != null && elements.Length == 0 && sw.Elapsed < timeout); if (PluginConfig.get_elements_in_different_thread && elements.Length > 0) { // Get them again, we need the COM objects to be loaded in the UI thread elements = WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults); } context.SetValue(Elements, elements); var lastelements = context.GetValue(_lastelements); if (lastelements == null) { lastelements = new UIElement[] { } } ; context.SetValue(_lastelements, elements); if ((elements.Length + lastelements.Length) < minresults) { Log.Selector(string.Format("Windows.GetElement::Failed locating " + minresults + " item(s) {0:mm\\:ss\\.fff}", sw.Elapsed)); throw new ElementNotFoundException("Failed locating " + minresults + " item(s)"); } IEnumerator <UIElement> _enum = elements.ToList().GetEnumerator(); bool more = _enum.MoveNext(); if (lastelements.Length == elements.Length && lastelements.Length > 0) { more = !System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(lastelements, elements); } if (more) { if (interactive) { var testelement = _enum.Current; Wait.UntilResponsive(testelement.RawElement, TimeSpan.FromMilliseconds(_timeout)); } context.SetValue(_elements, _enum); context.SetValue(_sw, sw); Log.Selector(string.Format("Windows.GetElement::end:: call ScheduleAction: {0:mm\\:ss\\.fff}", sw.Elapsed)); context.ScheduleAction <UIElement>(Body, _enum.Current, OnBodyComplete); } else { Log.Selector(string.Format("Windows.GetElement:end {0:mm\\:ss\\.fff}", sw.Elapsed)); } }
/// <summary> /// Removes the timeout if it hasn't been previously removed. /// </summary> /// <param name="timeoutId">The timeout id to remove.</param> /// <param name="timeoutData">The timeout data of the removed timeout.</param> /// <returns> /// <c>true</c> it the timeout was successfully removed. /// </returns> public bool TryRemove(string timeoutId, out Timeout.Core.TimeoutData timeoutData) { timeoutData = null; var collection = this.mongoDatabase.GetCollection<TimeoutData>(TimeoutDataName); var findAndRemoveArgs = new FindAndRemoveArgs { Query = Query<TimeoutData>.EQ(t => t.Id, timeoutId) }; var result = collection.FindAndRemove(findAndRemoveArgs); if (!result.Ok) { throw new InvalidOperationException( string.Format("Unable to remove timeout for id {0}: {1}", timeoutId, result.ErrorMessage)); } var data = result.GetModifiedDocumentAs<TimeoutData>(); if (data != null) { timeoutData = new Timeout.Core.TimeoutData() { Id = data.Id, Destination = data.Destination, SagaId = data.SagaId, State = data.State, Time = data.Time, Headers = data.Headers, OwningTimeoutManager = data.OwningTimeoutManager }; } return data != null; }
protected override void Execute(NativeActivityContext context) { var selector = Selector.Get(context); selector = OpenRPA.Interfaces.Selector.Selector.ReplaceVariables(selector, context.DataContext); var sel = new IESelector(selector); var timeout = Timeout.Get(context); var from = From.Get(context); var maxresults = MaxResults.Get(context); var minresults = MinResults.Get(context); if (maxresults < 1) { maxresults = 1; } IEElement[] elements = { }; if (WaitForReady.Get(context)) { var browser = Browser.GetBrowser(false); MSHTML.HTMLDocument doc = browser.Document; var sw2 = new Stopwatch(); sw2.Start(); string readyState = ""; while (sw2.Elapsed < timeout && readyState != "complete" && readyState != "interactive") { try { readyState = doc.readyState; } catch (Exception) { browser = Browser.GetBrowser(true); } // Log.Debug("pending complete, readyState: " + doc.readyState); System.Threading.Thread.Sleep(100); } } var sw = new Stopwatch(); sw.Start(); do { elements = IESelector.GetElementsWithuiSelector(sel, from, maxresults); } while (elements.Count() == 0 && sw.Elapsed < timeout); if (elements.Count() > maxresults) { elements = elements.Take(maxresults).ToArray(); } if (elements.Length < minresults) { Log.Selector(string.Format("Windows.GetElement::Failed locating " + minresults + " item(s) {0:mm\\:ss\\.fff}", sw.Elapsed)); throw new ElementNotFoundException("Failed locating " + minresults + " item(s)"); } context.SetValue(Elements, elements); IEnumerator <IEElement> _enum = elements.ToList().GetEnumerator(); context.SetValue(_elements, _enum); bool more = _enum.MoveNext(); if (more) { context.ScheduleAction(Body, _enum.Current, OnBodyComplete); } }
/// <summary> /// Executes the operation, by sending a request to the server. /// </summary> /// <returns>A <see cref="Task"/> that will return an instance of <see cref="Entity"/> with the operation result.</returns> public async Task <Entity> Execute() { Dictionary <string, string> headers; if (AdditionalHeaders != null) { headers = new Dictionary <string, string>(AdditionalHeaders); } else { headers = new Dictionary <string, string>(); } if (Schemas != null && Schemas.Count > 0) { headers["X-NXDocumentProperties"] = string.Join(",", Schemas); } headers["Nuxeo-Transaction-Timeout"] = Timeout.ToString(); if (Repository != null && Repository != string.Empty) { headers["X-NXRepository"] = Repository; } JObject data = new JObject(); if (Parameters != null) { JObject jsonParams = new JObject(); foreach (KeyValuePair <string, JToken> param in Parameters) { jsonParams.Add(param.Key, param.Value); } data.Add("params", jsonParams); } if (Context != null) { JObject jsonCotext = new JObject(); foreach (KeyValuePair <string, JToken> param in Context) { jsonCotext.Add(param.Key, param.Value); } data.Add("context", jsonCotext); } if (Input is Blob) { return(await client.RequestMultipart(Endpoint, data, (Blob)Input, HttpMethod.Post, headers)); } if (Input is BlobList) { return(await client.RequestMultipart(Endpoint, data, (BlobList)Input, HttpMethod.Post, headers)); } else { ICollection <Document> docs = Input is Documents ? ((Documents)Input).Entries : Input as ICollection <Document>; if (docs != null) { data.Add("input", $"docs:{string.Join(",", docs.Select(d => d.Uid).ToArray())}"); } else { Document doc = Input as Document; if (!string.IsNullOrWhiteSpace(doc?.Uid)) { data.Add("input", $"doc:{doc.Uid}"); } else { data.Add("input", (string)Input); } } return(await client.RequestJson(Endpoint, null, data, HttpMethod.Post, headers)); } }
public void TimeoutObjectWithParameter() { bool done = false; Timeout timeout = new Timeout(500,"timedout",true); timeout.Then((parm) => { done = true; Assert.AreEqual("timedout", parm); }); Assert.IsFalse(done); System.Threading.Thread.Sleep(250); Assert.IsFalse(done); System.Threading.Thread.Sleep(350); Assert.IsTrue(done); }
/// <summary>Reads a sensor capture.</summary> /// <param name="capture"> /// If successful this contains object with capture data read from device (don't forget to free this object by calling <see cref="Capture.Dispose"/>), /// otherwise - <see langword="null"/>. /// </param> /// <param name="timeout"> /// Specifies the time the function should block waiting for the capture. /// Default value is <see cref="Timeout.NoWait"/>, which means that the function will return without blocking. /// Passing <see cref="Timeout.Infinite"/> will block indefinitely until data is available, the /// device is disconnected, or another error occurs. /// </param> /// <returns> /// <see langword="true"/> - if a capture is returned, /// <see langword="false"/> - if a capture is not available before the timeout elapses. /// </returns> /// <remarks> /// This function needs to be called while the device is in a running state; /// after <see cref="StartCameras(DeviceConfiguration)"/> is called and before <see cref="StopCameras"/> is called. /// </remarks> /// <exception cref="ObjectDisposedException">This method cannot be called for disposed object.</exception> /// <exception cref="DeviceConnectionLostException">Connection with Azure Kinect device has been lost.</exception> /// <exception cref="InvalidOperationException">Camera streaming is not running or has been stopped during this call.</exception> public bool TryGetCapture([NotNullWhen(returnValue: true)] out Capture?capture, Timeout timeout = default) { var res = NativeApi.DeviceGetCapture(handle.ValueNotDisposed, out var captureHandle, timeout); if (res == NativeCallResults.WaitResult.Succeeded) { capture = Capture.Create(captureHandle); return(capture != null); } if (res == NativeCallResults.WaitResult.Timeout) { capture = null; return(false); } ThrowException("Cameras streaming is not running or has been stopped."); capture = null; // Actually, this code is unreachable return(false); }
/// <summary> /// Constructor to create a promise that resolves when one or more other promises have all /// resolved or a timeout elapses. /// </summary> /// /// <param name="timeoutMilliseconds"> /// The timeout in milliseconds. /// </param> /// <param name="promises"> /// A variable-length parameters list containing promises that must all resolve. /// </param> public WhenAll(int timeoutMilliseconds, params IPromise[] promises) { Configure(promises); timeout = new Timeout(timeoutMilliseconds); timeout.Then((Action)null,(Action)TimedOut); }
public override IEnumerable <Status> Run() { Creature.IsCloaked = false; if (CurrentAttack == null) { yield return(Status.Fail); yield break; } Timeout.Reset(); FailTimer.Reset(); if (Target == null && TargetName != null) { Target = Agent.Blackboard.GetData <Body>(TargetName); if (Target == null) { yield return(Status.Fail); yield break; } } if (Agent.Faction.Race.IsIntelligent) { var targetInventory = Target.GetRoot().GetComponent <Inventory>(); if (targetInventory != null) { targetInventory.SetLastAttacker(Agent); } } CharacterMode defaultCharachterMode = Creature.AI.Movement.CanFly ? CharacterMode.Flying : CharacterMode.Walking; bool avoided = false; while (true) { Timeout.Update(DwarfTime.LastTime); FailTimer.Update(DwarfTime.LastTime); if (FailTimer.HasTriggered) { Creature.Physics.Orientation = Physics.OrientMode.RotateY; Creature.OverrideCharacterMode = false; Creature.CurrentCharacterMode = defaultCharachterMode; yield return(Status.Fail); yield break; } if (Timeout.HasTriggered) { if (Training) { Agent.AddXP(1); Creature.Physics.Orientation = Physics.OrientMode.RotateY; Creature.OverrideCharacterMode = false; Creature.CurrentCharacterMode = defaultCharachterMode; yield return(Status.Success); yield break; } else { Creature.Physics.Orientation = Physics.OrientMode.RotateY; Creature.OverrideCharacterMode = false; Creature.CurrentCharacterMode = defaultCharachterMode; yield return(Status.Fail); yield break; } } if (Target == null || Target.IsDead) { Creature.CurrentCharacterMode = defaultCharachterMode; Creature.Physics.Orientation = Physics.OrientMode.RotateY; yield return(Status.Success); } // Find the location of the melee target Vector3 targetPos = new Vector3(Target.GlobalTransform.Translation.X, Target.GetBoundingBox().Min.Y, Target.GlobalTransform.Translation.Z); Vector2 diff = new Vector2(targetPos.X, targetPos.Z) - new Vector2(Creature.AI.Position.X, Creature.AI.Position.Z); Creature.Physics.Face(targetPos); bool intersectsbounds = Creature.Physics.BoundingBox.Intersects(Target.BoundingBox); float dist = diff.Length(); // If we are really far from the target, something must have gone wrong. if (DefensiveStructure == null && !intersectsbounds && dist > CurrentAttack.Range * 4) { Creature.Physics.Orientation = Physics.OrientMode.RotateY; Creature.OverrideCharacterMode = false; Creature.CurrentCharacterMode = defaultCharachterMode; yield return(Status.Fail); yield break; } if (DefensiveStructure != null) { if (Creature.Hp < LastHp) { float damage = LastHp - Creature.Hp; Creature.Heal(Math.Min(5.0f, damage)); var health = DefensiveStructure.GetRoot().GetComponent <Health>(); if (health != null) { health.Damage(damage); Drawer2D.DrawLoadBar(health.World.Camera, DefensiveStructure.Position, Color.White, Color.Black, 32, 1, health.Hp / health.MaxHealth, 0.1f); } LastHp = Creature.Hp; } if (dist > CurrentAttack.Range) { float sqrDist = dist * dist; foreach (var threat in Creature.AI.Faction.Threats) { float threatDist = (threat.AI.Position - Creature.AI.Position).LengthSquared(); if (threatDist < sqrDist) { sqrDist = threatDist; Target = threat.Physics; break; } } dist = (float)Math.Sqrt(sqrDist); } if (dist > CurrentAttack.Range * 4) { yield return(Status.Fail); yield break; } if (DefensiveStructure.IsDead) { DefensiveStructure = null; } } LastHp = Creature.Hp; // If we're out of attack range, run toward the target. if (DefensiveStructure == null && !Creature.AI.Movement.IsSessile && !intersectsbounds && diff.Length() > CurrentAttack.Range) { Creature.CurrentCharacterMode = defaultCharachterMode; /* * Vector3 output = Creature.Controller.GetOutput(DwarfTime.Dt, targetPos, Creature.Physics.GlobalTransform.Translation) * 0.9f; * output.Y = 0.0f; * if (Creature.AI.Movement.CanFly) * { * Creature.Physics.ApplyForce(-Creature.Physics.Gravity, DwarfTime.Dt); * } * if (Creature.AI.Movement.IsSessile) * { * output *= 0.0f; * } * Creature.Physics.ApplyForce(output, DwarfTime.Dt); * Creature.Physics.Orientation = Physics.OrientMode.RotateY; */ GreedyPathAct greedyPath = new GreedyPathAct(Creature.AI, Target, CurrentAttack.Range * 0.75f) { PathLength = 5 }; greedyPath.Initialize(); foreach (Act.Status stat in greedyPath.Run()) { if (stat == Act.Status.Running) { yield return(Status.Running); } else { break; } } } // If we have a ranged weapon, try avoiding the target for a few seconds to get within range. else if (DefensiveStructure == null && !Creature.AI.Movement.IsSessile && !intersectsbounds && !avoided && (CurrentAttack.Mode == Attack.AttackMode.Ranged && dist < CurrentAttack.Range * 0.15f)) { FailTimer.Reset(); foreach (Act.Status stat in AvoidTarget(CurrentAttack.Range, 3.0f)) { yield return(Status.Running); } avoided = true; } // Else, stop and attack else if ((DefensiveStructure == null && dist < CurrentAttack.Range) || (DefensiveStructure != null && dist < CurrentAttack.Range * 2.0)) { if (CurrentAttack.Mode == Attack.AttackMode.Ranged && VoxelHelpers.DoesRayHitSolidVoxel(Creature.World.ChunkManager.ChunkData, Creature.AI.Position, Target.Position)) { yield return(Status.Fail); yield break; } FailTimer.Reset(); avoided = false; Creature.Physics.Orientation = Physics.OrientMode.Fixed; Creature.Physics.Velocity = new Vector3(Creature.Physics.Velocity.X * 0.9f, Creature.Physics.Velocity.Y, Creature.Physics.Velocity.Z * 0.9f); CurrentAttack.RechargeTimer.Reset(CurrentAttack.RechargeRate); Creature.Sprite.ResetAnimations(Creature.AttackMode); Creature.Sprite.PlayAnimations(Creature.AttackMode); Creature.CurrentCharacterMode = Creature.AttackMode; Creature.OverrideCharacterMode = true; Timer timeout = new Timer(10.0f, true); while (!CurrentAttack.Perform(Creature, Target, DwarfTime.LastTime, Creature.Stats.BuffedStr + Creature.Stats.BuffedSiz, Creature.AI.Position, Creature.Faction.Name)) { timeout.Update(DwarfTime.LastTime); if (timeout.HasTriggered) { break; } Creature.Physics.Velocity = new Vector3(Creature.Physics.Velocity.X * 0.9f, Creature.Physics.Velocity.Y, Creature.Physics.Velocity.Z * 0.9f); if (Creature.AI.Movement.CanFly) { Creature.Physics.ApplyForce(-Creature.Physics.Gravity * 0.1f, DwarfTime.Dt); } yield return(Status.Running); } timeout.Reset(); while (!Agent.Creature.Sprite.AnimPlayer.IsDone()) { timeout.Update(DwarfTime.LastTime); if (timeout.HasTriggered) { break; } if (Creature.AI.Movement.CanFly) { Creature.Physics.ApplyForce(-Creature.Physics.Gravity * 0.1f, DwarfTime.Dt); } yield return(Status.Running); } var targetCreature = Target.GetRoot().GetComponent <CreatureAI>(); if (targetCreature != null && !Creature.AI.FightOrFlight(targetCreature)) { yield return(Act.Status.Fail); yield break; } Creature.CurrentCharacterMode = CharacterMode.Attacking; Vector3 dogfightTarget = Vector3.Zero; while (!CurrentAttack.RechargeTimer.HasTriggered && !Target.IsDead) { CurrentAttack.RechargeTimer.Update(DwarfTime.LastTime); if (CurrentAttack.Mode == Attack.AttackMode.Dogfight) { dogfightTarget += MathFunctions.RandVector3Cube() * 0.1f; Vector3 output = Creature.Controller.GetOutput(DwarfTime.Dt, dogfightTarget + Target.Position, Creature.Physics.GlobalTransform.Translation) * 0.9f; Creature.Physics.ApplyForce(output - Creature.Physics.Gravity, DwarfTime.Dt); } else { Creature.Physics.Velocity = Vector3.Zero; if (Creature.AI.Movement.CanFly) { Creature.Physics.ApplyForce(-Creature.Physics.Gravity, DwarfTime.Dt); } } yield return(Status.Running); } Creature.CurrentCharacterMode = defaultCharachterMode; Creature.Physics.Orientation = Physics.OrientMode.RotateY; if (Target.IsDead) { Target = null; Agent.AddXP(10); Creature.Physics.Face(Creature.Physics.Velocity + Creature.Physics.GlobalTransform.Translation); Creature.Stats.NumThingsKilled++; Creature.AddThought(Thought.ThoughtType.KilledThing); Creature.Physics.Orientation = Physics.OrientMode.RotateY; Creature.OverrideCharacterMode = false; Creature.CurrentCharacterMode = defaultCharachterMode; yield return(Status.Success); break; } } yield return(Status.Running); } }
protected override void StartLoop(NativeActivityContext context) { var SelectorString = Selector.Get(context); SelectorString = OpenRPA.Interfaces.Selector.Selector.ReplaceVariables(SelectorString, context.DataContext); var sel = new SAPSelector(SelectorString); var timeout = Timeout.Get(context); if (Timeout == null || Timeout.Expression == null) { timeout = TimeSpan.FromSeconds(3); } var maxresults = MaxResults.Get(context); var minresults = MinResults.Get(context); var flatternguitree = FlatternGuiTree.Get(context); //var from = From.Get(context); SAPElement from = null; if (maxresults < 1) { maxresults = 1; } if (timeout.Minutes > 5 || timeout.Hours > 1) { Activity _Activity = null; try { var strProperty = context.GetType().GetProperty("Activity", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var strGetter = strProperty.GetGetMethod(nonPublic: true); _Activity = (Activity)strGetter.Invoke(context, null); } catch (Exception) { } if (_Activity != null) { Log.Warning("Timeout for Activity " + _Activity.Id + " is above 5 minutes, was this the intention ? calculated value " + timeout.ToString()); } else { Log.Warning("Timeout for on of your SAP.GetElements is above 5 minutes, was this the intention ? calculated value " + timeout.ToString()); } } SAPElement[] elements = { }; var sw = new Stopwatch(); sw.Start(); do { var selector = new SAPSelector(SelectorString); elements = SAPSelector.GetElementsWithuiSelector(selector, from, 0, maxresults, flatternguitree); } while (elements.Count() == 0 && sw.Elapsed < timeout); Log.Debug(string.Format("OpenRPA.SAP::GetElement::found {1} elements in {0:mm\\:ss\\.fff}", sw.Elapsed, elements.Count())); if (elements.Count() > maxresults) { elements = elements.Take(maxresults).ToArray(); } if (elements.Count() < minresults) { Log.Selector(string.Format("Windows.GetElement::Failed locating " + minresults + " item(s) {0:mm\\:ss\\.fff}", sw.Elapsed)); throw new ElementNotFoundException("Failed locating " + minresults + " item(s)"); } context.SetValue(Elements, elements); IEnumerator <SAPElement> _enum = elements.ToList().GetEnumerator(); context.SetValue(_elements, _enum); bool more = _enum.MoveNext(); if (more) { IncIndex(context); SetTotal(context, elements.Length); context.ScheduleAction(Body, _enum.Current, OnBodyComplete); } }
// Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if (Namespace.Expression != null) { targetCommand.AddParameter("Namespace", Namespace.Get(context)); } if (Credential.Expression != null) { targetCommand.AddParameter("Credential", Credential.Get(context)); } if (ComputerName.Expression != null) { targetCommand.AddParameter("ComputerName", ComputerName.Get(context)); } if (Class.Expression != null) { targetCommand.AddParameter("Class", Class.Get(context)); } if (Query.Expression != null) { targetCommand.AddParameter("Query", Query.Get(context)); } if (Timeout.Expression != null) { targetCommand.AddParameter("Timeout", Timeout.Get(context)); } if (SourceIdentifier.Expression != null) { targetCommand.AddParameter("SourceIdentifier", SourceIdentifier.Get(context)); } if (Action.Expression != null) { targetCommand.AddParameter("Action", Action.Get(context)); } if (MessageData.Expression != null) { targetCommand.AddParameter("MessageData", MessageData.Get(context)); } if (SupportEvent.Expression != null) { targetCommand.AddParameter("SupportEvent", SupportEvent.Get(context)); } if (Forward.Expression != null) { targetCommand.AddParameter("Forward", Forward.Get(context)); } if (MaxTriggerCount.Expression != null) { targetCommand.AddParameter("MaxTriggerCount", MaxTriggerCount.Get(context)); } return(new ActivityImplementationContext() { PowerShellInstance = invoker }); }
protected override void Execute(NativeActivityContext context) { UIElement[] elements = null; var selector = Selector.Get(context); var sel = new WindowsSelector(selector); var timeout = Timeout.Get(context); var maxresults = MaxResults.Get(context); var minresults = MinResults.Get(context); if (maxresults < 1) { maxresults = 1; } var sw = new Stopwatch(); var from = From.Get(context); sw.Start(); double _timeout = 250; #if DEBUG _timeout = _timeout * 8; #endif do { elements = OpenRPA.AutomationHelper.RunSTAThread <UIElement[]>(() => { try { return(WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults)); } catch (System.Threading.ThreadAbortException) { } catch (Exception ex) { Log.Error(ex, ""); } return(new UIElement[] { }); }, TimeSpan.FromMilliseconds(_timeout)).Result; if (elements == null) { elements = new UIElement[] { }; } } while (elements != null && elements.Length == 0 && sw.Elapsed < timeout); if (elements.Length > 0) { // Get them again, we need the COM objects to be loaded in the UI thread elements = WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults); } context.SetValue(Elements, elements); if (elements.Count() < minresults) { throw new ElementNotFoundException("Failed locating " + minresults + " item(s)"); } IEnumerator <UIElement> _enum = elements.ToList().GetEnumerator(); context.SetValue(_elements, _enum); bool more = _enum.MoveNext(); if (more) { context.ScheduleAction <UIElement>(Body, _enum.Current, OnBodyComplete); } }
/// <summary> /// Generate the necessary parameters /// </summary> public List <KeyValuePair <string, string> > GetParams() { var p = new List <KeyValuePair <string, string> >(); if (To != null) { p.Add(new KeyValuePair <string, string>("To", To.ToString())); } if (From != null) { p.Add(new KeyValuePair <string, string>("From", From.ToString())); } if (Url != null) { p.Add(new KeyValuePair <string, string>("Url", Serializers.Url(Url))); } if (ApplicationSid != null) { p.Add(new KeyValuePair <string, string>("ApplicationSid", ApplicationSid.ToString())); } if (Method != null) { p.Add(new KeyValuePair <string, string>("Method", Method.ToString())); } if (FallbackUrl != null) { p.Add(new KeyValuePair <string, string>("FallbackUrl", Serializers.Url(FallbackUrl))); } if (FallbackMethod != null) { p.Add(new KeyValuePair <string, string>("FallbackMethod", FallbackMethod.ToString())); } if (StatusCallback != null) { p.Add(new KeyValuePair <string, string>("StatusCallback", Serializers.Url(StatusCallback))); } if (StatusCallbackEvent != null) { p.AddRange(StatusCallbackEvent.Select(prop => new KeyValuePair <string, string>("StatusCallbackEvent", prop))); } if (StatusCallbackMethod != null) { p.Add(new KeyValuePair <string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString())); } if (SendDigits != null) { p.Add(new KeyValuePair <string, string>("SendDigits", SendDigits)); } if (Timeout != null) { p.Add(new KeyValuePair <string, string>("Timeout", Timeout.ToString())); } if (Record != null) { p.Add(new KeyValuePair <string, string>("Record", Record.Value.ToString().ToLower())); } if (RecordingChannels != null) { p.Add(new KeyValuePair <string, string>("RecordingChannels", RecordingChannels)); } if (RecordingStatusCallback != null) { p.Add(new KeyValuePair <string, string>("RecordingStatusCallback", RecordingStatusCallback)); } if (RecordingStatusCallbackMethod != null) { p.Add(new KeyValuePair <string, string>("RecordingStatusCallbackMethod", RecordingStatusCallbackMethod.ToString())); } if (SipAuthUsername != null) { p.Add(new KeyValuePair <string, string>("SipAuthUsername", SipAuthUsername)); } if (SipAuthPassword != null) { p.Add(new KeyValuePair <string, string>("SipAuthPassword", SipAuthPassword)); } if (MachineDetection != null) { p.Add(new KeyValuePair <string, string>("MachineDetection", MachineDetection)); } if (MachineDetectionTimeout != null) { p.Add(new KeyValuePair <string, string>("MachineDetectionTimeout", MachineDetectionTimeout.ToString())); } if (RecordingStatusCallbackEvent != null) { p.AddRange(RecordingStatusCallbackEvent.Select(prop => new KeyValuePair <string, string>("RecordingStatusCallbackEvent", prop))); } if (Trim != null) { p.Add(new KeyValuePair <string, string>("Trim", Trim)); } if (CallerId != null) { p.Add(new KeyValuePair <string, string>("CallerId", CallerId)); } if (MachineDetectionSpeechThreshold != null) { p.Add(new KeyValuePair <string, string>("MachineDetectionSpeechThreshold", MachineDetectionSpeechThreshold.ToString())); } if (MachineDetectionSpeechEndThreshold != null) { p.Add(new KeyValuePair <string, string>("MachineDetectionSpeechEndThreshold", MachineDetectionSpeechEndThreshold.ToString())); } if (MachineDetectionSilenceTimeout != null) { p.Add(new KeyValuePair <string, string>("MachineDetectionSilenceTimeout", MachineDetectionSilenceTimeout.ToString())); } return(p); }
public void WaitUntil(IStatePredicate predicate, Timeout timeout) { lock (sync) { for (; ; ) { if (firstException != null) throw firstException; if (predicate.IsActive()) break; if (timeout.HasTimedOut) { throw new TimeoutException(string.Format("timed out waiting for {0}", StringDescription.Describe(predicate))); } Monitor.Wait(sync, timeout.TimeRemaining); } } }
public void Dispose() { _builder.Dispose(); Timeout.Dispose(); Result?.Dispose(); }
public abstract void AddTimeout(Timeout timeout);
/// <summary> /// Creates a new instance of the timeouts chunk. /// </summary> /// <param name="dueTimeouts">timeouts that are due.</param> /// <param name="nextTimeToQuery">the next time to query for due timeouts again.</param> public TimeoutsChunk(Timeout[] dueTimeouts, DateTime nextTimeToQuery) { DueTimeouts = dueTimeouts; NextTimeToQuery = nextTimeToQuery; }
/// <summary> /// Adds a new timeout. /// </summary> /// <param name="timeout">Timeout data.</param> /// <exception cref="InvalidOperationException"> /// Throws exception if timeout is not saved. /// </exception> public void Add(Timeout.Core.TimeoutData timeout) { var data = new TimeoutData() { Id = Guid.NewGuid().ToString(), Destination = timeout.Destination, SagaId = timeout.SagaId, State = timeout.State, Time = timeout.Time, Headers = timeout.Headers, OwningTimeoutManager = timeout.OwningTimeoutManager }; var collection = this.mongoDatabase.GetCollection<TimeoutData>(TimeoutDataName); var result = collection.Save(data); if (result.HasLastErrorMessage) { throw new InvalidOperationException(string.Format("Unable to save timeout [{0}]", timeout)); } timeout.Id = data.Id; }
/** * Enable automatic rotation mode **/ public void AutomaticRotation(Timeout screenTimeout) { mRotationMode = ECameraState.AUTO; mScreenTimeout = screenTimeout; }
private void Start() { Timeout.StartTimers(); }
public string GetOrganizationCrmConnectionString() { var currentServerName = string.Empty; var authType = "AD"; if (UseOsdp || UseOnline) { currentServerName = string.Format("{0}.{1}", OrganizationUrlName, ServerName); } else if (UseIfd) { var serverNameParts = ServerName.Split('.'); serverNameParts[0] = OrganizationUrlName; currentServerName = string.Format("{0}:{1}", string.Join(".", serverNameParts), ServerPort == 0 ? (UseSsl ? 443 : 80) : ServerPort); } else { currentServerName = string.Format("{0}:{1}/{2}", ServerName, ServerPort == 0 ? (UseSsl ? 443 : 80) : ServerPort, Organization); } var connectionString = string.Format("Url={0}://{1};", UseSsl ? "https" : "http", currentServerName); //var connectionString = string.Format("Url={0};", OrganizationServiceUrl.Replace("/XRMServices/2011/Organization.svc", "")); if (IsCustomAuth) { if (!UseIfd) { if (!string.IsNullOrEmpty(UserDomain)) { connectionString += string.Format("Domain={0};", UserDomain); } } string username = UserName; if (UseIfd) { if (!string.IsNullOrEmpty(UserDomain)) { username = string.Format("{0}\\{1}", UserDomain, UserName); } } connectionString += string.Format("Username={0};Password={1};", username, UserPassword); } if (UseOnline) { ClientCredentials deviceCredentials; do { deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ?? DeviceIdManager.RegisterDevice(); } while (deviceCredentials.UserName.Password.Contains(";") || deviceCredentials.UserName.Password.Contains("=") || deviceCredentials.UserName.Password.Contains(" ") || deviceCredentials.UserName.UserName.Contains(";") || deviceCredentials.UserName.UserName.Contains("=") || deviceCredentials.UserName.UserName.Contains(" ")); connectionString += string.Format("DeviceID={0};DevicePassword={1};", deviceCredentials.UserName.UserName, deviceCredentials.UserName.Password); authType = "Office365"; } if (UseIfd && !string.IsNullOrEmpty(HomeRealmUrl)) { connectionString += string.Format("HomeRealmUri={0};", HomeRealmUrl); } if (UseIfd) { authType = "IFD"; } connectionString += string.Format("AuthType={0};", authType); //append timeout in seconds to connectionstring connectionString += string.Format("Timeout={0};", Timeout.ToString(@"hh\:mm\:ss")); return(connectionString); }
void DeleteTimeout(Timeout timeout, SqlConnection connection) { using (var command = connection.CreateCommand()) { command.CommandText = string.Format( @"delete from [{0}] where time_to_return = @time_to_return and reply_to = @reply_to and correlation_id = @correlation_id", timeoutsTableName); command.Parameters.AddWithValue("time_to_return", timeout.TimeToReturn); command.Parameters.AddWithValue("correlation_id", timeout.CorrelationId); command.Parameters.AddWithValue("reply_to", timeout.ReplyTo); var executeNonQuery = command.ExecuteNonQuery(); if (executeNonQuery == 0) { throw new InvalidOperationException(string.Format("Stale state! Attempted to delete {0} from {1}, but it was already deleted!", timeout, timeoutsTableName)); } } }
private bool Equals(HttpClientCacheKey other) { return(string.Equals(ApiKey, other.ApiKey) && Equals(Credentials, other.Credentials) && Timeout.Equals(other.Timeout) && AuthenticationDisabled.Equals(other.AuthenticationDisabled)); }
/// <summary> /// Adds a timeout to the mainloop. /// </summary> /// <remarks> /// When time time specified passes, the callback will be invoked. /// If the callback returns true, the timeout will be reset, repeating /// the invocation. If it returns false, the timeout will stop. /// /// The returned value is a token that can be used to stop the timeout /// by calling RemoveTimeout. /// </remarks> public object AddTimeout(TimeSpan time, Func<MainLoop,bool> callback) { if (callback == null) throw new ArgumentNullException ("callback"); var timeout = new Timeout () { Span = time, Callback = callback }; AddTimeout (time, timeout); return timeout; }
public void Yes() { Timeout.StopTimers(); GameFlags.AdultIsPresent = true; GUIHelper.NextGUI(); }
/// <inheritdoc/> public Task<Position> GetPositionAsync(int timeoutMilliseconds = Timeout.Infite, CancellationToken? token = null, bool includeHeading = false) { if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infite) throw new ArgumentOutOfRangeException("timeoutMilliseconds"); if (!token.HasValue) token = CancellationToken.None; IAsyncOperation<Geoposition> pos = GetGeolocator().GetGeopositionAsync(TimeSpan.FromTicks(0), TimeSpan.FromDays(365)); token.Value.Register(o => ((IAsyncOperation<Geoposition>)o).Cancel(), pos); var timer = new Timeout(timeoutMilliseconds, pos.Cancel); var tcs = new TaskCompletionSource<Position>(); pos.Completed = (op, s) => { timer.Cancel(); switch (s) { case AsyncStatus.Canceled: tcs.SetCanceled(); break; case AsyncStatus.Completed: tcs.SetResult(GetPosition(op.GetResults())); break; case AsyncStatus.Error: Exception ex = op.ErrorCode; if (ex is UnauthorizedAccessException) ex = new GeolocationException(GeolocationError.Unauthorized, ex); tcs.SetException(ex); break; } }; return tcs.Task; }
public void Handle(Timeout e) { RescheduleTimeout(TimeSpan.FromMinutes(30)); }
public void TimeoutObject() { bool done = false; Timeout timeout = new Timeout(250); timeout.Then(null,() => { done = true; }); Assert.IsFalse(done); System.Threading.Thread.Sleep(350); Assert.IsTrue(done); }
public static extern NativeCallResults.WaitResult TrackerPopResult( NativeHandles.TrackerHandle trackerHandle, out NativeHandles.BodyFrameHandle bodyFrameHandle, Timeout timeout);
public bool Equals(State <TS, TD> other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(EqualityComparer <TS> .Default.Equals(StateName, other.StateName) && EqualityComparer <TD> .Default.Equals(StateData, other.StateData) && Timeout.Equals(other.Timeout) && Equals(StopReason, other.StopReason) && Equals(Replies, other.Replies)); }
/// <summary>Adds a Azure Kinect sensor capture to the tracker input queue to generate its body tracking result asynchronously.</summary> /// <param name="capture">It should contain the depth and IR data compatible with <see cref="DepthMode"/> for this function to work. Not <see langword="null"/>.</param> /// <param name="timeout"> /// Specifies the time the function should block waiting to add the sensor capture to the tracker process queue. /// Default value is <see cref="Timeout.NoWait"/>, which means checking of the status without blocking. /// Passing <see cref="Timeout.Infinite"/> will block indefinitely until the capture is added to the process queue. /// </param> /// <returns> /// <see langword="true"/> - if a sensor capture is successfully added to the processing queue. /// <see langword="false"/> - if the queue is still full (see <see cref="IsQueueFull"/> property) before the <paramref name="timeout"/> elapses. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="capture"/> cannot be <see langword="null"/>.</exception> /// <exception cref="ArgumentException"><paramref name="capture"/> doesn't contain depth and/or IR data compatible with <see cref="DepthMode"/>.</exception> /// <exception cref="ObjectDisposedException">Object was disposed before this call or has been disposed during this call.</exception> /// <exception cref="BodyTrackingException">Cannot add capture to the tracker for some unknown reason. See logs for details.</exception> public bool TryEnqueueCapture(Capture capture, Timeout timeout = default) { if (capture is null) { throw new ArgumentNullException(nameof(capture)); } var res = NativeApi.TrackerEnqueueCapture(handle.ValueNotDisposed, Capture.ToHandle(capture), timeout); if (res == NativeCallResults.WaitResult.Timeout) { return(false); } if (res == NativeCallResults.WaitResult.Failed) { handle.CheckNotDisposed(); // to throw ObjectDisposedException() if failure is a result of disposing using (var depthImage = capture.DepthImage) { if (depthImage == null) { throw new ArgumentException( "Capture should contain the depth data.", nameof(capture)); } if (depthImage.Format != ImageFormat.Depth16) { throw new ArgumentException( $"Invalid format of depth data in capture: expected {ImageFormat.Depth16} but was {depthImage.Format}.", nameof(capture)); } if (depthImage.WidthPixels != DepthMode.WidthPixels() || depthImage.HeightPixels != DepthMode.HeightPixels()) { throw new ArgumentException( $"Invalid resolution of depth data in capture: expected {DepthMode.WidthPixels()}x{DepthMode.HeightPixels()} pixels but was {depthImage.WidthPixels}x{depthImage.HeightPixels} pixels.", nameof(capture)); } } using (var irImage = capture.IRImage) { if (irImage == null) { throw new ArgumentException( "Capture should contain the IR data.", nameof(capture)); } if (irImage.Format != ImageFormat.IR16) { throw new ArgumentException( $"Invalid format of IR data in capture: expected {ImageFormat.IR16} but was {irImage.Format}.", nameof(capture)); } if (irImage.WidthPixels != DepthMode.WidthPixels() || irImage.HeightPixels != DepthMode.HeightPixels()) { throw new ArgumentException( $"Invalid resolution of IR data in capture: expected {DepthMode.WidthPixels()}x{DepthMode.HeightPixels()} pixels but was {irImage.WidthPixels}x{irImage.HeightPixels} pixels.", nameof(capture)); } } throw new BodyTrackingException("Cannot add new capture to body tracking pipeline. See logs for details."); } Interlocked.Increment(ref queueSize); QueueSizeIncreased?.Invoke(this, EventArgs.Empty); return(true); }
public void Handle(Timeout e) { }
/// <summary>Gets the next available body frame.</summary> /// <param name="bodyFrame"> /// If successful this contains object with body data (don't forget to free this object by calling <see cref="BodyFrame.Dispose"/>), /// otherwise - <see langword="null"/>. /// </param> /// <param name="timeout"> /// Specifies the time the function should block waiting for the body frame. /// Default value is <see cref="Timeout.NoWait"/>, which means checking of the status without blocking. /// Passing <see cref="Timeout.Infinite"/> will block indefinitely until the body frame becomes available. /// </param> /// <returns> /// <see langword="true"/> - if a body frame is returned, /// <see langword="false"/> - if a body frame is not available before the timeout elapses. /// </returns> /// <exception cref="ObjectDisposedException">Object was disposed before this call or has been disposed during this call.</exception> /// <exception cref="BodyTrackingException">Cannot get body frame for some unknown reason. See logs for details.</exception> /// <seealso cref="PopResult"/> public bool TryPopResult([NotNullWhen(returnValue: true)] out BodyFrame?bodyFrame, Timeout timeout = default) { var res = NativeApi.TrackerPopResult(handle.ValueNotDisposed, out var bodyFrameHandle, timeout); if (res == NativeCallResults.WaitResult.Timeout) { bodyFrame = null; return(false); } if (res == NativeCallResults.WaitResult.Failed) { handle.CheckNotDisposed(); // to throw ObjectDisposedException() if failure is a result of disposing throw new BodyTrackingException("Cannot extract tracking result from body tracking pipeline. See logs for details."); } Interlocked.Decrement(ref queueSize); QueueSizeDecreased?.Invoke(this, EventArgs.Empty); bodyFrame = BodyFrame.Create(bodyFrameHandle); return(bodyFrame != null); }
public void ToString_ReturnsMilliseconds() { var t = new Timeout(123456); Assert.AreEqual("123456", t.ToString()); Assert.AreEqual("123456", (string)t); }
void OnTimeoutElapsed(Timeout t) { // no need to call gameobject.destroy here because Timeout does it // for us. Destroyed?.Invoke(this); }
/// <summary> /// Generate the necessary parameters /// </summary> public List <KeyValuePair <string, string> > GetParams() { var p = new List <KeyValuePair <string, string> >(); if (From != null) { p.Add(new KeyValuePair <string, string>("From", From.ToString())); } if (To != null) { p.Add(new KeyValuePair <string, string>("To", To.ToString())); } if (StatusCallback != null) { p.Add(new KeyValuePair <string, string>("StatusCallback", Serializers.Url(StatusCallback))); } if (StatusCallbackMethod != null) { p.Add(new KeyValuePair <string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString())); } if (StatusCallbackEvent != null) { p.AddRange(StatusCallbackEvent.Select(prop => new KeyValuePair <string, string>("StatusCallbackEvent", prop))); } if (Timeout != null) { p.Add(new KeyValuePair <string, string>("Timeout", Timeout.ToString())); } if (Record != null) { p.Add(new KeyValuePair <string, string>("Record", Record.Value.ToString().ToLower())); } if (Muted != null) { p.Add(new KeyValuePair <string, string>("Muted", Muted.Value.ToString().ToLower())); } if (Beep != null) { p.Add(new KeyValuePair <string, string>("Beep", Beep)); } if (StartConferenceOnEnter != null) { p.Add(new KeyValuePair <string, string>("StartConferenceOnEnter", StartConferenceOnEnter.Value.ToString().ToLower())); } if (EndConferenceOnExit != null) { p.Add(new KeyValuePair <string, string>("EndConferenceOnExit", EndConferenceOnExit.Value.ToString().ToLower())); } if (WaitUrl != null) { p.Add(new KeyValuePair <string, string>("WaitUrl", Serializers.Url(WaitUrl))); } if (WaitMethod != null) { p.Add(new KeyValuePair <string, string>("WaitMethod", WaitMethod.ToString())); } if (EarlyMedia != null) { p.Add(new KeyValuePair <string, string>("EarlyMedia", EarlyMedia.Value.ToString().ToLower())); } if (MaxParticipants != null) { p.Add(new KeyValuePair <string, string>("MaxParticipants", MaxParticipants.ToString())); } if (ConferenceRecord != null) { p.Add(new KeyValuePair <string, string>("ConferenceRecord", ConferenceRecord)); } if (ConferenceTrim != null) { p.Add(new KeyValuePair <string, string>("ConferenceTrim", ConferenceTrim)); } if (ConferenceStatusCallback != null) { p.Add(new KeyValuePair <string, string>("ConferenceStatusCallback", Serializers.Url(ConferenceStatusCallback))); } if (ConferenceStatusCallbackMethod != null) { p.Add(new KeyValuePair <string, string>("ConferenceStatusCallbackMethod", ConferenceStatusCallbackMethod.ToString())); } if (ConferenceStatusCallbackEvent != null) { p.AddRange(ConferenceStatusCallbackEvent.Select(prop => new KeyValuePair <string, string>("ConferenceStatusCallbackEvent", prop))); } if (RecordingChannels != null) { p.Add(new KeyValuePair <string, string>("RecordingChannels", RecordingChannels)); } if (RecordingStatusCallback != null) { p.Add(new KeyValuePair <string, string>("RecordingStatusCallback", Serializers.Url(RecordingStatusCallback))); } if (RecordingStatusCallbackMethod != null) { p.Add(new KeyValuePair <string, string>("RecordingStatusCallbackMethod", RecordingStatusCallbackMethod.ToString())); } if (SipAuthUsername != null) { p.Add(new KeyValuePair <string, string>("SipAuthUsername", SipAuthUsername)); } if (SipAuthPassword != null) { p.Add(new KeyValuePair <string, string>("SipAuthPassword", SipAuthPassword)); } if (Region != null) { p.Add(new KeyValuePair <string, string>("Region", Region)); } if (ConferenceRecordingStatusCallback != null) { p.Add(new KeyValuePair <string, string>("ConferenceRecordingStatusCallback", Serializers.Url(ConferenceRecordingStatusCallback))); } if (ConferenceRecordingStatusCallbackMethod != null) { p.Add(new KeyValuePair <string, string>("ConferenceRecordingStatusCallbackMethod", ConferenceRecordingStatusCallbackMethod.ToString())); } if (RecordingStatusCallbackEvent != null) { p.AddRange(RecordingStatusCallbackEvent.Select(prop => new KeyValuePair <string, string>("RecordingStatusCallbackEvent", prop))); } if (ConferenceRecordingStatusCallbackEvent != null) { p.AddRange(ConferenceRecordingStatusCallbackEvent.Select(prop => new KeyValuePair <string, string>("ConferenceRecordingStatusCallbackEvent", prop))); } if (Coaching != null) { p.Add(new KeyValuePair <string, string>("Coaching", Coaching.Value.ToString().ToLower())); } if (CallSidToCoach != null) { p.Add(new KeyValuePair <string, string>("CallSidToCoach", CallSidToCoach.ToString())); } if (Byoc != null) { p.Add(new KeyValuePair <string, string>("Byoc", Byoc.ToString())); } return(p); }
public static extern NativeCallResults.WaitResult TrackerEnqueueCapture( NativeHandles.TrackerHandle trackerHandle, NativeHandles.CaptureHandle sensorCaptureHandle, Timeout timeout);