Example #1
0
 public void CreateFromTask_AsTaskIdempotent()
 {
     Task<int> source = Task.FromResult(42);
     ValueTask<int> t = new ValueTask<int>(source);
     Assert.Same(source, t.AsTask());
     Assert.Same(t.AsTask(), t.AsTask());
 }
Example #2
0
 public void CreateFromNotCompletedTask_IsNotRanToCompletion()
 {
     var tcs = new TaskCompletionSource<int>();
     ValueTask<int> t = new ValueTask<int>(tcs.Task);
     Assert.False(t.IsRanToCompletion);
     tcs.SetResult(42);
     Assert.Equal(42, t.Result);
 }
Example #3
0
 public void CreateFromCompletedTask_IsRanToCompletion()
 {
     ValueTask<int> t = new ValueTask<int>(Task.FromResult(42));
     Assert.True(t.IsCompleted);
     Assert.True(t.IsCompletedSuccessfully);
     Assert.False(t.IsFaulted);
     Assert.False(t.IsCanceled);
     Assert.Equal(42, t.Result);
 }
Example #4
0
        public void CreateFromNotCompletedTask_IsNotRanToCompletion()
        {
            var tcs = new TaskCompletionSource<int>();
            ValueTask<int> t = new ValueTask<int>(tcs.Task);

            Assert.False(t.IsCompleted);
            Assert.False(t.IsCompletedSuccessfully);
            Assert.False(t.IsFaulted);
            Assert.False(t.IsCanceled);

            tcs.SetResult(42);

            Assert.Equal(42, t.Result);
            Assert.True(t.IsCompleted);
            Assert.True(t.IsCompletedSuccessfully);
            Assert.False(t.IsFaulted);
            Assert.False(t.IsCanceled);
        }
Example #5
0
 internal ValueTaskAwaiter(ValueTask value) => _value = value;
 async ValueTask ConditionalExpression(int x, ValueTask <int> vt)
 {
     return(x > 3 ? await vt : await vt.ConfigureAwait(false));
 }
Example #7
0
 public AsyncQueryableResultEnumerator(ValueTask <IAsyncEnumerable <T> > enumerableTask, CancellationToken cancellation)
 {
     _enumerableTask = enumerableTask;
     _cancellation   = cancellation;
 }
Example #8
0
            public override async ValueTask <int> ReadAsync(Memory <byte> buffer, CancellationToken cancellationToken)
            {
                CancellationHelper.ThrowIfCancellationRequested(cancellationToken);

                if (_connection == null)
                {
                    // Response body fully consumed
                    return(0);
                }

                Debug.Assert(_contentBytesRemaining > 0);

                if ((ulong)buffer.Length > _contentBytesRemaining)
                {
                    buffer = buffer.Slice(0, (int)_contentBytesRemaining);
                }

                ValueTask <int> readTask = _connection.ReadAsync(buffer);
                int             bytesRead;

                if (readTask.IsCompletedSuccessfully)
                {
                    bytesRead = readTask.Result;
                }
                else
                {
                    CancellationTokenRegistration ctr = _connection.RegisterCancellation(cancellationToken);
                    try
                    {
                        bytesRead = await readTask.ConfigureAwait(false);
                    }
                    catch (Exception exc) when(CancellationHelper.ShouldWrapInOperationCanceledException(exc, cancellationToken))
                    {
                        throw CancellationHelper.CreateOperationCanceledException(exc, cancellationToken);
                    }
                    finally
                    {
                        ctr.Dispose();
                    }
                }

                if (bytesRead == 0 && buffer.Length != 0)
                {
                    // A cancellation request may have caused the EOF.
                    CancellationHelper.ThrowIfCancellationRequested(cancellationToken);

                    // Unexpected end of response stream.
                    throw new IOException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, _contentBytesRemaining));
                }

                Debug.Assert((ulong)bytesRead <= _contentBytesRemaining);
                _contentBytesRemaining -= (ulong)bytesRead;

                if (_contentBytesRemaining == 0)
                {
                    // End of response body
                    _connection.CompleteResponse();
                    _connection = null;
                }

                return(bytesRead);
            }
            // continue after a ReadAsync call completes
            static async ValueTask <int> ReadAsync_ContinueAfterReadAsync(PipeReaderAdapter self, ValueTask <ReadResult> waitFor, Memory <char> into, CancellationToken cancellationToken)
            {
tryAgainAsync:
                var res = await ConfigureCancellableAwait(self, waitFor, cancellationToken);

                var handled = self.MapByteSequenceToChar(res, into);

                // we need to wait for more to happen, returning 0 will
                //    incorrectly signal that the writer has finished
                if (handled == 0 && !self.IsComplete)
                {
                    waitFor = self.Inner.ReadAsync(cancellationToken);
                    goto tryAgainAsync;
                }

                return(handled);
            }
