Exemplo n.º 1
0
 /// <summary>
 /// Execute a command directly sending a json string
 /// </summary>
 /// <param name="command"></param>
 /// <param name="storeName"></param>
 /// <param name="data"></param>
 /// <exception cref="ResponseException"></exception>
 /// <returns></returns>
 public async ValueTask <List <ResponseJsDb> > DbCommand(DbCommands command, string storeName, string data)
 {
     if (Settings.EnableDebug)
     {
         Console.WriteLine($"{command} store = {storeName}, data = {data}");
     }
     if (string.IsNullOrEmpty(storeName))
     {
         throw new ResponseException(command.ToString(), "StoreName can't be null", data);
     }
     else if (string.IsNullOrEmpty(data))
     {
         throw new ResponseException(command.ToString(), storeName, "Data can't be null");
     }
     else
     {
         try
         {
             return(await jsRuntime.InvokeAsync <List <ResponseJsDb> >($"MyDb.{command}", storeName, data, Setup.DBName, Setup.Version, Setup.ModelsAsJson));
         }
         catch (Exception ex)
         {
             if (Settings.EnableDebug)
             {
                 Console.WriteLine($"Exception: {ex.Message}");
             }
             throw new ResponseException(command.ToString(), storeName, data, ex);
         }
     }
 }
        private async Task SetVisibleValue(TItem value)
        {
            if (string.IsNullOrEmpty(Format))
            {
                VisibleValue = value.ToString();
            }
            else
            {
                VisibleValue = Convert.ToDecimal(value).ToString(Format);
            }

            var additionalFormatting = string.Empty;

            if (ConditionalFormatting != null)
            {
                additionalFormatting = ConditionalFormatting(value);
            }

            ActiveClass = ComputeClass(additionalFormatting);

            var currentValue = await JsModule.InvokeAsync <string>("GetNumericTextBoxValue", new string[] { "#" + Id });

            if (currentValue != VisibleValue)
            {
                await JsModule.InvokeVoidAsync("SetNumericTextBoxValue", new string[] { "#" + Id, VisibleValue });
            }
        }
