Exemplo n.º 1
0
 public IPromise<IEnumerable<Vault>> ReadPriority(bool async)
 {
   if (_readPriority == null)
     _readPriority = _child.ReadPriority(async);
   if (!async) _readPriority.Wait();
   return _readPriority;
 }
Exemplo n.º 2
0
 public IPromise<IEnumerable<Vault>> WritePriority(bool async)
 {
   if (_writePriority == null) 
     _writePriority = _child.WritePriority(async);
   if (!async) _writePriority.Wait();
   return _writePriority;
 }
 private IPromise<User> GetUserInfo(bool async)
 {
   if (_userInfo == null)
   {
     _userInfo = _conn.ItemByQuery(new Command("<Item type=\"User\" action=\"get\" select=\"default_vault\" expand=\"1\"><id>@0</id><Relationships><Item type=\"ReadPriority\" action=\"get\" select=\"priority, related_id\" expand=\"1\" orderBy=\"priority\"/></Relationships></Item>", _conn.UserId), async)
       .FailOver(() => _conn.ItemByQuery(new Command("<Item type=\"User\" action=\"get\" select=\"default_vault\" expand=\"1\"><id>@0</id></Item>", _conn.UserId), async))
       .Convert<IReadOnlyItem, User>(i =>
       {
         var result = new User();
         result.Id = i.Id();
         var vault = i.Property("default_vault").AsItem();
         if (vault.Exists) result.DefaultVault = Vault.GetVault(vault);
         foreach (var rel in i.Relationships("ReadPriority"))
         {
           vault = rel.RelatedId().AsItem();
           if (vault.Exists)
           {
             result.ReadPriority.Add(Vault.GetVault(vault));
           }
         }
         return result;
       })
       .Fail(ex => { ex.Rethrow(); });
   }
   return _userInfo;
 }
        public void getString(IPromise promise)
        {
            if (promise == null)
            {
                throw new ArgumentNullException(nameof(promise));
            }

            RunOnDispatcher(async () =>
            {
                try
                {
                    var clip = _clipboard.GetContent();
                    if (clip == null)
                    {
                        promise.Resolve("");
                    }
                    else if (clip.Contains(DataTransfer.StandardDataFormats.Text))
                    {
                        var text = await clip.GetTextAsync().AsTask().ConfigureAwait(false);
                        promise.Resolve(text);
                    }
                    else
                    {
                        promise.Resolve("");
                    }
                }
                catch (Exception ex)
                {
                    promise.Reject(ex);
                }
            });
        }
        public async void canOpenURL(string url, IPromise promise)
        {
            if (url == null)
            {
                promise.Reject(new ArgumentNullException(nameof(url)));
                return;
            }

            var uri = default(Uri);
            if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                promise.Reject(new ArgumentException(Invariant($"URL argument '{uri}' is not valid.")));
                return;
            }

            try
            {
                var support = await Launcher.QueryUriSupportAsync(uri, LaunchQuerySupportType.Uri).AsTask().ConfigureAwait(false);
                promise.Resolve(support == LaunchQuerySupportStatus.Available);
            }
            catch (Exception ex)
            {
                promise.Reject(new InvalidOperationException(
                    Invariant($"Could not check if URL '{url}' can be opened."), ex));
            }
        }
        public async void openURL(string url, IPromise promise)
        {
            if (url == null)
            {
                promise.Reject(new ArgumentNullException(nameof(url)));
                return;
            }

            var uri = default(Uri);
            if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                promise.Reject(new ArgumentException(Invariant($"URL argument '{uri}' is not valid.")));
                return;
            }

            try
            {
                await Launcher.LaunchUriAsync(uri).AsTask().ConfigureAwait(false);
                promise.Resolve(true);
            }
            catch (Exception ex)
            {
                promise.Reject(new InvalidOperationException(
                    Invariant($"Could not open URL '{url}'."), ex));
            }
        }
Exemplo n.º 7
0
    private void ProcessCommand(bool force)
    {
      _commands++;
      if ((force || _commands > this.Threshold) && _builder.Length > 5)
      {
        // Execute the query
        _builder.Append("</sql>");
        WaitLastResult();
        _lastQuery = _builder.ToString();

        // Run either synchronously or asynchronously based on what's currently supported
        var asyncConn = _conn as IAsyncConnection;
        if (asyncConn == null)
        {
          _conn.Apply(new Command(_lastQuery).WithAction(CommandAction.ApplySQL)).AssertNoError();
        }
        else
        {
          _lastResult = asyncConn.Process(new Command(_lastQuery).WithAction(CommandAction.ApplySQL), true);
        }

        // Reset the state
        _builder.Length = 0;
        _builder.Append("<sql>");
        _commands = 0;
      }
    }
        public void getScriptText(IPromise promise)
        {
            var map = new JObject
            {
                { "fullSourceMappingURL", _sourceMapUrl },
            };

            promise.Resolve(map);
        }
Exemplo n.º 9
0
		public void setup()
		{
			promise = new Promise();
			promiseOneArg = new Promise<int>();
			promiseTwoArg = new Promise<int, int>();
			promiseThreeArg = new Promise<int, int, int>();
			promiseFourArg = new Promise<int, int, int, int>();
			value = 0;
			currentException = null;
			currentProgress = 0.0f;
		}