Example #10
0
 public void CreateFromCompletedTask_IsRanToCompletion()
 {
     ValueTask<int> t = new ValueTask<int>(Task.FromResult(42));
     Assert.True(t.IsRanToCompletion);
     Assert.Equal(42, t.Result);
 }
Example #11
0
        /// <summary>
        /// Async operations on FasterKV
        /// </summary>
        static async Task AsyncOperator(int id)
        {
            using var session = faster.For(new CacheFunctions()).NewSession <CacheFunctions>(id.ToString());
            Random rand = new Random(id);

            bool batched       = true;  // whether we batch upserts on session
            bool asyncUpsert   = false; // whether we use sync or async upsert calls
            bool waitForCommit = false; // whether we wait for commit after each operation (or batch) on this session
            int  batchSize     = 100;   // batch size

            await Task.Yield();

            var  context   = new CacheContext();
            var  taskBatch = new ValueTask <FasterKV <CacheKey, CacheValue> .UpsertAsyncResult <CacheInput, CacheOutput, CacheContext> > [batchSize];
            long seqNo     = 0;

            if (!batched)
            {
                // Single upsert at a time, optionally waiting for commit
                // Needs high parallelism (NumParallelTasks) for perf
                // Separate commit thread performs regular checkpoints
                while (true)
                {
                    try
                    {
                        var key   = new CacheKey(rand.Next());
                        var value = new CacheValue(rand.Next());
                        if (asyncUpsert)
                        {
                            var r = await session.UpsertAsync(ref key, ref value, context, seqNo ++);

                            while (r.Status == Status.PENDING)
                            {
                                r = await r.CompleteAsync();
                            }
                        }
                        else
                        {
                            session.Upsert(ref key, ref value, context, seqNo++);
                        }
                        if (waitForCommit)
                        {
                            await session.WaitForCommitAsync();
                        }
                        Interlocked.Increment(ref numOps);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"{nameof(AsyncOperator)}({id}): {ex}");
                    }
                }
            }
            else
            {
                // Batched version - we enqueue many entries to memory,
                // then wait for commit periodically
                int count = 0;

                while (true)
                {
                    var key   = new CacheKey(rand.Next());
                    var value = new CacheValue(rand.Next());
                    if (asyncUpsert)
                    {
                        taskBatch[count % batchSize] = session.UpsertAsync(ref key, ref value, context, seqNo++);
                    }
                    else
                    {
                        session.Upsert(ref key, ref value, context, seqNo++);
                    }
                    if (count++ % batchSize == 0)
                    {
                        if (asyncUpsert)
                        {
                            for (int i = 0; i < batchSize; i++)
                            {
                                var r = await taskBatch[i];
                                while (r.Status == Status.PENDING)
                                {
                                    r = await r.CompleteAsync();
                                }
                            }
                        }
                        if (waitForCommit)
                        {
                            await session.WaitForCommitAsync();
                        }
                        Interlocked.Add(ref numOps, batchSize);
                    }
                }
            }
        }
Example #12
0
 public SimpleMockTokenCredential(string scope, string token)
 {
     _scope     = scope;
     _token     = token;
     _tokenTask = new ValueTask <string>(token);
 }
Example #13
0
 public void CreateFromValue_AsTaskNotIdempotent()
 {
     ValueTask<int> t = new ValueTask<int>(42);
     Assert.NotSame(Task.FromResult(42), t.AsTask());
     Assert.NotSame(t.AsTask(), t.AsTask());
 }
Example #14
0
 public void GetHashCode_ContainsNull()
 {
     ValueTask<string> t = new ValueTask<string>((string)null);
     Assert.Equal(0, t.GetHashCode());
 }
Example #15
0
 public void GetHashCode_ContainsTask()
 {
     ValueTask<string> t = new ValueTask<string>(Task.FromResult("42"));
     Assert.Equal(t.AsTask().GetHashCode(), t.GetHashCode());
 }
Example #16
0
 public void GetHashCode_ContainsResult()
 {
     ValueTask<int> t = new ValueTask<int>(42);
     Assert.Equal(t.Result.GetHashCode(), t.GetHashCode());
 }
Example #17
0
 public async Task ConfiguredAwaiter_ContinuesOnCapturedContext(bool continueOnCapturedContext)
 {
     await Task.Run(() =>
     {
         var tsc = new TrackingSynchronizationContext();
         SynchronizationContext.SetSynchronizationContext(tsc);
         try
         {
             ValueTask<int> t = new ValueTask<int>(42);
             var mres = new ManualResetEventSlim();
             t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => mres.Set());
             Assert.True(mres.Wait(10000));
             Assert.Equal(continueOnCapturedContext ? 1 : 0, tsc.Posts);
         }
         finally
         {
             SynchronizationContext.SetSynchronizationContext(null);
         }
     });
 }
