Example #1
0
        protected string _propName; // name of the property in the parent control

        protected override void Initialize()
        {
            var netRef = DotNetObjectRef.Create(this);
            var events = GetEventNames();

            _jsRef = Invoke <string>("initMarkupProperty", netRef, _host, _propName, _className, _props, events);
        }
Example #2
0
        /// <summary>
        /// Creates a new instance of <see cref="DotNetStaticClickHandler"/>
        /// </summary>
        /// <param name="clickHandler">The delegate for a click handler.</param>
        public DotNetInstanceClickHandler(InstanceClickHandler clickHandler)
        {
            if (clickHandler == null)
            {
                throw new ArgumentNullException(nameof(clickHandler));
            }

            // the method needs to be public
            if (!clickHandler.Method.IsPublic)
            {
                throw new ArgumentException("The click handler needs to be public", nameof(clickHandler));
            }

            // the method needs to have the attribute JSInvokable
            var isJsInvokable = clickHandler
                                .Method
                                .CustomAttributes.Any(data => data.AttributeType == typeof(JSInvokableAttribute));

            if (!isJsInvokable)
            {
                throw new ArgumentException("The passed in method must have the 'JSInvokable' attribute",
                                            nameof(clickHandler));
            }

            //AssemblyName = assembly.GetName().Name;
            // clickHandler.Method.DeclaringType.Assembly.GetName().Name;
            InstanceRef = DotNetObjectRef.Create(clickHandler.Target);
            MethodName  = clickHandler.Method.Name;
        }
Example #3
0
 public static Dictionary <string, DotNetObjectRef <TestDTO> > ReturnDotNetObjectByRef()
 {
     return(new Dictionary <string, DotNetObjectRef <TestDTO> >
     {
         { "Some sync instance", DotNetObjectRef.Create(new TestDTO(1000)) }
     });
 }
 public Task CallHelloHelperSayHello(string name)
 {
     // sayHello is implemented in wwwroot/exampleJsInterop.js
     return(_jsRuntime.InvokeAsync <object>(
                "exampleJsFunctions.sayHello",
                DotNetObjectRef.Create(new HelloHelper(name))));
 }
Example #5
0
        /////////////////////////////////////////////////////////
        #region initialize
        protected override void Initialize()
        {
            var netRef = DotNetObjectRef.Create(this);
            var events = GetEventNames();

            _jsRef = Invoke <string>("initCollectionView", netRef, _host, _props, events);
        }
Example #6
0
 public void OnClose(Func <Exception, Task> callback)
 {
     this.closeCallback = new HubCloseCallback(callback);
     this.runtime.InvokeSync <object>(ON_CLOSE_METHOD,
                                      this.InternalConnectionId,
                                      DotNetObjectRef.Create(this.closeCallback));
 }
Example #7
0
 public void RegisterJsEvents()
 {
     foreach (var item in listDragTarget)
     {
         BvgJsInterop.HandleDrop(item.ElementID, item.ID, DotNetObjectRef.Create(classForJS));
     }
 }
 protected DotNetObjectRef <T> CreateDotNetObjectRef <T>(T value) where T : class
 {
     lock (CreateDotNetObjectRefSyncObj)
     {
         JSRuntime.SetCurrentJSRuntime(jsRuntime);
         return(DotNetObjectRef.Create(value));
     }
 }
Example #9
0
 private DotNetObjectRef <SpeechSynthesis> GetObjectRef()
 {
     if (_ObjectRefOfThis == null)
     {
         _ObjectRefOfThis = DotNetObjectRef.Create(this);
     }
     return(_ObjectRefOfThis);
 }
Example #10
0
        public static async Task <Dictionary <string, DotNetObjectRef <TestDTO> > > ReturnDotNetObjectByRefAsync()
        {
            await Task.Yield();

            return(new Dictionary <string, DotNetObjectRef <TestDTO> >
            {
                { "Some async instance", DotNetObjectRef.Create(new TestDTO(1001)) }
            });
        }