Exemplo n.º 10
0
        public void Push(CorrelationId correlation, IPromise promise, IEnumerable<MessageIdentifier> messageIdentifiers)
        {
            IDictionary<MessageIdentifier, IPromise> messageHandlers;
            if (handlers.TryGetValue(correlation, out messageHandlers))
            {
                throw new DuplicatedKeyException($"Duplicated key: Correlation[{correlation.Value.GetString()}]");
            }

            var delayedItem = expirationQueue.Delay(correlation, promise.ExpireAfter);
            ((Promise)promise).SetExpiration(delayedItem);

            handlers[correlation] = messageIdentifiers.ToDictionary(mp => mp, mp => promise);
        }
        public void downloadUpdate(JObject updatePackage, bool notifyProgress, IPromise promise)
        {
            Action downloadAction = async () =>
            {
                try
                {
                    updatePackage[CodePushConstants.BinaryModifiedTimeKey] = "" + await _codePush.GetBinaryResourcesModifiedTime();
                    await _codePush.UpdateManager.DownloadPackage(
                        updatePackage,
                        _codePush.AssetsBundleFileName,
                        new Progress<HttpProgress>(
                            (HttpProgress progress) =>
                            {
                                if (!notifyProgress)
                                {
                                    return;
                                }

                                var downloadProgress = new JObject()
                                {
                                    { "totalBytes", progress.TotalBytesToReceive },
                                    { "receivedBytes", progress.BytesReceived }
                                };

                                _reactContext
                                    .GetJavaScriptModule<RCTDeviceEventEmitter>()
                                    .emit(CodePushConstants.DownloadProgressEventName, downloadProgress);
                            }
                        )
                    );

                    JObject newPackage = await _codePush.UpdateManager.GetPackage((string)updatePackage[CodePushConstants.PackageHashKey]);
                    promise.Resolve(newPackage);
                }
                catch (InvalidDataException e)
                {
                    CodePushUtils.Log(e.ToString());
                    SettingsManager.SaveFailedUpdate(updatePackage);
                    promise.Reject(e);
                }
                catch (Exception e)
                {
                    CodePushUtils.Log(e.ToString());
                    promise.Reject(e);
                }
            };

            Context.RunOnNativeModulesQueueThread(downloadAction);
        }
Exemplo n.º 12
0
        public void RandomUrls()
        {
            ServerConfig options = new ServerConfig {
                TimeoutSeconds=5
            };

            int outer = totalTests/simultaneousThreads;
            var list = GetRandomUrls(totalTests);
            List<string> successList = new List<string>();
            List<string> failList = new List<string>();

            int cur=0;
            for (int i = 0; i < outer; i++)
            {
                IPromise[] promises = new IPromise[simultaneousThreads];
                List<string> active = new List<string>();

                for (int j = 0; j < simultaneousThreads; j++)
                {
                    string url = list[cur++];
                    active.Add(url);

                    promises[j] = CQ.CreateFromUrlAsync(url, options).Then((success) =>
                    {
                        successList.Add(FormatResult(success));
                        active.Remove(success.Url);
    
                    },(fail) => {

                        failList.Add(FormatResult(fail));
                        active.Remove(fail.Url);
                    });

                }

                
                if (!AsyncWebRequestManager.WaitForAsyncEvents(10000))
                {
                    AsyncWebRequestManager.CancelAsyncEvents();
                    foreach (var item in active)
                    {
                        failList.Add(item + ": aborted");
                    }
                }
            }

           Debug.WriteLine(FormatTestOutput(successList,failList));
        }
        public void getString(IPromise promise)
        {
            if (promise == null)
            {
                throw new ArgumentNullException(nameof(promise));
            }

            if (_clipboard.ContainsText())
            {
                var text = _clipboard.GetText();
                promise.Resolve(text);
            }
            else
            {
                promise.Resolve("");
            }

        }
        public void getSize(string uriString, IPromise promise)
        {
            if (string.IsNullOrEmpty(uriString))
            {
                promise.Reject(ErrorInvalidUri, "Cannot get the size of an image for an empty URI.");
                return;
            }

            DispatcherHelpers.RunOnDispatcher(async () =>
            {
                try
                {
                    var bitmapImage = new BitmapImage();
                    var loadQuery = bitmapImage.GetStreamLoadObservable()
                        .Where(status => status.LoadStatus == ImageLoadStatus.OnLoadEnd)
                        .FirstAsync()
                        .Replay(1);

                    using (loadQuery.Connect())
                    {
                        using (var stream = await BitmapImageHelpers.GetStreamAsync(uriString))
                        {
                            await bitmapImage.SetSourceAsync(stream);
                        }

                        await loadQuery;

                        promise.Resolve(new JObject
                        {
                            { "width", bitmapImage.PixelWidth },
                            { "height", bitmapImage.PixelHeight },
                        });
                    }
                }
                catch (Exception ex)
                {
                    promise.Reject(ErrorGetSizeFailure, ex.Message);
                }
            });
        }
Exemplo n.º 15
0
 public ReadOnlyPromise(IPromise promised, bool allowWait)
 {
     _promised = promised;
     if (allowWait)
     {
         var promise = _promised as IWaitablePromise;
         if (promise != null)
         {
             _wait = () => promise.Wait();
         }
         else
         {
             _wait = () => ThreadingHelper.SpinWaitUntil(() => _promised.IsCompleted);
         }
     }
     else
     {
         _wait = () =>
         {
             throw new InvalidOperationException();
         };
     }
 }
Exemplo n.º 16
0
    public void SetConnection(ConnectionData connData)
    {
      _conn = null;
      _connData = null;
      btnEditConnection.Text = "No Connection ▼";
      lblConnColor.BackColor = Color.Transparent;

      if (connData.Type != ConnectionType.Innovator)
      {
        MessageBox.Show("Only Innovator connections are supported");
        return;
      }

      _connData = connData;
      btnEditConnection.Text = "Connecting... ▼";
      _conn = connData.ArasLogin(true)
        .UiPromise(this)
        .Done(c =>
        {
          btnEditConnection.Text = connData.ConnectionName + " ▼";
          lblConnColor.BackColor = connData.Color;
        });
    }
 public void notifyApplicationReady(IPromise promise)
 {
     SettingsManager.RemovePendingUpdate();
     promise.Resolve("");
 }
Exemplo n.º 18
0
        static void WritePromiseCombiner(IChannelHandlerContext ctx, List <object> output, IPromise promise)
        {
            PromiseCombiner combiner = new PromiseCombiner();

            for (int i = 0; i < output.Count; i++)
            {
                combiner.Add(ctx.WriteAsync(output[i]));
            }
            combiner.Finish(promise);
        }