Example #18
0
        public async Task ConfiguredAwaiter_OnCompleted(bool continueOnCapturedContext)
        {
            // Since ValueTask implements both OnCompleted and UnsafeOnCompleted,
            // OnCompleted typically won't be used by await, so we add an explicit test
            // for it here.

            ValueTask<int> t = new ValueTask<int>(42);
            var tcs = new TaskCompletionSource<bool>();
            t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => tcs.SetResult(true));
            await tcs.Task;
        }
        public static ValueTask <int> MudAddEventListenerAsync <T>(this ElementReference elementReference, DotNetObjectReference <T> dotnet, string @event, string callback, bool stopPropagation = false) where T : class
        {
            var parameters = dotnet?.Value.GetType().GetMethods().First(m => m.Name == callback).GetParameters().Select(p => p.ParameterType);

            if (parameters != null)
            {
                var parameterSpecs = new object[parameters.Count()];
                for (int i = 0; i < parameters.Count(); ++i)
                {
                    parameterSpecs[i] = GetSerializationSpec(parameters.ElementAt(i));
                }
                return(elementReference.GetJSRuntime()?.InvokeAsync <int>("mudElementRef.addEventListener", elementReference, dotnet, @event, callback, parameterSpecs, stopPropagation) ?? ValueTask.FromResult(0));
            }
            else
            {
                return(new ValueTask <int>(0));
            }
        }
        private static async Task <T> WriteDirectAsync_Awaited <T>(ServerEndPoint @this, Message message, ValueTask <WriteResult> write, TaskCompletionSource <T> tcs)
        {
            var result = await write.ForAwait();

            if (result != WriteResult.Success)
            {
                var ex = @this.Multiplexer.GetException(result, message, @this);
                ConnectionMultiplexer.ThrowFailed(tcs, ex);
            }
            return(await tcs.Task.ForAwait());
        }
Example #21
0
 public async Task CreateFromTask_Await_Normal()
 {
     Task<int> source = Task.Delay(1).ContinueWith(_ => 42);
     ValueTask<int> t = new ValueTask<int>(source);
     Assert.Equal(42, await t);
 }