Example #11
0
        // TODO: Find out a more smart way to register to global connect/disconnect events from the WebUSB API regardless if there are subscribers to the events.
        public async Task Initialize()
        {
            if (!this._initialized)
            {
                await this.JSRuntime.InvokeAsync <object>(REGISTER_USB_METHOD, DotNetObjectRef.Create(this));

                this._initialized = true;
            }
        }
Example #12
0
 public HubConnection(IJSRuntime runtime, HttpConnectionOptions options)
 {
     this.runtime = runtime;
     this.Options = options;
     this.InternalConnectionId = Guid.NewGuid().ToString();
     runtime.InvokeSync <object>(CREATE_CONNECTION_METHOD,
                                 this.InternalConnectionId,
                                 DotNetObjectRef.Create(this.Options));
 }
 internal DotNetObjectRef <SpeechSynthesisUtterance> GetObjectRef()
 {
     _ObjectRefCounter++;
     if (_ObjectRefCounter == 1)
     {
         _ObjectRef = DotNetObjectRef.Create(this);
     }
     return(_ObjectRef);
 }
Example #14
0
        public async Task InitAsync()
        {
            Logger.LogDebug("Init JsonRequestHandler");
            const string InitializeJavaScriptInteropName = "InitializeJavaScriptInterop";

            Logger.LogDebug(InitializeJavaScriptInteropName);
            Microsoft.JSInterop.JSRuntime.SetCurrentJSRuntime(JSRuntime);
            await JSRuntime.InvokeAsync <object>(InitializeJavaScriptInteropName, DotNetObjectRef.Create(this));
        }
Example #15
0
        public Task <string> GetTokenAsync()
        {
            //return _jsRuntime.InvokeAsync<object>("B2CService.login");
            return(_jsRuntime.InvokeAsync <string>("B2CService.login", DotNetObjectRef.Create(this)));

            //var token = await _jsRuntime.InvokeAsync<object>("B2CService.login");
            ////return _jsRuntime.InvokeAsync<string>("myPromiseFn");

            //return token.ToString();
        }
Example #16
0
        public Task Read_Throws_IfJsonContainsUnknownContent() => WithJSRuntime(_ =>
        {
            // Arrange
            var dotNetObjectRef = DotNetObjectRef.Create(new TestModel());

            var json = "{\"foo\":2}";

            // Act & Assert
            var ex = Assert.Throws <JsonException>(() => JsonSerializer.Deserialize <DotNetObjectRef <TestModel> >(json));
            Assert.Equal("Unexcepted JSON property foo.", ex.Message);
        });
Example #17
0
 public LocationService(IMediator mediator, IConfiguration configuration, IJSRuntime jsRuntime)
 {
     Mediator = mediator;
     BingKey  = configuration["bing"];
     JS       = jsRuntime;
     lock (Lock)
     {
         JSRuntime.SetCurrentJSRuntime(jsRuntime);
         Ref = DotNetObjectRef.Create(this);
     }
 }
Example #18
0
        public Task Read_Throws_IfJsonIsMissingDotNetObjectProperty() => WithJSRuntime(_ =>
        {
            // Arrange
            var dotNetObjectRef = DotNetObjectRef.Create(new TestModel());

            var json = "{}";

            // Act & Assert
            var ex = Assert.Throws <JsonException>(() => JsonSerializer.Deserialize <DotNetObjectRef <TestModel> >(json));
            Assert.Equal("Required property __dotNetObject not found.", ex.Message);
        });
Example #19
0
 public async Task CloseSSEAsync()
 {
     try
     {
         await _jsRuntime.InvokeAsync <object>(
             "BlazorSignalR.ServerSentEventsTransport.CloseConnection", DotNetObjectRef.Create(this));
     }
     catch (Exception e)
     {
         _logger.LogError($"Failed to stop SSE {e}");
     }
 }