Exemplo n.º 19
0
        private async Task <bool> PickMultipleFileAsync(FileOpenPicker picker, Boolean cache, Boolean readContent, IPromise promise)
        {
            IReadOnlyList <StorageFile> files = await picker.PickMultipleFilesAsync().AsTask().ConfigureAwait(false);

            if (files.Count > 0)
            {
                JArray jarrayObj = new JArray();
                foreach (var file in files)
                {
                    jarrayObj.Add(PrepareFile(file, cache, readContent).Result);
                }
                promise.Resolve(jarrayObj);
            }
            else
            {
                promise.Reject(E_DOCUMENT_PICKER_CANCELED, "User canceled document picker");
            }

            return(true);
        }
Exemplo n.º 20
0
        public void pick(JObject options, IPromise promise)
        {
            try
            {
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                // Get file type array options
                var fileTypeArray = options.Value <JArray>(OPTION_TYPE);
                var cache         = options.Value <Boolean>(CACHE_TYPE);
                // Init file type filter
                if (fileTypeArray != null && fileTypeArray.Count > 0)
                {
                    foreach (String typeString in fileTypeArray)
                    {
                        List <String> types = typeString.Split(' ').ToList();
                        foreach (String type in types)
                        {
                            if (Regex.Match(type, "(^[.]+[A-Za-z0-9]*$)|(^[*]$)").Success)
                            {
                                openPicker.FileTypeFilter.Add(type);
                            }
                        }
                    }
                }
                else
                {
                    openPicker.FileTypeFilter.Add("*");
                }

                RunOnDispatcher(async() =>
                {
                    try
                    {
                        if (_isInForeground)
                        {
                            var isMultiple  = options.Value <bool>(OPTION_MULIPLE);
                            var readContent = options.Value <bool>(OPTION_READ_CONTENT);
                            if (isMultiple)
                            {
                                await PickMultipleFileAsync(openPicker, cache, readContent, promise);
                            }
                            else
                            {
                                await PickSingleFileAsync(openPicker, cache, readContent, promise);
                            }
                        }
                        else
                        {
                            _pendingPicker = openPicker;
                        }
                    }
                    catch (Exception ex)
                    {
                        promise.Reject(E_FAILED_TO_SHOW_PICKER, ex.Message);
                    }
                });
            }
            catch (Exception ex) {
                promise.Reject(E_UNEXPECTED_EXCEPTION, ex.Message);
            }
        }
 public void Foo(IPromise promise, int foo)
 {
 }
Exemplo n.º 22
0
 public static IObservable <T> ToObservable <T>(this IPromise <T> promise, IScheduler scheduler = null)
 {
     return(new PromiseObservable <T>(promise, scheduler));
 }
 public void getNewStatusReport(IPromise promise)
 {
     // TODO implement this
     promise.Resolve("");
 }
Exemplo n.º 24
0
 public SelfParameterSyntax(TextSpan span, bool mutableSelf)
     : base(span, null)
 {
     MutableSelf = mutableSelf;
     DataType    = Symbol.Select(s => s.DataType);
 }
Exemplo n.º 25
0
        public async void SearchLibrary(string libraryName, JObject searchLibraryQuery, IPromise promise)
        {
            try
            {
                // If the library is not found KeyNotFoundException will be thrown and the promise will be rejected.
                var library = _libraries[libraryName];

                var libraryQuery = JsonUtils.ToLibraryQuery(searchLibraryQuery);

                TaskCompletionSource <IList <LibraryPreviewResult> >             previewsFromHandlerTcs = null;
                TaskCompletionSource <IDictionary <string, LibraryQueryResult> > resultsFromHandlerTcs  = null;
                if (libraryQuery.GenerateTextPreviews)
                {
                    previewsFromHandlerTcs = GetPreviewCompleteTcs(library);
                }
                else
                {
                    resultsFromHandlerTcs = GetSearchCompleteTcs(library);
                }

                // Ensure all indexing is complete before search.
                await library.WaitForAllIndexingTasksToFinishAsync().AsTask().ConfigureAwait(false);

                // We can do the searching in the background as the callbacks will receive the results.
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                library.SearchAsync(libraryQuery);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                if (previewsFromHandlerTcs != null)
                {
                    var previewResults = await previewsFromHandlerTcs.Task.ConfigureAwait(false);

                    promise.Resolve(JsonUtils.PreviewResultsToJson(previewResults));
                }

                if (resultsFromHandlerTcs != null)
                {
                    var resultsFromHandler = await resultsFromHandlerTcs.Task.ConfigureAwait(false);

                    promise.Resolve(JsonUtils.SearchResultsToJson(resultsFromHandler));
                }
            }
            catch (Exception e)
            {
                promise.Reject(e);
            }
        }
Exemplo n.º 26
0
 public PendingWrite(object msg, IPromise promise)
 {
     Message = msg;
     Promise = promise;
 }
Exemplo n.º 27
0
 public override void Write(IChannelHandlerContext context, object message, IPromise promise)
 {
     _queue.AddLast​(new PendingWrite(message, promise));
 }
Exemplo n.º 28
0
 public Task Foo(IPromise promise)
 {
     return(Task.FromResult(true));
 }
        /// <summary>
        /// Simulate a task.
        /// </summary>
        /// <returns>The task.</returns>
        /// <param name="promise">Promise.</param>
        protected IEnumerator DoTask(IPromise promise)
        {
            yield return(new WaitForSeconds(0.5f));

            promise.SetResult();
        }
Exemplo n.º 30
0
 public abstract Task CloseAsync(IPromise promise);