Example #22
0
    public async Task TtlExpiredScenarioAsync()
    {
        using CancellationTokenSource timeoutCts = new(TimeoutLimit);
        CancellationToken timeoutToken = timeoutCts.Token;

        Uri    uri             = new("http://postman-echo.com");
        string httpRequestHost = uri.Host;
        int    httpRequestPort = 80;

        TcpListener?listener = null;

        try
        {
            // Start local TCP server.
            listener = new(IPAddress.Loopback, port : 0);
            listener.Start();
            int serverPort = ((IPEndPoint)listener.LocalEndpoint).Port;

            Logger.LogTrace($"[{nameof(TtlExpiredScenarioAsync)}][server] Wait for TCP client on port {serverPort}.");
            ValueTask <TcpClient> acceptTask = listener.AcceptTcpClientAsync(timeoutToken);

            Task clientTask = Task.Run(
                async() =>
            {
                TorTcpConnectionFactory factory = new(new IPEndPoint(IPAddress.Loopback, serverPort));

                Logger.LogTrace($"[{nameof(TtlExpiredScenarioAsync)}][client] About to make connection.");
                using TorTcpConnection torConnection = await factory.ConnectAsync(httpRequestHost, httpRequestPort, useSsl: false, DefaultCircuit.Instance, timeoutToken);
                Logger.LogTrace($"[{nameof(TtlExpiredScenarioAsync)}][client] Connection established.");
            },
                timeoutToken);

            using TcpClient client = await acceptTask;

            Logger.LogTrace($"[{nameof(TtlExpiredScenarioAsync)}][server] Connected!");
            using NetworkStream stream = client.GetStream();
            stream.ReadTimeout         = (int)TimeoutLimit.TotalMilliseconds;

            // <Version method request>
            // Read SOCKS protocol version.
            int versionByte = stream.ReadByte();
            Assert.Equal(VerField.Socks5.Value, versionByte);

            // Read "NMethods" version.
            int nmethodsByte = stream.ReadByte();
            Assert.Equal(1, nmethodsByte);

            // Read method byte.
            int methodByte = stream.ReadByte();
            Assert.Equal(MethodField.UsernamePassword.ToByte(), methodByte);

            // Write response: version + method selected.
            stream.WriteByte(VerField.Socks5.Value);
            stream.WriteByte(MethodField.UsernamePassword.ToByte());
            stream.Flush();

            // </Version method request>

            // <UsernamePasswordRequest>
            // Read "AuthVerField" byte.
            int authVerByte = stream.ReadByte();
            Assert.Equal(AuthVerField.Version1.Value, authVerByte);

            int ulenByte = stream.ReadByte();
            Assert.Equal(21, ulenByte);

            // Read "UName".
            for (int j = 0; j < 21; j++)
            {
                _ = stream.ReadByte();
            }

            int plenByte = stream.ReadByte();
            Assert.Equal(21, plenByte);

            // Read "Passwd".
            for (int j = 0; j < 21; j++)
            {
                _ = stream.ReadByte();
            }

            // Write response (UsernamePasswordResponse): version + method selected.
            stream.WriteByte((byte)AuthVerField.Version1.Value);
            stream.WriteByte(AuthStatusField.Success.ToByte());
            stream.Flush();

            // </UsernamePasswordRequest>

            TorSocks5Request expectedConnectionRequest = new(cmd : CmdField.Connect, new(httpRequestHost), new(httpRequestPort));

            int i = 0;
            foreach (byte byteValue in expectedConnectionRequest.ToBytes())
            {
                i++;
                Logger.LogTrace($"[{nameof(TtlExpiredScenarioAsync)}][server] Reading request byte #{i}.");
                int readByte = stream.ReadByte();
                Assert.Equal(byteValue, readByte);
            }

            // Tor SOCKS5 reply reporting TTL expired error.
            // Note: RepField.Succeeded is the only OK code.
            // https://tools.ietf.org/html/rfc1928: See "6. Replies"
            byte[] torSocks5Response = new byte[]
            {
                VerField.Socks5.Value,
                RepField.TtlExpired.ToByte(),
                RsvField.X00.ToByte(),
                AtypField.DomainName.ToByte(),
                0x04, 0x00, 0x00, 0x00, 0x00,      // BndAddr (ATYP = "Domain" therefore the first octet is length of "BND.ADDR")
                0x00, 0x00                         // BndPort
            };

            Logger.LogTrace($"[{nameof(TtlExpiredScenarioAsync)}][server] Respond with RepField.TtlExpired result.");
            await stream.WriteAsync(torSocks5Response, timeoutToken);

            stream.Flush();

            Logger.LogTrace($"[{nameof(TtlExpiredScenarioAsync)}][server] Expecting exception.");
            await Assert.ThrowsAsync <TorConnectCommandFailedException>(async() => await clientTask.WithAwaitCancellationAsync(timeoutToken));
        }
        finally
        {
            listener?.Stop();
        }
    }
Example #23
0
 public void CreateFromValue_IsRanToCompletion()
 {
     ValueTask<int> t = new ValueTask<int>(42);
     Assert.True(t.IsRanToCompletion);
     Assert.Equal(42, t.Result);
 }
Example #24
0
    public async Task AuthenticationErrorScenarioAsync()
    {
        using CancellationTokenSource timeoutCts = new(TimeoutLimit);
        CancellationToken timeoutToken = timeoutCts.Token;

        // No request is sent to the URI.
        Uri    uri             = new("http://postman-echo.com");
        string httpRequestHost = uri.Host;
        int    httpRequestPort = 80;

        TcpListener?listener = null;

        try
        {
            // Start local TCP server.
            listener = new(IPAddress.Loopback, port : 0);
            listener.Start();
            int serverPort = ((IPEndPoint)listener.LocalEndpoint).Port;

            Logger.LogTrace($"[{nameof(AuthenticationErrorScenarioAsync)}][server] Waiting for a TCP client on port {serverPort}.");
            ValueTask <TcpClient> acceptTask = listener.AcceptTcpClientAsync(timeoutToken);

            Task clientTask = Task.Run(
                async() =>
            {
                TorTcpConnectionFactory factory = new(new IPEndPoint(IPAddress.Loopback, serverPort));

                Logger.LogTrace($"[{nameof(AuthenticationErrorScenarioAsync)}][client] About to make connection.");
                using TorTcpConnection torConnection = await factory.ConnectAsync(httpRequestHost, httpRequestPort, useSsl: false, DefaultCircuit.Instance, timeoutToken).ConfigureAwait(false);
                Logger.LogTrace($"[{nameof(AuthenticationErrorScenarioAsync)}][client] Connection established.");
            },
                timeoutToken);

            using TcpClient client = await acceptTask;

            Logger.LogTrace($"[{nameof(AuthenticationErrorScenarioAsync)}][server] Connected!");
            using NetworkStream stream = client.GetStream();
            stream.ReadTimeout         = (int)TimeoutLimit.TotalMilliseconds;

            // Read SOCKS protocol version.
            int versionByte = stream.ReadByte();
            Assert.Equal(VerField.Socks5.Value, versionByte);

            // Read "NMethods" version.
            int nmethodsByte = stream.ReadByte();
            Assert.Equal(1, nmethodsByte);

            // Read SOCKS version.
            int methodByte = stream.ReadByte();
            Assert.Equal(MethodField.UsernamePassword.ToByte(), methodByte);

            // Write response: version + method selected.
            stream.WriteByte(VerField.Socks5.Value);
            stream.WriteByte(MethodField.NoAcceptableMethods.ToByte());
            stream.Flush();

            Logger.LogTrace($"[{nameof(AuthenticationErrorScenarioAsync)}][server] Expecting exception.");
            await Assert.ThrowsAsync <NotSupportedException>(async() => await clientTask.WithAwaitCancellationAsync(timeoutToken).ConfigureAwait(false));
        }
        finally
        {
            listener?.Stop();
        }
    }
 public ValueTask <ConnectionContext> ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken = default)
 {
     ConnectTask = _innerFactory.ConnectAsync(endPoint, cancellationToken);
     return(ConnectTask);
 }