Example #20
0
        public Task Read_Throws_IfDotNetObjectIdAppearsMultipleTimes() => WithJSRuntime(_ =>
        {
            // Arrange
            var input           = new TestModel();
            var dotNetObjectRef = DotNetObjectRef.Create(input);
            var objectId        = dotNetObjectRef.ObjectId;

            var json = $"{{\"__dotNetObject\":{objectId},\"__dotNetObject\":{objectId}}}";

            // Act & Assert
            var ex = Record.Exception(() => JsonSerializer.Deserialize <DotNetObjectRef <TestModel> >(json));
            Assert.IsAssignableFrom <JsonException>(ex);
        });
Example #21
0
 public async Task CloseWebSocketAsync()
 {
     Log.ClosingWebSocket(_logger);
     try
     {
         await _jsRuntime.InvokeAsync <object>(
             "BlazorSignalR.WebSocketsTransport.CloseConnection", DotNetObjectRef.Create(this));
     }
     catch (Exception e)
     {
         Log.ClosingWebSocketFailed(_logger, e);
     }
 }
Example #22
0
 public InstanceMethodOutput InstanceMethod(InstanceMethodInput input)
 {
     // This method shows we can pass in values marshalled both as JSON (the dict itself)
     // and by ref (the incoming dtoByRef), plus that we can return values marshalled as
     // JSON (the returned dictionary) and by ref (the outgoingByRef value)
     return(new InstanceMethodOutput
     {
         ThisTypeName = GetType().Name,
         StringValueUpper = input.StringValue.ToUpperInvariant(),
         IncomingByRef = input.DTOByRef.Value.GetNonSerializedValue(),
         OutgoingByRef = DotNetObjectRef.Create(new TestDTO(1234)),
     });
 }
Example #23
0
        public Task NotifiesAssociatedJsRuntimeOfDisposal() => WithJSRuntime(jsRuntime =>
        {
            // Arrange
            var objRef     = DotNetObjectRef.Create(new object());
            var trackingId = objRef.__dotNetObject;

            // Act
            objRef.Dispose();

            // Assert
            var ex = Assert.Throws <ArgumentException>(() => jsRuntime.ObjectRefManager.FindDotNetObject(trackingId));
            Assert.StartsWith("There is no tracked object with id '1'.", ex.Message);
        });
Example #24
0
        internal void RegisterHandle(string methodName, HubMethodCallback callback)
        {
            if (this.callbacks.TryGetValue(methodName, out var methodHandlers))
            {
                methodHandlers[callback.Id] = callback;
            }
            else
            {
                this.callbacks[methodName] = new Dictionary <string, HubMethodCallback>
                {
                    { callback.Id, callback }
                };
            }

            this.runtime.InvokeSync <object>(ON_METHOD, this.InternalConnectionId, DotNetObjectRef.Create(callback));
        }
Example #25
0
        public Task Read_ReadsJson() => WithJSRuntime(_ =>
        {
            // Arrange
            var input           = new TestModel();
            var dotNetObjectRef = DotNetObjectRef.Create(input);
            var objectId        = dotNetObjectRef.ObjectId;

            var json = $"{{\"__dotNetObject\":{objectId}}}";

            // Act
            var deserialized = JsonSerializer.Deserialize <DotNetObjectRef <TestModel> >(json);

            // Assert
            Assert.Same(input, deserialized.Value);
            Assert.Equal(objectId, deserialized.ObjectId);
        });
Example #26
0
        /// <summary>
        /// Creates a new instance of <see cref="DotNetInstanceHoverHandler"/>
        /// </summary>
        /// <param name="legendItemOnHoverHandler">The delegate for a hover handler</param>
        public DotNetInstanceHoverHandler(LegendItemOnHover legendItemOnHoverHandler)
        {
            // Check for null
            ArgValidation.AssertNotNullOrEmpty(nameof(legendItemOnHoverHandler), legendItemOnHoverHandler);

            // Check for the method to be public and static
            ArgValidation.AssertIsPublic(legendItemOnHoverHandler.Method);

            // Check for the JsInvokable attribute
            ArgValidation.AssertHasCustomAttribute(legendItemOnHoverHandler.Method, typeof(JSInvokableAttribute));

            // The parameters and return type is taken care of by the delegate's definition

            InstanceRef = DotNetObjectRef.Create(legendItemOnHoverHandler.Target);
            MethodName  = legendItemOnHoverHandler.Method.Name;
        }