Exemplo n.º 31
0
 private void InitializeProcessQueue()
 {
     currentProcess = Promise.Resolved();
 }
        /// <summary>
        /// Remove a <see cref="IByteBuffer"/> from the queue with the specified number of bytes. Any added buffer who's bytes are
        /// fully consumed during removal will have it's promise completed when the passed aggregate <see cref="IPromise"/>
        /// completes.
        /// </summary>
        /// <param name="alloc">The allocator used if a new <see cref="IByteBuffer"/> is generated during the aggregation process.</param>
        /// <param name="bytes">the maximum number of readable bytes in the returned <see cref="IByteBuffer"/>, if {@code bytes} is greater
        /// than <see cref="ReadableBytes"/> then a buffer of length <see cref="ReadableBytes"/> is returned.</param>
        /// <param name="aggregatePromise">used to aggregate the promises and listeners for the constituent buffers.</param>
        /// <returns>a <see cref="IByteBuffer"/> composed of the enqueued buffers.</returns>
        public IByteBuffer Remove(IByteBufferAllocator alloc, int bytes, IPromise aggregatePromise)
        {
            if ((uint)bytes > SharedConstants.TooBigOrNegative)
            {
                ThrowHelper.ThrowArgumentException_PositiveOrZero(bytes, ExceptionArgument.bytes);
            }
            if (aggregatePromise is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.aggregatePromise);
            }

            // Use isEmpty rather than readableBytes==0 as we may have a promise associated with an empty buffer.
            if (_bufAndListenerPairs.IsEmpty)
            {
                Debug.Assert(_readableBytes == 0);
                return(RemoveEmptyValue());
            }
            bytes = Math.Min(bytes, _readableBytes);

            IByteBuffer toReturn      = null;
            IByteBuffer entryBuffer   = null;
            int         originalBytes = bytes;

            try
            {
                while (_bufAndListenerPairs.TryRemoveFirst(out var entry))
                {
                    if (entry is IPromise promise)
                    {
                        aggregatePromise.Task.CascadeTo(promise, Logger);
                        continue;
                    }
                    entryBuffer = (IByteBuffer)entry;
                    if (entryBuffer.ReadableBytes > bytes)
                    {
                        // Add the buffer back to the queue as we can't consume all of it.
                        _bufAndListenerPairs.AddFirst​(entryBuffer);
                        if (bytes > 0)
                        {
                            // Take a slice of what we can consume and retain it.
                            entryBuffer = entryBuffer.ReadRetainedSlice(bytes);
                            toReturn    = toReturn is null?ComposeFirst(alloc, entryBuffer)
                                              : Compose(alloc, toReturn, entryBuffer);

                            bytes = 0;
                        }
                        break;
                    }
                    else
                    {
                        bytes   -= entryBuffer.ReadableBytes;
                        toReturn = toReturn is null?ComposeFirst(alloc, entryBuffer)
                                       : Compose(alloc, toReturn, entryBuffer);
                    }
                    entryBuffer = null;
                }
            }
            catch (Exception cause)
            {
                ReferenceCountUtil.SafeRelease(entryBuffer);
                ReferenceCountUtil.SafeRelease(toReturn);
                aggregatePromise.SetException(cause);
                throw;
            }
            DecrementReadableBytes(originalBytes - bytes);
            return(toReturn);
        }
Exemplo n.º 33
0
 public void PlanProcess(Func <IPromise> process)
 {
     currentProcess = currentProcess.Then(process);
 }
Exemplo n.º 34
0
 public virtual Task DisconnectAsync(IPromise promise) => _pipeline.DisconnectAsync(promise);
Exemplo n.º 35
0
 public PromiseObservable(IPromise <T> promise, IScheduler scheduler)
 {
     this.promise   = promise;
     this.scheduler = scheduler ?? Scheduler.Default;
 }
Exemplo n.º 36
0
 public Task DeregisterAsync(IPromise promise) => _pipeline.DeregisterAsync(promise);
 public override void Write(IChannelHandlerContext context, object message, IPromise promise)
 {
     if (message is IHttp2StreamFrame streamFrame)
     {
         frames.Enqueue(streamFrame);
         context.WriteAsync(Unpooled.Empty, promise);
     }
     else
     {
         context.WriteAsync(message, promise);
     }
 }
Exemplo n.º 38
0
        private async Task <bool> PickSingleFileAsync(FileOpenPicker picker, Boolean cache, Boolean readContent, IPromise promise)
        {
            var file = await picker.PickSingleFileAsync().AsTask().ConfigureAwait(false);

            if (file != null)
            {
                JArray jarrayObj = new JArray();
                jarrayObj.Add(PrepareFile(file, cache, readContent).Result);
                promise.Resolve(jarrayObj);
            }
            else
            {
                promise.Reject(E_DOCUMENT_PICKER_CANCELED, "User canceled document picker");
            }

            return(true);
        }
Exemplo n.º 39
0
 public virtual Task CloseAsync(IPromise promise) => _pipeline.CloseAsync(promise);
Exemplo n.º 40
0
 public void respondWith(IPromise<object> r) { }
Exemplo n.º 41
0
 public Task WriteAndFlushAsync(object message, IPromise promise) => _pipeline.WriteAndFlushAsync(message, promise);
Exemplo n.º 42
0
 public static extern Task <TResult> FromPromise <TResult>(IPromise promise, Delegate resultHandler);
 public Task Foo(IPromise promise)
 {
     return(Task.CompletedTask);
 }
Exemplo n.º 44
0
		public void TestThenOrder()
		{
			promiseOneArg.Then(OneArgCallback);
			promiseOneArg.Then(OneArgCallbackTwo);
			promiseOneArg.Then(OneArgCallbackThree);

			promiseOneArg.Dispatch(add);
			Assert.AreEqual((add+(add * 2))*add, value);

			value = 0;

			promiseOneArg = new Promise<int>();
			promiseOneArg.Then(OneArgCallback);
			promiseOneArg.Then(OneArgCallbackThree);
			promiseOneArg.Then(OneArgCallbackTwo);

			promiseOneArg.Dispatch(add);
			Assert.AreEqual((add*add)+(add*2), value);
		}