Example #26
0
 internal static ValueTask Await <T>(this ValueTask <T> pending)
 {
     if (pending.IsCompletedSuccessfully)
     {
         _ = pending.Result; // for IValueTaskSource reasons
         return(default);
        public bool Draw()
        {
            ImGui.SetNextWindowSize(new Vector2(500, 500), ImGuiCond.FirstUseEver);

            var isOpen = true;

            if (!ImGui.Begin(Loc.Localize("DalamudItemSelectHeader", "Select an item"), ref isOpen, ImGuiWindowFlags.NoCollapse))
            {
                ImGui.End();
                return(false);
            }

            // Main window
            ImGui.AlignTextToFramePadding();

            ImGui.Text(Loc.Localize("DalamudItemSelect", "Please select an item."));
            if (this.selectedItemTex != null)
            {
                ImGui.Text(" ");

                ImGui.SetCursorPosY(200f);
                ImGui.SameLine();
                ImGui.Image(this.selectedItemTex.ImGuiHandle, new Vector2(40, 40));
            }
            else
            {
                ImGui.Text(" ");
            }

            ImGui.Separator();


            ImGui.Text(Loc.Localize("DalamudItemSearchVerb", "Search: "));
            ImGui.SameLine();
            ImGui.InputText("##searchbox", ref this.searchText, 32);

            var kinds = new List <string> {
                Loc.Localize("DalamudItemSelectAll", "All")
            };

            kinds.AddRange(this.data.GetExcelSheet <ItemUICategory>().GetRows().Where(x => !string.IsNullOrEmpty(x.Name)).Select(x => x.Name.Replace("\u0002\u001F\u0001\u0003", "-")));

            ImGui.Text(Loc.Localize("DalamudItemSelectCategory", "Category: "));
            ImGui.SameLine();
            ImGui.Combo("##kindbox", ref this.currentKind, kinds.ToArray(),
                        kinds.Count);


            var windowSize = ImGui.GetWindowSize();

            ImGui.BeginChild("scrolling", new Vector2(0, windowSize.Y - ImGui.GetCursorPosY() - 40), true, ImGuiWindowFlags.HorizontalScrollbar);

            ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));

            if (this.luminaItems != null)
            {
                if (!string.IsNullOrEmpty(this.searchText) || this.currentKind != 0)
                {
                    if (this.lastSearchText != this.searchText || this.lastKind != this.currentKind)
                    {
                        this.lastSearchText = this.searchText;
                        this.lastKind       = this.currentKind;

                        this.searchCancelTokenSource?.Cancel();

                        this.searchCancelTokenSource = new CancellationTokenSource();

                        var asyncEnum = this.luminaItems.ToAsyncEnumerable();

                        if (!string.IsNullOrEmpty(this.searchText))
                        {
                            Log.Debug("Searching for " + this.searchText);
                            asyncEnum = asyncEnum.Where(
                                x => (x.Name.ToLower().Contains(this.searchText.ToLower()) ||
                                      int.TryParse(this.searchText, out var parsedId) &&
                                      parsedId == x.RowId) && x.Icon < 65000);
                        }

                        if (this.currentKind != 0)
                        {
                            Log.Debug("Searching for C" + this.currentKind);
                            asyncEnum = asyncEnum.Where(x => x.ItemUICategory == this.currentKind);
                        }

                        this.selectedItemIndex = -1;
                        this.selectedItemTex?.Dispose();
                        this.selectedItemTex = null;

                        this.searchTask = asyncEnum.ToListAsync(this.searchCancelTokenSource.Token);
                    }

                    if (this.searchTask.IsCompletedSuccessfully)
                    {
                        for (var i = 0; i < this.searchTask.Result.Count; i++)
                        {
                            if (ImGui.Selectable(this.searchTask.Result[i].Name, this.selectedItemIndex == i, ImGuiSelectableFlags.AllowDoubleClick))
                            {
                                this.selectedItemIndex = i;

                                try
                                {
                                    var iconTex = this.data.GetIcon(this.searchTask.Result[i].Icon);
                                    this.selectedItemTex?.Dispose();

                                    this.selectedItemTex =
                                        this.builder.LoadImageRaw(iconTex.GetRgbaImageData(), iconTex.Header.Width,
                                                                  iconTex.Header.Height, 4);
                                } catch (Exception ex)
                                {
                                    Log.Error(ex, "Failed loading item texture");
                                    this.selectedItemTex?.Dispose();
                                    this.selectedItemTex = null;
                                }

                                if (ImGui.IsMouseDoubleClicked(0))
                                {
                                    if (this.selectedItemTex != null)
                                    {
                                        OnItemChosen?.Invoke(this, this.searchTask.Result[i]);
                                        if (this.closeOnChoose)
                                        {
                                            this.selectedItemTex?.Dispose();
                                            isOpen = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    ImGui.TextColored(new Vector4(0.86f, 0.86f, 0.86f, 1.00f), Loc.Localize("DalamudItemSelectHint", "Type to start searching..."));

                    this.selectedItemIndex = -1;
                    this.selectedItemTex?.Dispose();
                    this.selectedItemTex = null;
                }
            }
            else
            {
                ImGui.TextColored(new Vector4(0.86f, 0.86f, 0.86f, 1.00f), Loc.Localize("DalamudItemSelectLoading", "Loading item list..."));
            }

            ImGui.PopStyleVar();

            ImGui.EndChild();

            // Darken choose button if it shouldn't be clickable
            ImGui.PushStyleVar(ImGuiStyleVar.Alpha, this.selectedItemIndex < 0 || this.selectedItemTex == null ? 0.25f : 1);

            if (ImGui.Button(Loc.Localize("Choose", "Choose")))
            {
                try {
                    if (this.selectedItemTex != null)
                    {
                        OnItemChosen?.Invoke(this, this.searchTask.Result[this.selectedItemIndex]);
                        if (this.closeOnChoose)
                        {
                            this.selectedItemTex?.Dispose();
                            isOpen = false;
                        }
                    }
                } catch (Exception ex) {
                    Log.Error($"Exception in Choose: {ex.Message}");
                }
            }

            ImGui.PopStyleVar();

            if (!this.closeOnChoose)
            {
                ImGui.SameLine();
                if (ImGui.Button(Loc.Localize("Close", "Close")))
                {
                    this.selectedItemTex?.Dispose();
                    isOpen = false;
                }
            }

            if (this.selectedItemIndex >= 0 && this.selectedItemTex == null)
            {
                ImGui.SameLine();
                ImGui.Text(Loc.Localize("DalamudItemNotLinkable", "This item is not linkable."));
            }

            ImGui.End();

            return(isOpen);
        }
Example #28
0
        public virtual ValueTask <IEnumerable <ActivityDisplayDescriptor> > GetDescriptorsAsync(CancellationToken cancellationToken = default)
        {
            var descriptors = GetDescriptors();

            return(ValueTask.FromResult(descriptors));
        }
 async ValueTask CallingAsTask(ValueTask vt)
 {
     await vt.AsTask();
 }
        public override ValueTask <RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
        {
            if (MixService.GetAppSetting <bool>(MixAppSettingKeywords.IsInit))
            {
                return(ValueTask.FromResult(values));
            }

            RouteValueDictionary result = values;

            var keys = values.Keys.ToList();

            var language = (string)values[keys[0]];
            var keyIndex = 1;

            if (!MixService.Instance.CheckValidCulture(language))
            {
                language  = MixService.GetAppSetting <string>(MixAppSettingKeywords.DefaultCulture);
                keyIndex -= 1;
            }

            var path = string.Join('/', values.Values.Skip(keyIndex));

            if (MixService.Instance.CheckValidAlias(language, path))
            {
                result["controller"] = "home";
                result["culture"]    = language;
                result["action"]     = "Index";
                result["seoName"]    = path;
                return(ValueTask.FromResult(result));
            }


            string notTransformPattern = @"^(.*)\.(xml|json|html|css|js|map|jpg|png|gif|jpeg|svg|map|ico|webmanifest|woff|woff2|ttf|eot)$";
            Regex  reg = new Regex(notTransformPattern);

            if (reg.IsMatch(httpContext.Request.Path.Value))
            {
                return(ValueTask.FromResult(values));
            }

            var currentController = GetRouteValue(values, keys, ref keyIndex);
            var controller        = MixService.Translate(currentController, language, currentController);

            if (!IsValidController(controller))
            {
                controller           = "home";
                keyIndex            -= 1;
                result["keyword"]    = keyIndex < keys.Count ? string.Join('/', values.Values.Skip(keyIndex + 1)) : string.Empty;
                result["seoName"]    = keys.Count > keyIndex ? (string)values[keys[keyIndex]] : string.Empty;
                result["culture"]    = language;
                result["action"]     = "Index";
                result["controller"] = controller;
            }
            else
            {
                if (keys.Count > 2)
                {
                    result["id"] = GetRouteValue(values, keys, ref keyIndex);
                }
                result["controller"] = controller;
                result["keyword"]    = GetRouteValue(values, keys, ref keyIndex);
            }
            result["action"] = "Index";

            return(ValueTask.FromResult(result));
        }
Example #31
0
 static async ValueTask <Packet> AddContinuation(ValueTask <ArraySegment <byte> > headerBytes, BufferedByteReader bufferedByteReader, IByteHandler byteHandler, Func <int> getNextSequenceNumber, ProtocolErrorBehavior protocolErrorBehavior, IOBehavior ioBehavior) =>
 await ReadPacketAfterHeader(await headerBytes.ConfigureAwait(false), bufferedByteReader, byteHandler, getNextSequenceNumber, protocolErrorBehavior, ioBehavior).ConfigureAwait(false);
Example #32
0
        public async Task GetUserInfoAsync(
            [Summary("The user to retrieve information about, if any.")]
            [Remainder] DiscordUserOrMessageAuthorEntity user = null)
        {
            var userId = user?.UserId ?? Context.User.Id;

            var timer = Stopwatch.StartNew();

            var userInfo = await _userService.GetUserInformationAsync(Context.Guild.Id, userId);

            if (userInfo == null)
            {
                var embed = new EmbedBuilder()
                            .WithTitle("Retrieval Error")
                            .WithColor(Color.Red)
                            .WithDescription("Sorry, we don't have any data for that user - and we couldn't find any, either.")
                            .AddField("User Id", userId);
                await _autoRemoveMessageService.RegisterRemovableMessageAsync(
                    Context.User,
                    embed,
                    async (embedBuilder) => await ReplyAsync(embed: embedBuilder.Build()));

                return;
            }

            var builder = new StringBuilder();

            builder.AppendLine("**\u276F User Information**");
            builder.AppendLine("ID: " + userId);
            builder.AppendLine("Profile: " + MentionUtils.MentionUser(userId));

            var embedBuilder = new EmbedBuilder()
                               .WithUserAsAuthor(userInfo)
                               .WithTimestamp(_utcNow);

            var avatar = userInfo.GetDefiniteAvatarUrl();

            embedBuilder.ThumbnailUrl   = avatar;
            embedBuilder.Author.IconUrl = avatar;

            ValueTask <Color> colorTask = default;

            if ((userInfo.GetAvatarUrl(size: 16) ?? userInfo.GetDefaultAvatarUrl()) is { } avatarUrl)
            {
                colorTask = _imageService.GetDominantColorAsync(new Uri(avatarUrl));
            }

            var moderationRead = await _authorizationService.HasClaimsAsync(Context.User as IGuildUser, AuthorizationClaim.ModerationRead);

            var promotions = await _promotionsService.GetPromotionsForUserAsync(Context.Guild.Id, userId);

            if (userInfo.IsBanned)
            {
                builder.AppendLine("Status: **Banned** \\🔨");

                if (moderationRead)
                {
                    builder.AppendLine($"Ban Reason: {userInfo.BanReason}");
                }
            }
            else
            {
                builder.AppendLine($"Status: {userInfo.Status.Humanize()}");
            }

            if (userInfo.FirstSeen is DateTimeOffset firstSeen)
            {
                builder.AppendLine($"First Seen: {FormatUtilities.FormatTimeAgo(_utcNow, firstSeen)}");
            }

            if (userInfo.LastSeen is DateTimeOffset lastSeen)
            {
                builder.AppendLine($"Last Seen: {FormatUtilities.FormatTimeAgo(_utcNow, lastSeen)}");
            }

            try
            {
                var userRank = await _messageRepository.GetGuildUserParticipationStatistics(Context.Guild.Id, userId);

                var messagesByDate = await _messageRepository.GetGuildUserMessageCountByDate(Context.Guild.Id, userId, TimeSpan.FromDays(30));

                var messageCountsByChannel = await _messageRepository.GetGuildUserMessageCountByChannel(Context.Guild.Id, userId, TimeSpan.FromDays(30));

                var emojiCounts = await _emojiRepository.GetEmojiStatsAsync(Context.Guild.Id, SortDirection.Ascending, 1, userId : userId);

                await AddParticipationToEmbedAsync(userId, builder, userRank, messagesByDate, messageCountsByChannel, emojiCounts);
            }
            catch (Exception ex)
            {
                _log.LogError(ex, "An error occured while retrieving a user's message count.");
            }

            AddMemberInformationToEmbed(userInfo, builder);
            AddPromotionsToEmbed(builder, promotions);

            if (moderationRead)
            {
                await AddInfractionsToEmbedAsync(userId, builder);
            }

            embedBuilder.Description = builder.ToString();

            embedBuilder.WithColor(await colorTask);

            timer.Stop();
            embedBuilder.WithFooter(footer => footer.Text = $"Completed after {timer.ElapsedMilliseconds} ms");

            await _autoRemoveMessageService.RegisterRemovableMessageAsync(
                userInfo.Id == Context.User.Id?new[] { userInfo } : new[] { userInfo, Context.User },
                embedBuilder,
                async (embedBuilder) => await ReplyAsync(embed: embedBuilder.Build()));
        }
Example #33
0
 internal ValueTaskAwaiter(ValueTask <TResult> value) => _value = value;
Example #34
0
 /// <summary>
 /// Make a task execute synchronously
 /// </summary>
 /// <param name="task">Task</param>
 public static void Sync(this ValueTask task)
 {
     task.ConfigureAwait(false).GetAwaiter().GetResult();
 }
 private (LendingData, ValueTask <Unit>) Match(ValueTask <Unit> disposedTask, LendingData data, CancellationToken _3, CancellationToken _4)
 {
     return(data, disposedTask);
 }
Example #36
0
 /// <summary>
 /// Make a task execute synchronously
 /// </summary>
 /// <param name="task">Task</param>
 /// <returns>Result</returns>
 public static T Sync <T>(this ValueTask <T> task)
 {
     return(task.ConfigureAwait(false).GetAwaiter().GetResult());
 }
 public static ValueTask <BoundingClientRect> MudGetBoundingClientRectAsync(this ElementReference elementReference) =>
 elementReference.GetJSRuntime()?.InvokeAsync <BoundingClientRect>("mudElementRef.getBoundingClientRect", elementReference) ?? ValueTask.FromResult(new BoundingClientRect());
Example #38
0
 internal ConfiguredValueTaskAwaiter(ValueTask value)
 {
     this._value = value;
 }
Example #39
0
 private static Task AwaitAndDispose(ValueTask task, IDisposable scope) => AwaitAndDispose(task.AsTask(), scope);
 internal ValueTaskCompletionSource5(ValueTask first, ValueTask second, ValueTask third, ValueTask fourth, ValueTask fifth)
     : base(first, second, third, fourth)
 {
     this.fifth = fifth;
 }
Example #41
0
 public async Task CreateFromValue_Await()
 {
     ValueTask<int> t = new ValueTask<int>(42);
     Assert.Equal(42, await t);
     Assert.Equal(42, await t.ConfigureAwait(false));
     Assert.Equal(42, await t.ConfigureAwait(true));
 }
 internal ValueTaskCompletionSource2(ValueTask <TResult> first, ValueTask <TResult> second)
 {
     this.first  = first;
     this.second = second;
 }
Example #43
0
 public async Task CreateFromTask_Await_ConfigureAwaitTrue()
 {
     Task<int> source = Task.Delay(1).ContinueWith(_ => 42);
     ValueTask<int> t = new ValueTask<int>(source);
     Assert.Equal(42, await t.ConfigureAwait(true));
 }
 internal ValueTaskCompletionSource3(ValueTask first, ValueTask second, ValueTask third)
     : base(first, second)
 {
     this.third = third;
 }
 public ValueTask <string> LoadAsync(TemplateContext context, SourceSpan callerSpan, string templatePath)
 => ValueTask.FromResult(Load(context, callerSpan, templatePath));
Example #46
0
        public void ConfiguredAwaiter_OnCompleted(bool continueOnCapturedContext)
        {
            // Since ValueTask implements both OnCompleted and UnsafeOnCompleted,
            // OnCompleted typically won't be used by await, so we add an explicit test
            // for it here.

            ValueTask<int> t = new ValueTask<int>(42);
            var mres = new ManualResetEventSlim();
            t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => mres.Set());
            Assert.True(mres.Wait(10000));
        }