Exemplo n.º 3
0
        public async Task <PageSize> GetPageSizeAsync()
        {
            await CheckJsObjectAsync();

            var size = await _resizeJs.InvokeAsync <PageSize>("getPageSize");

            return(size);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Remove First Item from the data set by calling Array.shift() on the data
        /// </summary>
        /// <param name="dataSetIndex"></param>
        /// <param name="data"></param>
        /// <param name="labels"></param>
        /// <returns></returns>
        public async ValueTask <JToken> ShiftData(int dataSetIndex)
        {
            this.ThrowIfChartNotInitialized();

            var json = await _ChartJSInstance.InvokeAsync <string>("shiftData", dataSetIndex);

            return(JToken.Parse(json));
        }
        public async Task InitializeAsync()
        {
            var statusCode = await response.InvokeAsync <int>("GetStatusCode", cancellationToken);

            StatusCode = (HttpStatusCode)statusCode;
            var responseText = await response.InvokeAsync <string>("GetResponseText", cancellationToken);

            Content      = new StringContent(responseText);
            ReasonPhrase = await response.InvokeAsync <string>("GetStatusText", cancellationToken);
        }
Exemplo n.º 6
0
 public async Task <string> GetJWTAsync()
 {
     try
     {
         return(await jsModule.InvokeAsync <string>("LzAuth.getIdToken"));
     } catch (JSException e)
     {
         return(string.Empty);
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// Get all resister from a table
        /// </summary>
        /// <typeparam name="TModel">Table or store to use</typeparam>
        /// <exception cref="ResponseException"></exception>
        /// <returns></returns>
        public async ValueTask <List <TModel> > DbSelect <TModel>()
        {
            List <TModel> data;

            if (Setup.Initialized)
            {
                try
                {
                    data = await jsRuntime.InvokeAsync <List <TModel> >("MyDb.Select", Setup.Tables.GetTable <TModel>(), Setup.DBName, Setup.Version, Setup.ModelsAsJson);
                }
                catch (Exception ex)
                {
                    throw new ResponseException(nameof(DbSelect), Setup.Tables.GetTable <TModel>(), ex.Message, ex);
                }
            }
            else
            {
                if (Settings.EnableDebug)
                {
                    Console.WriteLine($"SelectActions: IndexedDb not initialized yet!");
                }
                data = new List <TModel>();
            }
            return(data);
        }
Exemplo n.º 8
0
 /// <summary>
 /// Delete one row from a table
 /// </summary>
 /// <typeparam name="TModel">Table or store to use</typeparam>
 /// <param name="id"></param>
 /// <exception cref="ResponseException"></exception>
 /// <returns></returns>
 public async ValueTask <ResponseJsDb> DbDelete <TModel>([NotNull] int id)
 {
     try
     {
         List <ResponseJsDb> result = new List <ResponseJsDb>();
         if (Setup.Initialized)
         {
             result.AddRange(await jsRuntime.InvokeAsync <List <ResponseJsDb> >($"MyDb.Delete", Setup.Tables.GetTable <TModel>(), id, Setup.DBName, Setup.Version, Setup.ModelsAsJson));
         }
         else
         {
             if (Settings.EnableDebug)
             {
                 Console.WriteLine($"DeleteActions: IndexedDb not initialized yet!");
             }
             result = new List <ResponseJsDb>();
             result.Add(new ResponseJsDb {
                 Result = false, Message = $"IndexedDb not initialized yet!"
             });
         }
         if (result.Count > 0)
         {
             return(result[0]);
         }
         else
         {
             return new ResponseJsDb {
                        Result = false, Message = "No results"
             }
         };
     }
     catch (ResponseException ex)
     {
         if (Settings.EnableDebug)
         {
             Console.WriteLine($"DbDelete Model: {Setup.Tables.GetTable<TModel>()} Error: {ex}");
         }
         throw;
     }
     catch (Exception ex)
     {
         if (Settings.EnableDebug)
         {
             Console.WriteLine($"DbDelete Model: {Setup.Tables.GetTable<TModel>()} Error: {ex}");
         }
         throw new ResponseException(nameof(DbDelete), typeof(TModel).Name, ex.Message, ex);
     }
 }
Exemplo n.º 9
0
        private async Task <T> ImportSymmetricKeyAsync <T>(
            byte[] key,
            string algorithmName,
            Func <SafeCryptoKeyHandle, string, T> ctor)
        {
            bool?result;
            IJSObjectReference module = await GetModule();

            string keyId;

            do
            {
                keyId  = Guid.NewGuid().ToString("N");
                result = await module.InvokeAsync <bool?>(
                    "importSecretKey",
                    Convert.ToBase64String(key),
                    keyId,
                    algorithmName);
            } while (!result.HasValue);

            if (result.GetValueOrDefault())
            {
                SafeCryptoKeyHandle handle = new SafeCryptoKeyHandle(keyId, module);
                return(ctor(handle, algorithmName));
            }

            throw new Exception("?");
        }
Exemplo n.º 10
0
        public async Task ResizeGrid()
        {
            resizemodule = await jsruntime.InvokeAsync <IJSObjectReference>("import", "./_content/Blazm.Components/scripts/ResizeTable.js");

            var size = await resizemodule.InvokeAsync <TableSize>("ResizeTable", id, GroupBy != null);

            if (size != null)
            {
                for (var i = 0; i < size?.Columns?.Length; i++)
                {
                    var counter = i;
                    if (ShowCheckbox || Columns.Any(c => !c.Visible))
                    {
                        //Skip the first one
                        counter = i - 1;
                        if (i == 0)
                        {
                            continue;
                        }
                    }
                    Columns[counter].ClientWidth = size.Columns[i];
                }
                TableClientWidth     = size.TableClientWidth;
                ContainerClientWidth = size.ContainerClientWidth;

                await resizeTableAsync();

                StateHasChanged();
            }
        }
Exemplo n.º 11
0
        private async Task <HmacKey> ImportHmacKeyAsync(
            string algorithmName,
            int outputLength,
            ReadOnlyMemory <byte> key)
        {
            bool?result;
            IJSObjectReference module = await GetModule();

            string keyId;

            do
            {
                keyId  = Guid.NewGuid().ToString("N");
                result = await module.InvokeAsync <bool?>(
                    "importHmacKey",
                    Convert.ToBase64String(key.Span),
                    keyId,
                    algorithmName);
            } while (!result.HasValue);

            if (result.GetValueOrDefault())
            {
                SafeCryptoKeyHandle handle = new SafeCryptoKeyHandle(keyId, module);
                return(new HmacKey(handle, algorithmName, outputLength));
            }

            throw new Exception("?");
        }
Exemplo n.º 12
0
        private async Task <T> GenerateRsaKeyAsync <T>(
            int keySize,
            string algorithmName,
            string hashAlgorithmName,
            bool signatureKey,
            Func <SafeCryptoKeyHandle, string, string, T> ctor)
        {
            bool?result;
            IJSObjectReference module = await GetModule();

            string keyId;

            do
            {
                keyId  = Guid.NewGuid().ToString("N");
                result = await module.InvokeAsync <bool?>(
                    "generateRsaKey",
                    keySize,
                    keyId,
                    algorithmName,
                    hashAlgorithmName,
                    signatureKey);
            } while (!result.HasValue);

            if (result.GetValueOrDefault())
            {
                SafeCryptoKeyHandle handle = new SafeCryptoKeyHandle(keyId, module);
                return(ctor(handle, algorithmName, hashAlgorithmName));
            }

            throw new Exception("?");
        }
Exemplo n.º 13
0
        public async Task <CultureInfo> GetBrowserLanguageAsync()
        {
            await CheckJsObjectAsync();

            var lang = await _langJs.InvokeAsync <string>("detectLanguage");

            return(new CultureInfo(lang, false));
        }
Exemplo n.º 14
0
        protected override async void OnInitialized()
        {
            Globals.DebugWriteLine(@"[Auto:BattleNet\ManageForgotten.razor.cs.OnInitializedAsync]");
            AppData.Instance.WindowTitle = Lang["Title_BNet_ManageIgnored"];
            _jsModule = await _jsRuntime.InvokeAsync <IJSObjectReference>("import", "./js/battlenet/ManageIgnored.js");

            _ = await _jsModule.InvokeAsync <string>("jsLoadIgnored");
        }
Exemplo n.º 15
0
    /// <summary>
    /// Invokes the specified JavaScript function asynchronously.
    /// </summary>
    /// <typeparam name="TValue">The JSON-serializable return type.</typeparam>
    /// <param name="jsObjectReference">The <see cref="IJSObjectReference"/>.</param>
    /// <param name="identifier">An identifier for the function to invoke. For example, the value <c>"someScope.someFunction"</c> will invoke the function <c>someScope.someFunction</c> on the target instance.</param>
    /// <param name="cancellationToken">
    /// A cancellation token to signal the cancellation of the operation. Specifying this parameter will override any default cancellations such as due to timeouts
    /// (<see cref="JSRuntime.DefaultAsyncTimeout"/>) from being applied.
    /// </param>
    /// <param name="args">JSON-serializable arguments.</param>
    /// <returns>An instance of <typeparamref name="TValue"/> obtained by JSON-deserializing the return value.</returns>
    public static ValueTask <TValue> InvokeAsync <[DynamicallyAccessedMembers(JsonSerialized)] TValue>(this IJSObjectReference jsObjectReference, string identifier, CancellationToken cancellationToken, params object?[]?args)
    {
        if (jsObjectReference is null)
        {
            throw new ArgumentNullException(nameof(jsObjectReference));
        }

        return(jsObjectReference.InvokeAsync <TValue>(identifier, cancellationToken, args));
    }
Exemplo n.º 16
0
        public async ValueTask <IJSObjectReference> Weavy(object options = null)
        {
            await Init();

            // get jwt from current user claims
            var jwt = new { jwt = _httpContextAccessor?.HttpContext?.User?.FindFirst("jwt")?.Value };

            return(await _bridge.InvokeAsync <IJSObjectReference>("weavy", new object[] { jwt, options }));
        }
Exemplo n.º 17
0
    /// <summary>
    /// Invokes the specified JavaScript function asynchronously.
    /// </summary>
    /// <param name="jsObjectReference">The <see cref="IJSObjectReference"/>.</param>
    /// <param name="identifier">An identifier for the function to invoke. For example, the value <c>"someScope.someFunction"</c> will invoke the function <c>someScope.someFunction</c> on the target instance.</param>
    /// <param name="cancellationToken">
    /// A cancellation token to signal the cancellation of the operation. Specifying this parameter will override any default cancellations such as due to timeouts
    /// (<see cref="JSRuntime.DefaultAsyncTimeout"/>) from being applied.
    /// </param>
    /// <param name="args">JSON-serializable arguments.</param>
    /// <returns>A <see cref="ValueTask"/> that represents the asynchronous invocation operation.</returns>
    public static async ValueTask InvokeVoidAsync(this IJSObjectReference jsObjectReference, string identifier, CancellationToken cancellationToken, params object?[]?args)
    {
        if (jsObjectReference is null)
        {
            throw new ArgumentNullException(nameof(jsObjectReference));
        }

        await jsObjectReference.InvokeAsync <IJSVoidResult>(identifier, cancellationToken, args);
    }
        /// <summary>
        /// Invokes the specified JavaScript function asynchronously.
        /// </summary>
        /// <typeparam name="TValue">The JSON-serializable return type.</typeparam>
        /// <param name="jsObjectReference">The <see cref="IJSObjectReference"/>.</param>
        /// <param name="identifier">An identifier for the function to invoke. For example, the value <c>"someScope.someFunction"</c> will invoke the function <c>someScope.someFunction</c> on the target instance.</param>
        /// <param name="cancellationToken">
        /// A cancellation token to signal the cancellation of the operation. Specifying this parameter will override any default cancellations such as due to timeouts
        /// (<see cref="JSRuntime.DefaultAsyncTimeout"/>) from being applied.
        /// </param>
        /// <param name="args">JSON-serializable arguments.</param>
        /// <returns>An instance of <typeparamref name="TValue"/> obtained by JSON-deserializing the return value.</returns>
        public static ValueTask <TValue> InvokeAsync <TValue>(this IJSObjectReference jsObjectReference, string identifier, CancellationToken cancellationToken, params object?[] args)
        {
            if (jsObjectReference is null)
            {
                throw new ArgumentNullException(nameof(jsObjectReference));
            }

            return(jsObjectReference.InvokeAsync <TValue>(identifier, cancellationToken, args));
        }
Exemplo n.º 19
0
        // Calling Javascript to create a new instance of Weavy via the JS Interop Module
        public async ValueTask <IJSObjectReference> Weavy(object options = null)
        {
            await Init();

            // Demo JWT only for showcase.weavycloud.com
            // Configure your own JWT here
            var jwt = new { jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzYW1hcmEiLCJuYW1lIjoiU2FtYXJhIEthdXIiLCJleHAiOjI1MTYyMzkwMjIsImlzcyI6InN0YXRpYy1mb3ItZGVtbyIsImNsaWVudF9pZCI6IldlYXZ5RGVtbyIsImRpciI6ImNoYXQtZGVtby1kaXIiLCJlbWFpbCI6InNhbWFyYS5rYXVyQGV4YW1wbGUuY29tIiwidXNlcm5hbWUiOiJzYW1hcmEifQ.UKLmVTsyN779VY9JLTLvpVDLc32Coem_0evAkzG47kM" };

            return(await Bridge.InvokeAsync <IJSObjectReference>("weavy", new object[] { jwt, options }));
        }
        public async ValueTask <string> AesCbcEncrypt(byte[] key, byte[] iv, byte[] data)
        {
            IJSObjectReference module = await GetModule();

            return(await module.InvokeAsync <string>(
                       "symmetricEncrypt",
                       Base64UrlEncode(data),
                       Base64UrlEncode(key),
                       Base64UrlEncode(iv),
                       "AES-CBC"));
        }
Exemplo n.º 21
0
        // Calling Javascript to create a new instance of Weavy via the JS Interop Module
        public async ValueTask <IJSObjectReference> Weavy(object options = null)
        {
            await Init();

            // Configure your own JWT here
            // Currently using Demo JWT only for showcase.weavycloud.com
            // Get jwt from current user claims
            var jwt = new { jwt = HttpContextAccessor?.HttpContext?.User?.FindFirst("jwt")?.Value };

            return(await Bridge.InvokeAsync <IJSObjectReference>("weavy", new object[] { jwt, options }));
        }
Exemplo n.º 22
0
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                // Load the JS file
                _module = await JSRuntime.InvokeAsync <IJSObjectReference>("import", "./js/dropzone.js");

                // Initialize the drop zone
                _dropZoneInstance = await _module.InvokeAsync <IJSObjectReference>("initializeFileDropZone", dropZoneElement, inputFile.Element);
            }
        }
Exemplo n.º 23
0
    /// <summary>
    /// Invokes the specified JavaScript function asynchronously.
    /// </summary>
    /// <param name="jsObjectReference">The <see cref="IJSObjectReference"/>.</param>
    /// <param name="identifier">An identifier for the function to invoke. For example, the value <c>"someScope.someFunction"</c> will invoke the function <c>someScope.someFunction</c> on the target instance.</param>
    /// <param name="timeout">The duration after which to cancel the async operation. Overrides default timeouts (<see cref="JSRuntime.DefaultAsyncTimeout"/>).</param>
    /// <param name="args">JSON-serializable arguments.</param>
    /// <returns>A <see cref="ValueTask"/> that represents the asynchronous invocation operation.</returns>
    public static async ValueTask InvokeVoidAsync(this IJSObjectReference jsObjectReference, string identifier, TimeSpan timeout, params object?[]?args)
    {
        if (jsObjectReference is null)
        {
            throw new ArgumentNullException(nameof(jsObjectReference));
        }

        using var cancellationTokenSource = timeout == Timeout.InfiniteTimeSpan ? null : new CancellationTokenSource(timeout);
        var cancellationToken = cancellationTokenSource?.Token ?? CancellationToken.None;

        await jsObjectReference.InvokeAsync <IJSVoidResult>(identifier, cancellationToken, args);
    }
Exemplo n.º 24
0
    /// <summary>
    /// Invokes the specified JavaScript function asynchronously.
    /// </summary>
    /// <param name="jsObjectReference">The <see cref="IJSObjectReference"/>.</param>
    /// <param name="identifier">An identifier for the function to invoke. For example, the value <c>"someScope.someFunction"</c> will invoke the function <c>someScope.someFunction</c> on the target instance.</param>
    /// <param name="timeout">The duration after which to cancel the async operation. Overrides default timeouts (<see cref="JSRuntime.DefaultAsyncTimeout"/>).</param>
    /// <param name="args">JSON-serializable arguments.</param>
    /// <returns>A <see cref="ValueTask"/> that represents the asynchronous invocation operation.</returns>
    public static async ValueTask <TValue> InvokeAsync <[DynamicallyAccessedMembers(JsonSerialized)] TValue>(this IJSObjectReference jsObjectReference, string identifier, TimeSpan timeout, params object?[]?args)
    {
        if (jsObjectReference is null)
        {
            throw new ArgumentNullException(nameof(jsObjectReference));
        }

        using var cancellationTokenSource = timeout == Timeout.InfiniteTimeSpan ? null : new CancellationTokenSource(timeout);
        var cancellationToken = cancellationTokenSource?.Token ?? CancellationToken.None;

        return(await jsObjectReference.InvokeAsync <TValue>(identifier, cancellationToken, args));
    }
        /// <summary>
        /// This is a component life cycle event that's trigerred after the component is rendered
        /// We use it to load additional javascript to get the bounding client rectangle for our component so that we can
        /// calculate the offsets correctly while doing drag and drop operation for clock arms
        /// </summary>
        /// <param name="firstRender">True if the component is rendering for the first time; false otherwise</param>
        /// <returns>An async task</returns>
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            //Import the js file
            //Please note that the path of the js file specified here is generated at runtime by the project that will use this component library
            IJSObjectReference jsModule = await JS.InvokeAsync <IJSObjectReference>("import", $"./_content/{Assembly.GetExecutingAssembly().GetName().Name}/TimePicker.razor.js");

            //Let's now call our js function and store the bounding rectangle dimensions
            _clockDimensions = await jsModule.InvokeAsync <BoundingClientRect>("GetBoundingClientRect", TimePickerRef);

            //Call the base OnAfterRenderAsync
            await base.OnAfterRenderAsync(firstRender);
        }
Exemplo n.º 26
0
        public async Task OnLoginClick()
        {
            var result = await _module.InvokeAsync <LoginResult>("login", Email, Password);

            if (result.Success)
            {
                NavigationManager.NavigateTo("/secret", true);
            }
            else
            {
                ShowErrorMessage = true;
            }
        }
        public async Task <string> Encrypt(byte[] data, byte[] iv, CryptoKey key, Algorithm algorithm)
        {
            IJSObjectReference module = await GetModule();

            string base64 = await module.InvokeAsync <string>(
                "encrypt",
                key.KeyId,
                Base64UrlEncode(data),
                Base64UrlEncode(iv),
                algorithm.Name);

            return(base64);
        }
Exemplo n.º 28
0
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();

            //var width = await JSRuntime.InvokeAsync<int>("blazorDimension.getWidth");
            _module = await JSRuntime.InvokeAsync <IJSObjectReference>("import", "./js/jsIsolation.js");

            var width = await _module.InvokeAsync <int>("getWidth");

            CheckUsesShortNavText(width);

            _dotNetReference = DotNetObjectReference.Create(this);
            await JSRuntime.InvokeVoidAsync("blazorResize.registerReferenceForResizeEvent", nameof(MainLayout), _dotNetReference);
        }
        public async Task ResizeGrid()
        {
            do
            {
                try
                {
                    resizing     = true;
                    resizeAgain  = false;
                    resizemodule = await jsruntime.InvokeAsync <IJSObjectReference>("import", "/_content/Blazm.Components/scripts/ResizeTable.js");

                    ShowAllColumns = true;
                    await InvokeAsync(StateHasChanged);

                    var size = await resizemodule.InvokeAsync <TableSize>("ResizeTable", id, GroupBy != null);

                    ShowAllColumns = false;
                    await InvokeAsync(StateHasChanged);

                    if (size != null)
                    {
                        for (var i = 0; i < size?.Columns?.Length; i++)
                        {
                            var counter = i;
                            if (ShowCheckbox || Columns.Any(c => !c.Visible) || DetailTemplate != null)
                            {
                                //Skip the first one
                                counter = i - 1;
                                if (i == 0)
                                {
                                    continue;
                                }
                            }
                            Columns[counter].ClientWidth = size.Columns[i];
                        }
                        TableClientWidth     = size.TableClientWidth;
                        ContainerClientWidth = size.ContainerClientWidth;

                        await resizeTableAsync();

                        await InvokeAsync(StateHasChanged);
                    }
                }
                finally
                {
                    resizing = false;
                }
            }while (resizeAgain);
        }
Exemplo n.º 30
0
        public async Task <int> AddGeolocationWatcherAsync(Func <GeolocationResult, Task> locationEventsCallback, bool highAccuracy = false, TimeSpan?timeout = null, TimeSpan?cacheTime = null)
        {
            await CheckJsObjectAsync();

            var info      = new GeolocationEventWatcherInfo(locationEventsCallback);
            var dotnetRef = DotNetObjectReference.Create <GeolocationEventWatcherInfo>(info);

            var id = await _geoJs.InvokeAsync <int>("addGeolocationWatcher", dotnetRef,
                                                    highAccuracy,
                                                    timeout?.TotalMilliseconds ?? DefaultTimeOut,
                                                    cacheTime?.TotalMilliseconds ?? DefaultCacheTime);

            dotnetRef.Value.HandlerId = id;
            _dotNetObjectReferences.Add(dotnetRef);
            return(id);
        }