Exemplo n.º 45
0
        /// <inheritdoc />
        public override void Write(IChannelHandlerContext ctx, object msg, IPromise promise)
        {
            ThreadLocalObjectList output = null;

            try
            {
                if (AcceptOutboundMessage(msg))
                {
                    output = ThreadLocalObjectList.NewInstance();
                    var cast = (T)msg;
                    try
                    {
                        Encode(ctx, cast, output);
                    }
                    finally
                    {
                        _ = ReferenceCountUtil.Release(cast);
                    }

                    if (0u >= (uint)output.Count)
                    {
                        CThrowHelper.ThrowEncoderException_MustProduceAtLeastOneMsg(GetType());
                    }
                }
                else
                {
                    _ = ctx.WriteAsync(msg, promise);
                }
            }
            catch (EncoderException)
            {
                throw;
            }
            catch (Exception ex)
            {
                CThrowHelper.ThrowEncoderException(ex); // todo: we don't have a stack on EncoderException but it's present on inner exception.
            }
            finally
            {
                if (output is object)
                {
                    try
                    {
                        int lastItemIndex = output.Count - 1;
                        if (0u >= (uint)lastItemIndex)
                        {
                            _ = ctx.WriteAsync(output[0], promise);
                        }
                        else if (lastItemIndex > 0)
                        {
                            // Check if we can use a voidPromise for our extra writes to reduce GC-Pressure
                            // See https://github.com/netty/netty/issues/2525
                            if (promise == ctx.VoidPromise())
                            {
                                WriteVoidPromise(ctx, output);
                            }
                            else
                            {
                                WritePromiseCombiner(ctx, output, promise);
                            }
                        }
                    }
                    finally
                    {
                        output.Return();
                    }
                }
            }
        }
Exemplo n.º 46
0
 public override Task WriteRstStreamAsync(IChannelHandlerContext ctx, int streamId, Http2Error errorCode, IPromise promise)
 {
     if (IsExistingStream(streamId))
     {
         return(base.WriteRstStreamAsync(ctx, streamId, errorCode, promise));
     }
     // Since the delegate doesn't know about any buffered streams we have to handle cancellation
     // of the promises and releasing of the ByteBufs here.
     if (_pendingStreams.TryGetValue(streamId, out var stream))
     {
         _ = _pendingStreams.Remove(streamId);
         // Sending a RST_STREAM to a buffered stream will succeed the promise of all frames
         // associated with the stream, as sending a RST_STREAM means that someone "doesn't care"
         // about the stream anymore and thus there is not point in failing the promises and invoking
         // error handling routines.
         stream.Close(null);
         promise.Complete();
     }
     else
     {
         promise.SetException(ThrowHelper.GetConnectionError_StreamDoesNotExist(streamId));
     }
     return(promise.Task);
 }
Exemplo n.º 47
0
 public static extern Task <object[]> FromPromise(IPromise promise);
Exemplo n.º 48
0
 public bool cancel(IPromise promise)
 {
     return false;
 }
Exemplo n.º 49
0
    private IPromise<IResultObject> Submit(string query, OutputType preferred = OutputType.Any)
    {
      if (_currentQuery != null)
      {
        _currentQuery.Cancel();
        _clock.Enabled = false;
        lblProgress.Text = "Canceled";
        _currentQuery = null;
        outputEditor.Text = "";
        _clock.Enabled = false;
        btnSubmit.Text = "► Run";
        return null;
      }

      if (_proxy.ConnData != null && _proxy.ConnData.Confirm)
      {
        if (MessageBox.Show("Do you want to run this query on " + _proxy.ConnData.ConnectionName +"?", "Confirm Execution", MessageBoxButtons.YesNo) == DialogResult.No)
        {
          return null;
        }
      }
      try
      {
        outputEditor.Text = "Processing...";
        lblProgress.Text = "Processing...";
        _start = DateTime.UtcNow;
        _clock.Enabled = true;
        _outputTextSet = false;
        btnSubmit.Text = "Cancel";

        var cmd = _proxy.NewCommand().WithQuery(query).WithAction(this.SoapAction);
        var queryParams = _proxy.GetHelper().GetParameterNames(query)
          .Select(p => GetCreateParameter(p)).ToList();
        if (queryParams.Any() && this.SoapAction != ArasEditorProxy.UnitTestAction)
        {
          using (var dialog = new ParameterWindow(queryParams))
          {
            switch (dialog.ShowDialog(this))
            {
              case System.Windows.Forms.DialogResult.OK:
                foreach (var param in queryParams)
                {
                  cmd.WithParam(param.Name, param.GetValue());
                }
                break;
              case System.Windows.Forms.DialogResult.Ignore:
                break;
              default:
                return null;
            }
          }
        }

        // Only reset if we are getting a new result
        if (preferred != OutputType.None)
        {
          _result = null;
          _outputSet = null;
          var pagesToRemove = tbcOutputView.TabPages.OfType<TabPage>()
                  .Where(p => p.Name.StartsWith(GeneratedPage)).ToArray();
          foreach (var page in pagesToRemove)
          {
            tbcOutputView.TabPages.Remove(page);
          }
          pgTableOutput.Text = "Table";
          dgvItems.DataSource = null;
        }

        if (_proxy.ConnData != null)
        {
          SnippetManager.Instance.SetLastQueryByConnection(_proxy.ConnData.ConnectionName, new Snippet()
          {
            Action = this.SoapAction,
            Text = inputEditor.Text
          });
          Properties.Settings.Default.LastConnection = _proxy.ConnData.ConnectionName;
          Properties.Settings.Default.Save();
          Properties.Settings.Default.Reload();
        }

        var st = Stopwatch.StartNew();
        _currentQuery = _proxy.Process(cmd, true)
          .UiPromise(this)
          .Done(result =>
          {
            try
            {
              var milliseconds = st.ElapsedMilliseconds;
              _clock.Enabled = false;

              SetResult(result, milliseconds, preferred);
            }
            catch (Exception ex)
            {
              Utils.HandleError(ex);
            }
          }).Fail(ex =>
          {
            outputEditor.Text = ex.Message;
            tbcOutputView.SelectedTab = pgTextOutput;
            lblProgress.Text = "Error";
          })
          .Always(() =>
          {
            _clock.Enabled = false;
            _currentQuery = null;
            btnSubmit.Text = "► Run";
          });
      }
      catch (Exception err)
      {
        outputEditor.Text = err.Message;
        tbcOutputView.SelectedTab = pgTextOutput;
        _clock.Enabled = false;
        lblProgress.Text = "Error";
        _currentQuery = null;
        btnSubmit.Text = "► Run";
      }
      return _currentQuery;
    }
 public void isFailedUpdate(string packageHash, IPromise promise)
 {
     promise.Resolve(SettingsManager.IsFailedHash(packageHash));
 }