Example #27
0
        public Task Read_ReturnsTheCorrectInstance() => WithJSRuntime(_ =>
        {
            // Arrange
            // Track a few instances and verify that the deserialized value returns the correct value.
            var instance1 = new TestModel();
            var instance2 = new TestModel();
            var ref1      = DotNetObjectRef.Create(instance1);
            var ref2      = DotNetObjectRef.Create(instance2);

            var json = $"[{{\"__dotNetObject\":{ref2.ObjectId}}},{{\"__dotNetObject\":{ref1.ObjectId}}}]";

            // Act
            var deserialized = JsonSerializer.Deserialize <DotNetObjectRef <TestModel>[]>(json);

            // Assert
            Assert.Same(instance2, deserialized[0].Value);
            Assert.Same(instance1, deserialized[1].Value);
        });
Example #28
0
        private async Task ProcessEventStream(string url, IDuplexPipe application, CancellationToken transportCtsToken)
        {
            Log.StartReceive(_logger);

            try
            {
                // Creates a task to represent the SSE js processing
                TaskCompletionSource <object> task = new TaskCompletionSource <object>();
                _jsTask = task;

                // Create connection
                await _jsRuntime.InvokeAsync <object>(
                    "BlazorSignalR.ServerSentEventsTransport.CreateConnection", url, DotNetObjectRef.Create(this));

                // If canceled, stop fake processing
                transportCtsToken.Register(() => { task.SetCanceled(); });

                // Wait until js side stops
                await task.Task;

                if (task.Task.IsCanceled)
                {
                    Log.ReceiveCanceled(_logger);
                }
            }
            catch (Exception ex)
            {
                _logger.LogDebug($"SSE JS Side error {ex.Message}");
                _error = ex;
            }
            finally
            {
                _application.Output.Complete(_error);

                Log.ReceiveStopped(_logger);

                // Close JS side SSE
                await CloseSSEAsync();
            }
        }
Example #29
0
        public async Task StartAsync(Uri url, TransferFormat transferFormat, CancellationToken cancellationToken)
        {
            if (url == null)
            {
                throw new ArgumentNullException(nameof(url));
            }

            if (transferFormat != TransferFormat.Binary && transferFormat != TransferFormat.Text)
            {
                throw new ArgumentException(
                          $"The '{transferFormat}' transfer format is not supported by this transport.",
                          nameof(transferFormat));
            }


            Log.StartTransport(_logger, transferFormat);

            // Create connection
            _startTask = new TaskCompletionSource <object>();
            await _jsRuntime.InvokeAsync <object>(
                "BlazorSignalR.WebSocketsTransport.CreateConnection", url.ToString(),
                transferFormat == TransferFormat.Binary, DotNetObjectRef.Create(this));

            await _startTask.Task;

            _startTask = null;

            Log.StartedTransport(_logger);

            // Create the pipe pair (Application's writer is connected to Transport's reader, and vice versa)
            PipeOptions options = ClientPipeOptions.DefaultOptions;

            DuplexPipe.DuplexPipePair pair = DuplexPipe.CreateConnectionPair(options, options);

            _transport   = pair.Transport;
            _application = pair.Application;

            Running = ProcessSocketAsync();
        }
Example #30
0
        public void SyncCallResultCanIncludeDotNetObjects()
        {
            // Arrange
            var runtime = new TestJSInProcessRuntime
            {
                NextResultJson = "[{\"__dotNetObject\":2},{\"__dotNetObject\":1}]"
            };

            JSRuntime.SetCurrentJSRuntime(runtime);
            var obj1 = new object();
            var obj2 = new object();

            // Act
            var syncResult = runtime.Invoke <DotNetObjectRef <object>[]>(
                "test identifier",
                DotNetObjectRef.Create(obj1),
                "some other arg",
                DotNetObjectRef.Create(obj2));
            var call = runtime.InvokeCalls.Single();

            // Assert
            Assert.Equal(new[] { obj2, obj1 }, syncResult.Select(r => r.Value));
        }