Exemplo n.º 51
0
    private void btnSubmit_Click(object sender, EventArgs e)
    {
      try
      {
        if (_currentRun == null)
        {
          if (_conn == null)
          {
            outputEditor.Text = "Please select a connection first";
            return;
          }

          btnSubmit.Text = "► Cancel";
          outputEditor.Text = "Processing...";

          _currentRun = _conn
            .Continue(c => _script.Execute(c))
            .UiPromise(this)
            .Done(s =>
            {
              outputEditor.Text = s;
              _currentRun = null;
            })
            .Fail(ex => outputEditor.Text = ex.ToString());
        }
        else
        {
          btnSubmit.Text = "► Run";
          _currentRun.Cancel();
          _currentRun = null;
        }
      }
      catch (Exception ex)
      {
        outputEditor.Text = ex.ToString();
      }
    }
        public void installUpdate(JObject updatePackage, InstallMode installMode, int minimumBackgroundDuration, IPromise promise)
        {
            Action installUpdateAction = async () =>
            {
                await _codePush.UpdateManager.InstallPackage(updatePackage, SettingsManager.IsPendingUpdate(null));
                var pendingHash = (string)updatePackage[CodePushConstants.PackageHashKey];
                SettingsManager.SavePendingUpdate(pendingHash, /* isLoading */false);
                if (installMode == InstallMode.OnNextResume)
                {
                    if (_minimumBackgroundListener == null)
                    {
                        // Ensure we do not add the listener twice.
                        Action loadBundleAction = () =>
                        {
                            Context.RunOnNativeModulesQueueThread(async () =>
                            {
                                await LoadBundle();
                            });
                        };
                        
                        _minimumBackgroundListener = new MinimumBackgroundListener(loadBundleAction, minimumBackgroundDuration);
                        _reactContext.AddLifecycleEventListener(_minimumBackgroundListener);
                    }
                    else
                    {
                        _minimumBackgroundListener.MinimumBackgroundDuration = minimumBackgroundDuration;
                    }
                }

                promise.Resolve("");
            };

            Context.RunOnNativeModulesQueueThread(installUpdateAction);
        }
Exemplo n.º 53
0
    private IPromise<IResultObject> Submit(string query, OutputType preferred = OutputType.Any, int batchSize = 0, int concurrentCount = 0)
    {
      if (_currentQuery != null)
      {
        outputEditor.Text = "";
        _currentQuery.Cancel();
        _currentQuery = null;
        lblClock.Text = "";
        progQuery.Visible = false;
        _clock.Enabled = false;
        btnSubmit.Text = "► Run";
        lblProgress.Text = "Canceled";
        return null;
      }

      if (_proxy.ConnData != null && _proxy.ConnData.Confirm)
      {
        if (Dialog.MessageDialog.Show("Do you want to run this query on " + _proxy.ConnData.ConnectionName + "?", "Confirm Execution"
          , "&Run Query", "&Cancel") != DialogResult.OK)
        {
          return null;
        }
      }
      try
      {
        var cmd = _proxy.NewCommand()
          .WithQuery(query)
          .WithAction(this.SoapAction)
          .WithStatementCount(batchSize)
          .WithConcurrentCount(concurrentCount);
        var queryParams = _proxy.GetHelper().GetParameterNames(query)
          .Select(p => GetCreateParameter(p)).ToList();
        if (queryParams.Any() && this.SoapAction != ArasEditorProxy.UnitTestAction)
        {
          using (var dialog = new Dialog.ParameterDialog(queryParams))
          {
            switch (dialog.ShowDialog(this))
            {
              case System.Windows.Forms.DialogResult.OK:
                foreach (var param in queryParams)
                {
                  cmd.WithParam(param.Name, param.GetValue());
                }
                break;
              case System.Windows.Forms.DialogResult.Ignore:
                break;
              default:
                return null;
            }
          }
        }

        outputEditor.Text = "Processing...";
        lblProgress.Text = "Processing...";
        _start = DateTime.UtcNow;
        lblClock.Text = "";
        progQuery.Visible = true;
        _clock.Enabled = true;
        _outputTextSet = false;
        btnSubmit.Text = "Cancel";

        // Only reset if we are getting a new result
        if (preferred != OutputType.None)
        {
          _result = null;
          _outputSet = null;
          CleanupGrids();
        }

        if (_proxy.ConnData != null)
        {
          SnippetManager.Instance.SetLastQueryByConnection(_proxy.ConnData.ConnectionName, new Snippet()
          {
            Action = this.SoapAction,
            Text = inputEditor.Text
          });
          Properties.Settings.Default.LastConnection = _proxy.ConnData.ConnectionName;
          Properties.Settings.Default.Save();
          Properties.Settings.Default.Reload();
        }

        var st = Stopwatch.StartNew();
        _currentQuery = _proxy
          .Process(cmd, true, (p, m) => this.UiThreadInvoke(() =>
          {
            lblProgress.Text = m;
            progQuery.Value = p;
          }))
          .UiPromise(this)
          .Done(result =>
          {
            try
            {
              var milliseconds = st.ElapsedMilliseconds;
              _clock.Enabled = false;

              SetResult(result, milliseconds, preferred);
            }
            catch (Exception ex)
            {
              Utils.HandleError(ex);
            }
          }).Fail(ex =>
          {
            outputEditor.Text = ex.Message;
            tbcOutputView.SelectedTab = pgTextOutput;
            lblProgress.Text = "Error";
          })
          .Always(() =>
          {
            lblClock.Text = "";
            _clock.Enabled = false;
            _currentQuery = null;
            progQuery.Visible = false;
            btnSubmit.Text = "► Run";
          });

        // Handle the synchronous option
        if (!_clock.Enabled)
          _currentQuery = null;
      }
      catch (Exception err)
      {
        outputEditor.Text = err.Message;
        tbcOutputView.SelectedTab = pgTextOutput;
        _clock.Enabled = false;
        progQuery.Visible = false;
        lblClock.Text = "";
        lblProgress.Text = "Error";
        _currentQuery = null;
        btnSubmit.Text = "► Run";
      }
      return _currentQuery;
    }
        public void isFirstRun(string packageHash, IPromise promise)
        {
            Action isFirstRunAction = async () =>
            {
                bool isFirstRun = _codePush.DidUpdate
                    && packageHash != null
                    && packageHash.Length > 0
                    && packageHash.Equals(await _codePush.UpdateManager.GetCurrentPackageHash());
                promise.Resolve(isFirstRun);
            };

            Context.RunOnNativeModulesQueueThread(isFirstRunAction);
        }
 public void getCurrentConnectivity(IPromise promise)
 {
     promise.Resolve(CreateConnectivityEventMap());
 }
 public void prefetchImage(string uriString, int requestId, IPromise promise)
 {
     promise.Reject(ErrorPrefetchFailure, "Prefetch is not yet implemented.");
 }
 public void prefetchImage(string uriString, IPromise promise)
 {
     promise.Reject(ErrorPrefetchFailure, "Prefetch is not yet implemented.");
 }
 public void queryCache(string[] urls, IPromise promise)
 {
     promise.Reject(ErrorQueryCacheFailure, "Prefetch is not yet implemented.");
 }
Exemplo n.º 59
0
    public IPromise<CompletionData> GetCompletions(string xml, string soapAction)
    {
      //var overlap = 0;
      if (string.IsNullOrEmpty(xml)) return Promises.Resolved<CompletionData>(new CompletionData());

      var path = new List<AmlNode>();
      string attr = null;
      string attrValue = null;

      var state = XmlUtils.ProcessFragment(xml, (r, o) =>
      {
        switch (r.NodeType)
        {
          case XmlNodeType.Element:
            if (!r.IsEmptyElement)
              path.Add(new AmlNode() { LocalName = r.LocalName, Type = r.GetAttribute("type"), Action = r.GetAttribute("action") });
            break;
          case XmlNodeType.EndElement:
            path.RemoveAt(path.Count - 1);
            break;
          case XmlNodeType.Attribute:
            attr = r.LocalName;
            attrValue = r.Value;
            break;
        }
        return true;
      });
      if (state == XmlState.Tag && (xml.Last() == '"' || xml.Last() == '\''))
        return Promises.Resolved<CompletionData>(new CompletionData());

      IPromise<IEnumerable<string>> items = null;
      var filter = string.Empty;
      var multiValueAttribute = false;

      if (path.Count < 1)
      {
        switch (soapAction)
        {
          case "ApplySQL":
            items = StringPromise("sql");
            break;
          case "ApplyAML":
            items = StringPromise("AML");
            break;
          default:
            items = StringPromise("Item");
            break;
        }
      }
      else
      {
        switch (state)
        {
          case XmlState.Attribute:
          case XmlState.AttributeStart:
            switch (path.Last().LocalName)
            {
              case "and":
              case "or":
              case "not":
              case "Relationships":
              case "AML":
              case "sql":
              case "SQL":
                break;
              case "Item":
                switch (soapAction)
                {
                  case "GenerateNewGUIDEx":
                    items = StringPromise("quantity");
                    break;
                  case "":
                    break;
                  default:
                    items = StringPromise(new string[] {"action"
                      , "access_type"
                      , "config_path"
                      , "doGetItem"
                      , "id"
                      , "idlist"
                      , "isCriteria"
                      , "language"
                      , "levels"
                      , "maxRecords"
                      , "page"
                      , "pagesize"
                      , "orderBy"
                      , "queryDate"
                      , "queryType"
                      , "related_expand"
                      , "select"
                      , "serverEvents"
                      , "type"
                      , "typeID"
                      , "version"
                      , "where"}
                      .Where(i => path.Last().Action == "getPermissions" || i != "access_type"));
                    break;
                }
                break;
              default:
                items = StringPromise("condition", "is_null");
                break;
            }

            filter = attr;
            break;
          case XmlState.AttributeValue:
            if (path.Last().LocalName == "Item")
            {
              ItemType itemType;
              switch (attr)
              {
                case "action":
                  if (_methods == null && _conn != null)
                  {
                    _methods = _conn.ApplyAsync("<AML><Item action=\"get\" type=\"Method\" select=\"name\"></Item></AML>", true, false)
                      .Convert(r => r.Items()
                                     .Select(m => m.Property("name").AsString("")));
                  }

                  var baseMethods = new string[] {"ActivateActivity"
                    , "add"
                    , "AddItem"
                    , "AddHistory"
                    , "ApplyUpdate"
                    , "BuildProcessReport"
                    , "CancelWorkflow"
                    , "checkImportedItemType"
                    , "closeWorkflow"
                    , "copy"
                    , "copyAsIs"
                    , "copyAsNew"
                    , "create"
                    , "delete"
                    , "edit"
                    , "EmailItem"
                    , "EvaluateActivity"
                    , "exportItemType"
                    , "get"
                    , "getItemAllVersions"
                    , "getAffectedItems"
                    , "GetItemConfig"
                    , "getItemLastVersion"
                    , "getItemNextStates"
                    , "getItemRelationships"
                    , "GetItemRepeatConfig"
                    , "getItemWhereUsed"
                    , "GetMappedPath"
                    , "getPermissions"
                    , "getRelatedItem"
                    , "GetUpdateInfo"
                    , "instantiateWorkflow"
                    , "lock"
                    , "merge"
                    , "New Workflow Map"
                    , "PromoteItem"
                    , "purge"
                    , "recache"
                    , "replicate"
                    , "resetAllItemsAccess"
                    , "resetItemAccess"
                    , "resetLifecycle"
                    , "setDefaultLifecycle"
                    , "skip"
                    , "startWorkflow"
                    , "unlock"
                    , "update"
                    , "ValidateWorkflowMap"
                    , "version"};

                  items = _methods == null
                    ? StringPromise(baseMethods)
                    : _methods.Convert(m => m.Concat(baseMethods));
                  break;
                case "access_type":
                  items = StringPromise("can_add", "can_delete", "can_get", "can_update");
                  break;
                case "doGetItem":
                case "version":
                case "isCriteria":
                case "related_expand":
                case "serverEvents":
                  items = StringPromise("0", "1");
                  break;
                case "queryType":
                  items = StringPromise("Effective", "Latest", "Released");
                  break;
                case "orderBy":
                  if (!string.IsNullOrEmpty(path.Last().Type)
                    && _itemTypes.TryGetValue(path.Last().Type, out itemType))
                  {
                    var lastComma = attrValue.LastIndexOf(",");
                    if (lastComma >= 0) attrValue = attrValue.Substring(lastComma + 1).Trim();

                    items = GetProperties(itemType)
                      .Convert(p => p.SelectMany(i => new string[] { i.Name, i.Name + " DESC" }));
                  }
                  multiValueAttribute = true;
                  break;
                case "select":
                  if (!string.IsNullOrEmpty(path.Last().Type)
                    && _itemTypes.TryGetValue(path.Last().Type, out itemType))
                  {
                    string partial;
                    var selectPath = SelectPath(attrValue, out partial);
                    attrValue = partial;

                    var itPromise = new Promise<ItemType>();
                    RecurseProperties(itemType, selectPath, it => itPromise.Resolve(it));

                    items = itPromise
                      .Continue(it => GetProperties(it))
                      .Convert(p => p.Select(i => i.Name));
                  }
                  multiValueAttribute = true;
                  break;
                case "type":
                  if (path.Count > 2
                    && path[path.Count - 3].LocalName == "Item"
                    && path[path.Count - 2].LocalName == "Relationships")
                  {
                    if (!string.IsNullOrEmpty(path[path.Count - 3].Type)
                      && _itemTypes.TryGetValue(path[path.Count - 3].Type, out itemType))
                    {
                      items = StringPromise(itemType.Relationships.Select(r => r.Name));
                    }
                  }
                  else
                  {
                    items = StringPromise(_itemTypes.Select(i => i.Value.Name));
                  }
                  break;
                case "where":
                  if (!string.IsNullOrEmpty(path.Last().Type)
                    && _itemTypes.TryGetValue(path.Last().Type, out itemType))
                  {
                    items = GetProperties(itemType)
                      .Convert(i => i.Select(p => "[" + itemType.Name + "].[" + p.Name + "]"));
                  }
                  multiValueAttribute = true;
                  break;
              }
            }
            else
            {
              switch (attr)
              {
                case "condition":
                  items = StringPromise("between"
                    , "eq"
                    , "ge"
                    , "gt"
                    , "in"
                    , "is not null"
                    , "is null"
                    , "is"
                    , "le"
                    , "like"
                    , "lt"
                    , "ne"
                    , "not between"
                    , "not in"
                    , "not like");
                  break;
                case "is_null":
                  items = StringPromise("0", "1");
                  break;
              }
            }

            filter = attrValue;
            break;
          default:
            if (path.Count == 1 && path.First().LocalName == "AML")
            {
              items = StringPromise("Item");
            }
            else
            {
              var j = path.Count - 1;
              while (path[j].LocalName == "and" || path[j].LocalName == "not" || path[j].LocalName == "or") j--;
              var last = path[j];
              if (last.LocalName == "Item")
              {
                var buffer = new List<string>();

                buffer.Add("Relationships");
                if (last.Action == "get")
                {
                  buffer.Add("and");
                  buffer.Add("not");
                  buffer.Add("or");
                }
                ItemType itemType;
                if (!string.IsNullOrEmpty(last.Type)
                  && _itemTypes.TryGetValue(last.Type, out itemType))
                {
                  items = GetProperties(itemType)
                      .Convert(p => p.Select(i => i.Name).Concat(buffer));
                }
                else
                {
                  items = StringPromise(buffer);
                }
              }
              else if (path.Count > 1)
              {
                var lastItem = path.LastOrDefault(n => n.LocalName == "Item");
                if (lastItem != null)
                {
                  if (path.Last().LocalName == "Relationships")
                  {
                    items = StringPromise("Item");
                  }
                  else
                  {
                    ItemType itemType;
                    if (!string.IsNullOrEmpty(lastItem.Type)
                      && _itemTypes.TryGetValue(lastItem.Type, out itemType))
                    {
                      items = GetProperty(itemType, path.Last().LocalName)
                        .Convert(p =>
                        {
                          if (p.Type == PropertyType.item && p.Restrictions.Any())
                          {
                            return p.Restrictions.Select(type => "Item type=\"" + type + "\"");
                          }
                          else
                          {
                            return Enumerable.Empty<string>();
                          }
                        });
                    }
                  }
                }
              }
            }

            break;
        }

      }

      if (items == null)
        return Promises.Resolved(new CompletionData());

      return items.Convert(i => new CompletionData() {
        Items = string.IsNullOrEmpty(filter) ? i.OrderBy(j => j) : FilterAndSort(i, filter),
        MultiValueAttribute = multiValueAttribute,
        Overlap = (filter ?? "").Length,
        State = state
      });
    }
Exemplo n.º 60
0
 public IPromise Each <T>(IPromise <IEnumerable <T> > items, Action <T> action)
 {
     return(items.Then(result => Each(result, action)));
 }