├── SpawnDev.BlazorJS.Photino.App.Demo ├── publish.win-x64.bat ├── icon-192.ico ├── Properties │ └── launchSettings.json ├── wwwroot │ └── index.html ├── Program.cs └── SpawnDev.BlazorJS.Photino.App.Demo.csproj ├── SpawnDev.BlazorJS.Photino ├── Assets │ └── icon-128.png ├── Native │ └── NativeMethodsWindows.cs ├── JsonConverters │ ├── IntPtrJsonConverter.cs │ └── ClaimsIdentityConverter.cs ├── IWebRootServer.cs ├── SpawnDev.BlazorJS.Photino.csproj ├── PhotinoAppDispatcher.cs ├── PhotinoBlazorWASMWindow.cs ├── JsonElementListExtensions.cs ├── PhotinoBlazorWASMApp.cs ├── AsyncCallDispatcherSlim.cs └── RemoteDispatcher.cs ├── SpawnDev.BlazorJS.Photino.App ├── Assets │ └── icon-128.png ├── SpawnDev.BlazorJS.Photino.App.csproj ├── PhotinoBlazorWASMAppBuilder.cs └── WebRootServer.cs ├── SpawnDev.BlazorJS.Photino.App.Demo.Client ├── wwwroot │ ├── favicon.png │ ├── icon-192.png │ ├── index.html │ └── css │ │ └── app.css ├── Pages │ ├── Counter.razor │ └── Home.razor ├── Layout │ ├── MainLayout.razor │ ├── NavMenu.razor │ ├── MainLayout.razor.css │ └── NavMenu.razor.css ├── _Imports.razor ├── App.razor ├── Services │ └── ConsoleLogger.cs ├── SpawnDev.BlazorJS.Photino.App.Demo.Client.csproj ├── Properties │ └── launchSettings.json └── Program.cs ├── LICENSE.txt ├── .gitattributes ├── SpawnDev.BlazorJS.Photino.sln ├── README.md └── .gitignore /SpawnDev.BlazorJS.Photino.App.Demo/publish.win-x64.bat: -------------------------------------------------------------------------------- 1 | 2 | dotnet publish -c Release -r win-x64 3 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/Assets/icon-128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LostBeard/SpawnDev.BlazorJS.Photino/master/SpawnDev.BlazorJS.Photino/Assets/icon-128.png -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo/icon-192.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LostBeard/SpawnDev.BlazorJS.Photino/master/SpawnDev.BlazorJS.Photino.App.Demo/icon-192.ico -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App/Assets/icon-128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LostBeard/SpawnDev.BlazorJS.Photino/master/SpawnDev.BlazorJS.Photino.App/Assets/icon-128.png -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "HelloPhotinoApp": { 4 | "commandName": "Project" 5 | } 6 | } 7 | } -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/wwwroot/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LostBeard/SpawnDev.BlazorJS.Photino/master/SpawnDev.BlazorJS.Photino.App.Demo.Client/wwwroot/favicon.png -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/wwwroot/icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LostBeard/SpawnDev.BlazorJS.Photino/master/SpawnDev.BlazorJS.Photino.App.Demo.Client/wwwroot/icon-192.png -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/Pages/Counter.razor: -------------------------------------------------------------------------------- 1 | @page "/counter" 2 | 3 | Counter 4 | 5 |

Counter

6 | 7 |

Current count: @currentCount

8 | 9 |
10 | 11 | @code { 12 | 13 | private int currentCount = 0; 14 | 15 | private void Increment() 16 | { 17 | currentCount++; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/Layout/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 |
3 | 6 | 7 |
8 |
9 | About 10 |
11 | 12 |
13 | @Body 14 |
15 |
16 |
17 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/Native/NativeMethodsWindows.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | 3 | namespace SpawnDev.BlazorJS.Photino.Native; 4 | 5 | internal static class NativeMethodsWindows 6 | { 7 | [DllImport("user32.dll")] 8 | public static extern bool ShowWindow(nint hWnd, int nCmdShow); 9 | 10 | // ShowWindow commands 11 | public const int SW_HIDE = 0; 12 | public const int SW_SHOW = 5; 13 | public const int SW_MINIMIZE = 6; 14 | public const int SW_RESTORE = 9; 15 | } 16 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Forms 4 | @using Microsoft.AspNetCore.Components.Routing 5 | @using Microsoft.AspNetCore.Components.Web 6 | @using Microsoft.AspNetCore.Components.Web.Virtualization 7 | @using Microsoft.AspNetCore.Components.WebAssembly.Http 8 | @using Microsoft.JSInterop 9 | @using SpawnDev.BlazorJS.Photino.App.Demo.Client 10 | @using SpawnDev.BlazorJS.Photino.App.Demo.Client.Layout 11 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/App.razor: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Not found 8 | 9 |

Sorry, there's nothing at this address.

10 |
11 |
12 |
13 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/Services/ConsoleLogger.cs: -------------------------------------------------------------------------------- 1 | namespace SpawnDev.BlazorJS.Photino.App.Demo.Client.Services 2 | { 3 | public interface IConsoleLogger 4 | { 5 | Task LogAsync(string message); 6 | void Log(string message); 7 | } 8 | 9 | public class ConsoleLogger : IConsoleLogger 10 | { 11 | public ConsoleLogger() 12 | { 13 | var nmt = true; 14 | } 15 | public void Log(string message) 16 | { 17 | Console.WriteLine(message); 18 | } 19 | 20 | public Task LogAsync(string message) 21 | { 22 | Console.WriteLine(message); 23 | return Task.CompletedTask; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/SpawnDev.BlazorJS.Photino.App.Demo.Client.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/JsonConverters/IntPtrJsonConverter.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using System.Text.Json; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace SpawnDev.BlazorJS.Photino.JsonConverters 6 | { 7 | public class IntPtrJsonConverter : JsonConverter 8 | { 9 | public override nint Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 10 | { 11 | if (reader.TokenType == JsonTokenType.Null) 12 | { 13 | return default(nint); 14 | } 15 | var value = JsonSerializer.Deserialize(ref reader, options); 16 | return new nint(value); 17 | } 18 | public override void Write(Utf8JsonWriter writer, nint value, JsonSerializerOptions options) 19 | { 20 | var sValue = value.ToInt64(); 21 | JsonSerializer.Serialize(writer, sValue, options); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/IWebRootServer.cs: -------------------------------------------------------------------------------- 1 | namespace SpawnDev.BlazorJS.Photino 2 | { 3 | /// 4 | /// Simple http server 5 | /// 6 | public interface IWebRootServer 7 | { 8 | /// 9 | /// True if running 10 | /// 11 | bool Running { get; } 12 | /// 13 | /// The currently served url 14 | /// 15 | string? Url { get; } 16 | /// 17 | /// The served folder 18 | /// 19 | string? WwwRootFolder { get; } 20 | /// 21 | /// Starts the server 22 | /// 23 | void CreateStaticFileServer(int startPort, int portRange, string webRootFolder, out string baseUrl); 24 | /// 25 | /// Starts the server 26 | /// 27 | void CreateStaticFileServer(out string baseUrl); 28 | /// 29 | /// Starts the server 30 | /// 31 | void CreateStaticFileServer(string webRootFolder, out string baseUrl); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [year] [fullname] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | SpawnDev.BlazorJS.Photino.App.Demo.Client 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 |
22 |
23 | 24 |
25 | An unhandled error has occurred. 26 | Reload 27 | 🗙 28 |
29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | SpawnDev.BlazorJS.Photino.App.Demo.Client 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 |
22 |
23 | 24 |
25 | An unhandled error has occurred. 26 | Reload 27 | 🗙 28 |
29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/Layout/NavMenu.razor: -------------------------------------------------------------------------------- 1 | 9 | 10 | 24 | 25 | @code { 26 | private bool collapseNavMenu = true; 27 | 28 | private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; 29 | 30 | private void ToggleNavMenu() 31 | { 32 | collapseNavMenu = !collapseNavMenu; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:29852", 8 | "sslPort": 44338 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 17 | "applicationUrl": "http://localhost:5174", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "https": { 23 | "commandName": "Project", 24 | "dotnetRunMessages": true, 25 | "launchBrowser": true, 26 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 27 | "applicationUrl": "https://localhost:7174;http://localhost:5174", 28 | "environmentVariables": { 29 | "ASPNETCORE_ENVIRONMENT": "Development" 30 | } 31 | }, 32 | "IIS Express": { 33 | "commandName": "IISExpress", 34 | "launchBrowser": true, 35 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 36 | "environmentVariables": { 37 | "ASPNETCORE_ENVIRONMENT": "Development" 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/JsonConverters/ClaimsIdentityConverter.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using System.Text.Json; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace SpawnDev.BlazorJS.Photino.JsonConverters 6 | { 7 | public class ClaimsIdentityConverter : JsonConverter 8 | { 9 | public override ClaimsIdentity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 10 | { 11 | var value = JsonSerializer.Deserialize(ref reader, options); 12 | return string.IsNullOrWhiteSpace(value) ? default! : Base64ToClaimsIdentity(value); 13 | } 14 | public override void Write(Utf8JsonWriter writer, ClaimsIdentity value, JsonSerializerOptions options) 15 | { 16 | var sValue = ToBase64(value); 17 | JsonSerializer.Serialize(writer, sValue, options); 18 | } 19 | static string ToBase64(ClaimsIdentity claimsIdentity) 20 | { 21 | using var buffer = new MemoryStream(); 22 | using var writer = new BinaryWriter(buffer); 23 | claimsIdentity.WriteTo(writer); 24 | var data = buffer.ToArray(); 25 | return Convert.ToBase64String(data); 26 | } 27 | static ClaimsIdentity Base64ToClaimsIdentity(string claimsIdentity) 28 | { 29 | var data = Convert.FromBase64String(claimsIdentity); 30 | using var buffer = new MemoryStream(data); 31 | using var reader = new BinaryReader(buffer); 32 | return new ClaimsIdentity(reader); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components.Web; 2 | using Microsoft.AspNetCore.Components.WebAssembly.Hosting; 3 | using SpawnDev.BlazorJS; 4 | using SpawnDev.BlazorJS.Photino; 5 | using SpawnDev.BlazorJS.Photino.App.Demo.Client; 6 | using SpawnDev.BlazorJS.Photino.App.Demo.Client.Services; 7 | 8 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 9 | builder.RootComponents.Add("#app"); 10 | builder.RootComponents.Add("head::after"); 11 | 12 | // BlazorJSRuntime (PhotinoAppDispatcher dependency) 13 | builder.Services.AddBlazorJSRuntime(); 14 | 15 | // PhotinoAppDispatcher lets Blazor WASM call into the Photino hosting app (if available) using: 16 | // Expressions: 17 | // var result = await PhotinoAppDispatcher.Run(service => service.SomeMethod(someVariable1, someVariable2)); 18 | // - or - 19 | // Interface DispatchProxy: 20 | // var service = PhotinoAppDispatcher.GetService() where TService : interface 21 | // var result = await service.SomeMethod(someVariable1, someVariable2); 22 | // - or - 23 | // Register Photino host app service interface DispatchProxy and use as a normal service 24 | // (See IConsoleLogger below) 25 | builder.Services.AddSingleton(); 26 | 27 | // This adds IConsoleLogger provided by PhotinoAppDispatcher which will relay all 28 | // async method calls to the Photino app instance via an interface DispatchProxy 29 | builder.Services.AddSingleton(sp => sp.GetRequiredService().GetService()); 30 | 31 | // Start 32 | await builder.Build().BlazorJSRunAsync(); 33 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/SpawnDev.BlazorJS.Photino.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0;net9.0;net10.0 5 | enable 6 | enable 7 | 1.2.0 8 | True 9 | true 10 | true 11 | Embedded 12 | SpawnDev.BlazorJS.Photino 13 | LostBeard 14 | Blazor WebAssembly in Photino. Use this package in the Blazor WebAssembly project. 15 | https://github.com/LostBeard/SpawnDev.BlazorJS.Photino 16 | README.md 17 | LICENSE.txt 18 | icon-128.png 19 | https://github.com/LostBeard/SpawnDev.BlazorJS.Photino.git 20 | git 21 | Blazor;BlazorWebAssembly;WebBrowser;Photino 22 | latest 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/Layout/MainLayout.razor.css: -------------------------------------------------------------------------------- 1 | .page { 2 | position: relative; 3 | display: flex; 4 | flex-direction: column; 5 | } 6 | 7 | main { 8 | flex: 1; 9 | } 10 | 11 | .sidebar { 12 | background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%); 13 | } 14 | 15 | .top-row { 16 | background-color: #f7f7f7; 17 | border-bottom: 1px solid #d6d5d5; 18 | justify-content: flex-end; 19 | height: 3.5rem; 20 | display: flex; 21 | align-items: center; 22 | } 23 | 24 | .top-row ::deep a, .top-row ::deep .btn-link { 25 | white-space: nowrap; 26 | margin-left: 1.5rem; 27 | text-decoration: none; 28 | } 29 | 30 | .top-row ::deep a:hover, .top-row ::deep .btn-link:hover { 31 | text-decoration: underline; 32 | } 33 | 34 | .top-row ::deep a:first-child { 35 | overflow: hidden; 36 | text-overflow: ellipsis; 37 | } 38 | 39 | @media (max-width: 640.98px) { 40 | .top-row { 41 | justify-content: space-between; 42 | } 43 | 44 | .top-row ::deep a, .top-row ::deep .btn-link { 45 | margin-left: 0; 46 | } 47 | } 48 | 49 | @media (min-width: 641px) { 50 | .page { 51 | flex-direction: row; 52 | } 53 | 54 | .sidebar { 55 | width: 250px; 56 | height: 100vh; 57 | position: sticky; 58 | top: 0; 59 | } 60 | 61 | .top-row { 62 | position: sticky; 63 | top: 0; 64 | z-index: 1; 65 | } 66 | 67 | .top-row.auth ::deep a:first-child { 68 | flex: 1; 69 | text-align: right; 70 | width: 0; 71 | } 72 | 73 | .top-row, article { 74 | padding-left: 2rem !important; 75 | padding-right: 1.5rem !important; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App/SpawnDev.BlazorJS.Photino.App.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0;net9.0;net10.0 5 | enable 6 | enable 7 | 1.2.0 8 | True 9 | true 10 | true 11 | Embedded 12 | SpawnDev.BlazorJS.Photino.App 13 | LostBeard 14 | Blazor WebAssembly in Photino. Use this package in the Photino.Net app project. 15 | https://github.com/LostBeard/SpawnDev.BlazorJS.Photino 16 | README.md 17 | LICENSE.txt 18 | icon-128.png 19 | https://github.com/LostBeard/SpawnDev.BlazorJS.Photino.git 20 | git 21 | Blazor;BlazorWebAssembly;WebBrowser;Photino 22 | latest 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App/PhotinoBlazorWASMAppBuilder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace SpawnDev.BlazorJS.Photino; 4 | /// 5 | /// Builds PhotinoBlazorWASMApp 6 | /// 7 | public class PhotinoBlazorWASMAppBuilder 8 | { 9 | /// 10 | /// PhotinoBlazorWASMApp services collection 11 | /// 12 | public IServiceCollection Services { get; } 13 | 14 | internal PhotinoBlazorWASMAppBuilder() 15 | { 16 | Services = new ServiceCollection(); 17 | } 18 | /// 19 | /// Create default 20 | /// 21 | /// 22 | /// 23 | public static PhotinoBlazorWASMAppBuilder CreateDefault(string[]? args = null) 24 | { 25 | PhotinoBlazorWASMAppBuilder photinoBlazorAppBuilder = new PhotinoBlazorWASMAppBuilder(); 26 | photinoBlazorAppBuilder.Services.AddSingleton(photinoBlazorAppBuilder.Services); 27 | photinoBlazorAppBuilder.Services.AddSingleton(sp => sp); 28 | photinoBlazorAppBuilder.Services.AddSingleton(); 29 | photinoBlazorAppBuilder.Services.AddSingleton(); 30 | return photinoBlazorAppBuilder; 31 | } 32 | /// 33 | /// Builds PhotinoBlazorWASMApp and returns it. 34 | /// 35 | /// 36 | /// 37 | public PhotinoBlazorWASMApp Build(Action? serviceProviderOptions = null) 38 | { 39 | var serviceProvider = Services.BuildServiceProvider(); 40 | var PhotinoBlazorWASMApp = serviceProvider.GetRequiredService(); 41 | serviceProviderOptions?.Invoke(serviceProvider); 42 | return PhotinoBlazorWASMApp; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/Pages/Home.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | @using SpawnDev.BlazorJS.Photino.App.Demo.Client.Services 3 | 4 | Home 5 | 6 |

Home

7 | 8 | Connected to Photino app services: @PhotinoAppDispatcher.IsReady 9 |
10 | 11 | 12 | 13 | 14 | @code { 15 | [Inject] 16 | PhotinoAppDispatcher PhotinoAppDispatcher { get; set; } = default!; 17 | 18 | [Inject] 19 | IConsoleLogger ConsoleLogger { get; set; } = default!; 20 | 21 | private async Task OpenWindow() 22 | { 23 | // this calls IConsoleLogger.LogAsync() which relays the call to the Photino host app IConsoleLogger service 24 | await ConsoleLogger.LogAsync(">> Window being opened by " + PhotinoAppDispatcher.WindowId); 25 | 26 | // call PhotinoBlazorWASMApp.OpenWindow() in the Photino host app on the PhotinoBlazorWASMApp service 27 | var windowId = await PhotinoAppDispatcher.Run(s => s.OpenWindow()); 28 | 29 | // this calls IConsoleLogger.LogAsync() which relays the call to the Photino host app IConsoleLogger service 30 | await ConsoleLogger.LogAsync(">> Window opened: " + windowId); 31 | } 32 | 33 | private async Task CloseThisWindow() 34 | { 35 | // this calls IConsoleLogger.LogAsync() which relays the call to the Photino host app IConsoleLogger service 36 | await ConsoleLogger.LogAsync(">> Window closing: " + PhotinoAppDispatcher.WindowId); 37 | 38 | // call PhotinoBlazorWASMWindow.Close() in the Photino host app on this window's PhotinoBlazorWASMWindow instance 39 | await PhotinoAppDispatcher.Run(s => s.Close()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using SpawnDev; 3 | using SpawnDev.BlazorJS.Photino; 4 | using SpawnDev.BlazorJS.Photino.App.Demo.Client.Services; 5 | 6 | namespace HelloPhotinoApp 7 | { 8 | // NOTE: To hide the console window, go to the project properties and change the Output Type to Windows Application. 9 | // Or edit the .csproj file and change the tag from "WinExe" to "Exe". 10 | internal class Program 11 | { 12 | [STAThread] 13 | static void Main(string[] args) 14 | { 15 | // Create RemoteServiceProviderBuilder 16 | var appBuilder = PhotinoBlazorWASMAppBuilder.CreateDefault(args); 17 | 18 | // Blazor WebAssembly instances can call these services using expressions or 19 | // an interface DispatchProxy provided by the PhotinoAppDispatcher service 20 | // Singleton services are shared with all windows 21 | // Scoped services are per-window 22 | // Transient are per call 23 | 24 | // The demo uses this service via an interface DispatchProxy 25 | appBuilder.Services.AddSingleton(); 26 | 27 | // build 28 | var app = appBuilder.Build(); 29 | 30 | /// 31 | /// If true, closing the main window will hide it instead of closing it.
32 | /// This allows the app to stay alive until all windows are closed.
33 | /// NOTE: Only supported when PhotinoWindow.IsWindowsPlatform == true
34 | /// Default: false 35 | ///
36 | app.IndependentWindows = false; 37 | 38 | /// 39 | /// If true the app will not exit when there are no windows except invisible MainWindow.
40 | /// Setting this to true is useful for a system tray icon that can be used to create a new window or show the main one.
41 | /// NOTE: Only supported when PhotinoWindow.IsWindowsPlatform == true
42 | /// Default: false 43 | ///
44 | app.InvisibleKeepAlive = false; 45 | 46 | #if DEBUG 47 | // Set the Url where the Blazor WebAssembly dev server is hosting when DEBUG 48 | // if not set, the app's "wwwroot/index.html" path will be used. 49 | // In production a release build of your Blazor WASM app could be served from there. 50 | app.SetAppBaseUri("https://localhost:7174/"); 51 | #endif 52 | 53 | // Start app. Show main window 54 | app.Run(); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.14.36623.8 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpawnDev.BlazorJS.Photino", "SpawnDev.BlazorJS.Photino\SpawnDev.BlazorJS.Photino.csproj", "{307238B9-F37F-43CA-950F-48BFEB35D7A5}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpawnDev.BlazorJS.Photino.App.Demo.Client", "SpawnDev.BlazorJS.Photino.App.Demo.Client\SpawnDev.BlazorJS.Photino.App.Demo.Client.csproj", "{72F1EA39-4075-4CCC-A3D1-05D468337FE3}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpawnDev.BlazorJS.Photino.App.Demo", "SpawnDev.BlazorJS.Photino.App.Demo\SpawnDev.BlazorJS.Photino.App.Demo.csproj", "{1D43CB3B-6BE9-41C6-BD08-A208814E47A7}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpawnDev.BlazorJS.Photino.App", "SpawnDev.BlazorJS.Photino.App\SpawnDev.BlazorJS.Photino.App.csproj", "{6DBD81D6-F4D2-4722-9B48-7FED0C18C1E5}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {307238B9-F37F-43CA-950F-48BFEB35D7A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {307238B9-F37F-43CA-950F-48BFEB35D7A5}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {307238B9-F37F-43CA-950F-48BFEB35D7A5}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {307238B9-F37F-43CA-950F-48BFEB35D7A5}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {72F1EA39-4075-4CCC-A3D1-05D468337FE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {72F1EA39-4075-4CCC-A3D1-05D468337FE3}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {72F1EA39-4075-4CCC-A3D1-05D468337FE3}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {72F1EA39-4075-4CCC-A3D1-05D468337FE3}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {1D43CB3B-6BE9-41C6-BD08-A208814E47A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {1D43CB3B-6BE9-41C6-BD08-A208814E47A7}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {1D43CB3B-6BE9-41C6-BD08-A208814E47A7}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {1D43CB3B-6BE9-41C6-BD08-A208814E47A7}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {6DBD81D6-F4D2-4722-9B48-7FED0C18C1E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {6DBD81D6-F4D2-4722-9B48-7FED0C18C1E5}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {6DBD81D6-F4D2-4722-9B48-7FED0C18C1E5}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {6DBD81D6-F4D2-4722-9B48-7FED0C18C1E5}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | GlobalSection(ExtensibilityGlobals) = postSolution 41 | SolutionGuid = {14EB1C29-66E3-450C-B11F-8F4298333AF8} 42 | EndGlobalSection 43 | EndGlobal 44 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/Layout/NavMenu.razor.css: -------------------------------------------------------------------------------- 1 | .navbar-toggler { 2 | background-color: rgba(255, 255, 255, 0.1); 3 | } 4 | 5 | .top-row { 6 | height: 3.5rem; 7 | background-color: rgba(0,0,0,0.4); 8 | } 9 | 10 | .navbar-brand { 11 | font-size: 1.1rem; 12 | } 13 | 14 | .bi { 15 | display: inline-block; 16 | position: relative; 17 | width: 1.25rem; 18 | height: 1.25rem; 19 | margin-right: 0.75rem; 20 | top: -1px; 21 | background-size: cover; 22 | } 23 | 24 | .bi-house-door-fill-nav-menu { 25 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-house-door-fill' viewBox='0 0 16 16'%3E%3Cpath d='M6.5 14.5v-3.505c0-.245.25-.495.5-.495h2c.25 0 .5.25.5.5v3.5a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293L8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5Z'/%3E%3C/svg%3E"); 26 | } 27 | 28 | .bi-plus-square-fill-nav-menu { 29 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-plus-square-fill' viewBox='0 0 16 16'%3E%3Cpath d='M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3a.5.5 0 0 1 1 0z'/%3E%3C/svg%3E"); 30 | } 31 | 32 | .bi-list-nested-nav-menu { 33 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-list-nested' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M4.5 11.5A.5.5 0 0 1 5 11h10a.5.5 0 0 1 0 1H5a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 3 7h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 1 3h10a.5.5 0 0 1 0 1H1a.5.5 0 0 1-.5-.5z'/%3E%3C/svg%3E"); 34 | } 35 | 36 | .nav-item { 37 | font-size: 0.9rem; 38 | padding-bottom: 0.5rem; 39 | } 40 | 41 | .nav-item:first-of-type { 42 | padding-top: 1rem; 43 | } 44 | 45 | .nav-item:last-of-type { 46 | padding-bottom: 1rem; 47 | } 48 | 49 | .nav-item ::deep a { 50 | color: #d7d7d7; 51 | border-radius: 4px; 52 | height: 3rem; 53 | display: flex; 54 | align-items: center; 55 | line-height: 3rem; 56 | } 57 | 58 | .nav-item ::deep a.active { 59 | background-color: rgba(255,255,255,0.37); 60 | color: white; 61 | } 62 | 63 | .nav-item ::deep a:hover { 64 | background-color: rgba(255,255,255,0.1); 65 | color: white; 66 | } 67 | 68 | @media (min-width: 641px) { 69 | .navbar-toggler { 70 | display: none; 71 | } 72 | 73 | .collapse { 74 | /* Never collapse the sidebar for wide screens */ 75 | display: block; 76 | } 77 | 78 | .nav-scrollable { 79 | /* Allow sidebar to scroll for tall menus */ 80 | height: calc(100vh - 3.5rem); 81 | overflow-y: auto; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo/SpawnDev.BlazorJS.Photino.App.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | WinExe 8 | net8.0 9 | enable 10 | enable 11 | 12 | 15 | 16 | 17 | ./icon-192.ico 18 | 19 | 20 | true 21 | 22 | 23 | true 24 | true 25 | 26 | 27 | true 28 | 29 | 33 | false 34 | false 35 | 36 | 37 | embedded 38 | 39 | ./bin/Publish 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | $(ProjectDir)..\SpawnDev.BlazorJS.Photino.App.Demo.Client 61 | $(BlazorWasmProjectDir)\bin\Publish\$(Configuration)\net8.0\publish\wwwroot 62 | $(ProjectDir)wwwroot 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/PhotinoAppDispatcher.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | 3 | namespace SpawnDev.BlazorJS.Photino; 4 | /// 5 | /// Handles interop between a Blazor WebAssembly app and the hosting Photino app 6 | /// 7 | public class PhotinoAppDispatcher : RemoteDispatcher, IAsyncBackgroundService 8 | { 9 | Task? _Ready = null; 10 | /// 11 | public Task Ready => _Ready ??= InitAsync(); 12 | BlazorJSRuntime JS; 13 | /// 14 | /// Serialization options used for interop 15 | /// 16 | public JsonSerializerOptions SerializerOptions { get; private set; } = new JsonSerializerOptions(); 17 | ActionCallback? External_OnMessageCallback; 18 | /// 19 | /// Returns true if the app appears to be running in a Photino window 20 | /// 21 | public bool PhotinoFound { get; } 22 | /// 23 | /// This will be the PhotinoBlazorWASMWindow.Id after the Photino app has connected. 24 | /// 25 | public string? WindowId { get; private set; } 26 | /// 27 | /// New instance 28 | /// 29 | /// 30 | /// 31 | public PhotinoAppDispatcher(BlazorJSRuntime js, IServiceProvider serviceProvider) : base(serviceProvider, createNewScope: false) 32 | { 33 | JS = js; 34 | RequireRemoteCallableAttribute = false; 35 | AllowPrivateMethods = true; 36 | AllowSpecialMethods = true; 37 | AllowStaticMethods = true; 38 | AllowNonServiceStaticMethods = true; 39 | PhotinoFound = PhotinoBlazorWASM; 40 | } 41 | static Lazy _PhotinoBlazorWASM = new Lazy(() => 42 | { 43 | return BlazorJSRuntime.JS.IsBrowser == true 44 | && BlazorJSRuntime.JS?.IsUndefined("external?.sendMessage") == false 45 | && BlazorJSRuntime.JS?.IsUndefined("external?.receiveMessage") == false; 46 | }); 47 | /// 48 | /// Returns true if the app appears to be running Blazor WASM in a Photino window 49 | /// 50 | public static bool PhotinoBlazorWASM => _PhotinoBlazorWASM.Value; 51 | async Task InitAsync() 52 | { 53 | if (PhotinoFound) 54 | { 55 | External_OnMessageCallback = new ActionCallback(External_OnMessage); 56 | JS.CallVoid("external.receiveMessage", External_OnMessageCallback); 57 | SendReadyFlag(); 58 | await WhenReady; 59 | WindowId = await Run(s => s.Id); 60 | #if DEBUG 61 | JS.Log($"WindowId: {WindowId}"); 62 | #endif 63 | } 64 | } 65 | async void External_OnMessage(string message) 66 | { 67 | try 68 | { 69 | var args = JsonSerializer.Deserialize>(message, SerializerOptions); 70 | if (args != null) 71 | { 72 | await HandleCall(args); 73 | } 74 | } 75 | catch { } 76 | } 77 | /// 78 | protected override void SendCall(object?[] args) 79 | { 80 | if (!PhotinoFound) return; 81 | try 82 | { 83 | var response = JsonSerializer.Serialize(args, SerializerOptions); 84 | JS.CallVoid("external.sendMessage", response); 85 | } 86 | catch { } 87 | } 88 | /// 89 | public override void Dispose() 90 | { 91 | base.Dispose(); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App.Demo.Client/wwwroot/css/app.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 3 | } 4 | 5 | h1:focus { 6 | outline: none; 7 | } 8 | 9 | a, .btn-link { 10 | color: #0071c1; 11 | } 12 | 13 | .btn-primary { 14 | color: #fff; 15 | background-color: #1b6ec2; 16 | border-color: #1861ac; 17 | } 18 | 19 | .btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { 20 | box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; 21 | } 22 | 23 | .content { 24 | padding-top: 1.1rem; 25 | } 26 | 27 | .valid.modified:not([type=checkbox]) { 28 | outline: 1px solid #26b050; 29 | } 30 | 31 | .invalid { 32 | outline: 1px solid red; 33 | } 34 | 35 | .validation-message { 36 | color: red; 37 | } 38 | 39 | #blazor-error-ui { 40 | background: lightyellow; 41 | bottom: 0; 42 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); 43 | display: none; 44 | left: 0; 45 | padding: 0.6rem 1.25rem 0.7rem 1.25rem; 46 | position: fixed; 47 | width: 100%; 48 | z-index: 1000; 49 | } 50 | 51 | #blazor-error-ui .dismiss { 52 | cursor: pointer; 53 | position: absolute; 54 | right: 0.75rem; 55 | top: 0.5rem; 56 | } 57 | 58 | .blazor-error-boundary { 59 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 60 | padding: 1rem 1rem 1rem 3.7rem; 61 | color: white; 62 | } 63 | 64 | .blazor-error-boundary::after { 65 | content: "An error has occurred." 66 | } 67 | 68 | .loading-progress { 69 | position: relative; 70 | display: block; 71 | width: 8rem; 72 | height: 8rem; 73 | margin: 20vh auto 1rem auto; 74 | } 75 | 76 | .loading-progress circle { 77 | fill: none; 78 | stroke: #e0e0e0; 79 | stroke-width: 0.6rem; 80 | transform-origin: 50% 50%; 81 | transform: rotate(-90deg); 82 | } 83 | 84 | .loading-progress circle:last-child { 85 | stroke: #1b6ec2; 86 | stroke-dasharray: calc(3.141 * var(--blazor-load-percentage, 0%) * 0.8), 500%; 87 | transition: stroke-dasharray 0.05s ease-in-out; 88 | } 89 | 90 | .loading-progress-text { 91 | position: absolute; 92 | text-align: center; 93 | font-weight: bold; 94 | inset: calc(20vh + 3.25rem) 0 auto 0.2rem; 95 | } 96 | 97 | .loading-progress-text:after { 98 | content: var(--blazor-load-percentage-text, "Loading"); 99 | } 100 | 101 | code { 102 | color: #c02d76; 103 | } 104 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/PhotinoBlazorWASMWindow.cs: -------------------------------------------------------------------------------- 1 | using Photino.NET; 2 | using SpawnDev.BlazorJS.Photino.Native; 3 | using System.Text.Json; 4 | 5 | namespace SpawnDev.BlazorJS.Photino; 6 | /// 7 | /// Handles interop between a Photino app and Photino windows hosting Blazor WASM apps. 8 | /// 9 | public class PhotinoBlazorWASMWindow : RemoteDispatcher 10 | { 11 | /// 12 | /// Window Guid as a string 13 | /// 14 | public string Id => Window.Id.ToString(); 15 | /// 16 | /// Photino window 17 | /// 18 | public PhotinoWindow Window { get; } 19 | /// 20 | /// Returns true if the window can be hidden 21 | /// 22 | public bool CanHide => PhotinoWindow.IsWindowsPlatform; 23 | JsonSerializerOptions SerializerOptions; 24 | /// 25 | /// New instance 26 | /// 27 | /// 28 | /// 29 | /// 30 | public PhotinoBlazorWASMWindow(IServiceProvider serviceProvider, PhotinoWindow window, JsonSerializerOptions serializerOptions) : base(serviceProvider, createNewScope: true) 31 | { 32 | Window = window; 33 | SerializerOptions = serializerOptions; 34 | window.WebMessageReceived += HandleMessage; 35 | RequireRemoteCallableAttribute = false; 36 | AllowPrivateMethods = true; 37 | AllowSpecialMethods = true; 38 | AllowStaticMethods = true; 39 | AllowNonServiceStaticMethods = true; 40 | } 41 | /// 42 | /// True if the window is visible 43 | /// 44 | public bool Visible 45 | { 46 | get => _Visible; 47 | set => Show(value); 48 | } 49 | bool _Visible = true; 50 | /// 51 | /// Closes the window 52 | /// 53 | public void Close() 54 | { 55 | Window?.Close(); 56 | } 57 | /// 58 | /// Show or hide the window 59 | /// 60 | /// 61 | public bool Show(bool show) 62 | { 63 | if (PhotinoWindow.IsWindowsPlatform) 64 | { 65 | var hWnd = Window.WindowHandle; 66 | if (show) 67 | { 68 | _Visible = true; 69 | // Show the window and restore it if minimized 70 | NativeMethodsWindows.ShowWindow(hWnd, NativeMethodsWindows.SW_RESTORE); 71 | NativeMethodsWindows.ShowWindow(hWnd, NativeMethodsWindows.SW_SHOW); 72 | } 73 | else 74 | { 75 | _Visible = false; 76 | NativeMethodsWindows.ShowWindow(hWnd, NativeMethodsWindows.SW_HIDE); 77 | } 78 | return true; 79 | } 80 | return false; 81 | } 82 | /// 83 | /// Wait for close (only waits if it starts a message pump, such as the MainWindow)
84 | /// If it doesn't start a message pump, it just starts the window and shows it 85 | ///
86 | public void WaitForClose() 87 | { 88 | Window.WaitForClose(); 89 | } 90 | /// 91 | /// Add this PhotinoWindow and PhotinoBlazorWASMWindow to services this instance can access 92 | /// 93 | /// 94 | /// 95 | protected override async Task GetServiceAsync(Type parameterType) 96 | { 97 | if (parameterType == typeof(PhotinoWindow) || parameterType == typeof(PhotinoWindow)) 98 | { 99 | return Window; 100 | } 101 | else if (parameterType == typeof(PhotinoBlazorWASMWindow)) 102 | { 103 | return this; 104 | } 105 | return await base.GetServiceAsync(parameterType); 106 | } 107 | async void HandleMessage(object? sender, string message) 108 | { 109 | try 110 | { 111 | var args = JsonSerializer.Deserialize>(message, SerializerOptions); 112 | if (args != null) 113 | { 114 | await Task.Run(() => HandleCall(args)); 115 | } 116 | } 117 | catch 118 | { 119 | // invalid message likely 120 | } 121 | } 122 | /// 123 | protected override void SendCall(object?[] args) 124 | { 125 | var response = JsonSerializer.Serialize(args, SerializerOptions); 126 | Window.SendWebMessage(response); 127 | } 128 | /// 129 | public override void Dispose() 130 | { 131 | Window?.Close(); 132 | base.Dispose(); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/JsonElementListExtensions.cs: -------------------------------------------------------------------------------- 1 | using SpawnDev.BlazorJS.Photino; 2 | using System.Text.Json; 3 | 4 | namespace SpawnDev.BlazorJS.Photino 5 | { 6 | /// 7 | /// Adds extension methods to List<JsonElement> 8 | /// 9 | internal static class JsonElementListExtensions 10 | { 11 | static JsonSerializerOptions DefaultJsonSerializerOptions { get; } = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; 12 | /// 13 | /// The ShiftAs method removes the first element from an list and returns that removed deserialized element. This method changes the length of the list. 14 | /// 15 | /// 16 | /// 17 | /// 18 | public static T? Shift(this List _this, JsonSerializerOptions? jsonSerializerOptions = null) 19 | { 20 | if (jsonSerializerOptions == null) jsonSerializerOptions = DefaultJsonSerializerOptions; 21 | var ret = _this[0].Deserialize(jsonSerializerOptions ?? DefaultJsonSerializerOptions); 22 | _this.RemoveAt(0); 23 | return ret; 24 | } 25 | /// 26 | /// The ShiftAs method removes the first element from an list and returns that removed deserialized element. This method changes the length of the list. 27 | /// 28 | /// 29 | /// 30 | /// 31 | /// 32 | public static object? Shift(this List _this, Type type, JsonSerializerOptions? jsonSerializerOptions = null) 33 | { 34 | var ret = _this[0].Deserialize(type, jsonSerializerOptions ?? DefaultJsonSerializerOptions); 35 | _this.RemoveAt(0); 36 | return ret; 37 | } 38 | /// 39 | /// Deserializes the item at the specified index 40 | /// 41 | /// 42 | /// 43 | /// 44 | /// 45 | /// 46 | public static object? Deserialize(this List _this, Type type, int i, JsonSerializerOptions? jsonSerializerOptions = null) => _this[i].Deserialize(type, jsonSerializerOptions ?? DefaultJsonSerializerOptions); 47 | 48 | /// 49 | /// Deserializes the item at the specified index 50 | /// 51 | /// 52 | /// 53 | /// 54 | /// 55 | /// 56 | public static object? GetItem(this List _this, Type type, int i, JsonSerializerOptions? jsonSerializerOptions = null) => _this[i].Deserialize(type, jsonSerializerOptions ?? DefaultJsonSerializerOptions); 57 | 58 | /// 59 | /// Deserializes the item at the specified index 60 | /// 61 | /// 62 | /// 63 | /// 64 | /// 65 | /// 66 | public static object? Get(this List _this, Type type, int i, JsonSerializerOptions? jsonSerializerOptions = null) => _this[i].Deserialize(type, jsonSerializerOptions ?? DefaultJsonSerializerOptions); 67 | /// 68 | /// Deserializes the item at the specified index 69 | /// 70 | /// 71 | /// 72 | /// 73 | /// 74 | /// 75 | public static T? Deserialize(this List _this, int i, JsonSerializerOptions? jsonSerializerOptions = null) => _this[i].Deserialize(jsonSerializerOptions ?? DefaultJsonSerializerOptions); 76 | /// 77 | /// Deserializes the item at the specified index 78 | /// 79 | /// 80 | /// 81 | /// 82 | /// 83 | /// 84 | public static T? Get(this List _this, int i, JsonSerializerOptions? jsonSerializerOptions = null) => _this[i].Deserialize(jsonSerializerOptions ?? DefaultJsonSerializerOptions); 85 | /// 86 | /// Deserializes the item at the specified index 87 | /// 88 | /// 89 | /// 90 | /// 91 | /// 92 | /// 93 | public static T? GetItem(this List _this, int i, JsonSerializerOptions? jsonSerializerOptions = null) => _this[i].Deserialize(jsonSerializerOptions ?? DefaultJsonSerializerOptions); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino.App/WebRootServer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.FileProviders; 4 | using System.Diagnostics; 5 | using System.Net; 6 | using System.Net.NetworkInformation; 7 | 8 | namespace SpawnDev.BlazorJS.Photino 9 | { 10 | /// 11 | /// Simple http server 12 | /// 13 | public class WebRootServer : IWebRootServer 14 | { 15 | /// 16 | /// True if running 17 | /// 18 | public bool Running { get; private set; } 19 | Task? RunningTask = null; 20 | /// 21 | /// The currently served url 22 | /// 23 | public string? Url { get; private set; } 24 | /// 25 | /// The served folder 26 | /// 27 | public string? WwwRootFolder { get; private set; } 28 | /// 29 | /// The WebApplication that is being used to host the files 30 | /// 31 | public WebApplication? WebApplication { get; private set; } 32 | /// 33 | /// Starts the server 34 | /// 35 | /// 36 | public void CreateStaticFileServer(out string baseUrl) 37 | { 38 | CreateStaticFileServer(8000, 100, "wwwroot", out baseUrl); 39 | } 40 | /// 41 | /// Starts the server 42 | /// 43 | /// 44 | /// 45 | public void CreateStaticFileServer(string webRootFolder, out string baseUrl) 46 | { 47 | CreateStaticFileServer(8000, 100, webRootFolder, out baseUrl); 48 | } 49 | /// 50 | /// Starts the server 51 | /// 52 | /// 53 | /// 54 | /// 55 | /// 56 | /// 57 | /// 58 | public void CreateStaticFileServer(int startPort, int portRange, string webRootFolder, out string baseUrl) 59 | { 60 | if (!string.IsNullOrEmpty(Url)) 61 | { 62 | baseUrl = Url; 63 | return; 64 | } 65 | var webRootPath = Path.GetFullPath(webRootFolder); 66 | if (Debugger.IsAttached && webRootFolder == "wwwroot") 67 | { 68 | string? projectDir = null; 69 | var parts = webRootPath.Split(new[] { '/', '\\' }).ToList(); 70 | var pos = parts.LastIndexOf("bin"); 71 | if (pos > -1) 72 | { 73 | parts = parts.Take(pos).ToList(); 74 | projectDir = string.Join("/", parts); 75 | var projectWwwRoot = Path.GetFullPath(Path.Combine(projectDir, webRootFolder)); 76 | if (Directory.Exists(projectWwwRoot)) 77 | { 78 | webRootPath = projectWwwRoot; 79 | } 80 | } 81 | } 82 | if (!Directory.Exists(webRootPath)) 83 | { 84 | throw new DirectoryNotFoundException(nameof(webRootPath)); 85 | } 86 | WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(new WebApplicationOptions 87 | { 88 | Args = Array.Empty(), 89 | WebRootPath = webRootPath 90 | }); 91 | IFileProvider webRootFileProvider = webApplicationBuilder.Environment.WebRootFileProvider; 92 | webApplicationBuilder.Environment.WebRootFileProvider = webRootFileProvider; 93 | int port; 94 | for (port = startPort; IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners().Any((IPEndPoint x) => x.Port == port); port++) 95 | { 96 | if (port > port + portRange) 97 | { 98 | throw new SystemException($"Couldn't find open port within range {port - portRange} - {port}."); 99 | } 100 | } 101 | 102 | baseUrl = $"http://localhost:{port}"; 103 | webApplicationBuilder.WebHost.UseUrls(baseUrl); 104 | WebApplication webApplication = webApplicationBuilder.Build(); 105 | webApplication.UseFileServer(new FileServerOptions() 106 | { 107 | EnableDirectoryBrowsing = true, 108 | FileProvider = webRootFileProvider, 109 | StaticFileOptions = 110 | { 111 | ServeUnknownFileTypes = true, 112 | DefaultContentType = "application/octet-stream" 113 | } 114 | }); 115 | RunningTask = webApplication.RunAsync(); 116 | WebApplication = webApplication; 117 | WwwRootFolder = webRootFolder; 118 | Url = baseUrl; 119 | Running = true; 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpawnDev.BlazorJS.Photino 2 | SpawnDev.BlazorJS.Photino enables running Blazor WebAssembly in [Photino.Net](https://github.com/tryphotino/photino.NET) apps 3 | with 2 way interop. 4 | 5 | ### Nuget Packages 6 | [![NuGet](https://img.shields.io/nuget/dt/SpawnDev.BlazorJS.Photino.App.svg?label=SpawnDev.BlazorJS.Photino.App)](https://www.nuget.org/packages/SpawnDev.BlazorJS.Photino.App) 7 | Add this package in the Photino.Net App to host Blazor WebAssembly windows with shared services. 8 | 9 | [![NuGet](https://img.shields.io/nuget/dt/SpawnDev.BlazorJS.Photino.svg?label=SpawnDev.BlazorJS.Photino)](https://www.nuget.org/packages/SpawnDev.BlazorJS.Photino) 10 | Add this package in Blazor WebAssembly for interop with the shared services running in the Photino.Net app. 11 | 12 | ### Why 13 | > Photino.Blazor already exists, why use this? 14 | 15 | #### Answer 16 | In Photino.Blazor, .Net only runs in the main process. In SpawnDev.BlazorJS.Photino, .Net runs in the main process and in the browser instances, 17 | enabling direct C# access to all of the awesome browser [Web APIs](https://developer.mozilla.org/en-US/docs/Web/API) like WebRTC, Canvas, 18 | WebGL, WEbGPU, etc. directly from C#, **no Javascript required**. See [Blazor WebAssembly libraries](#blazor-webassembly-libraries) 19 | 20 | ### Example 21 | 22 | Photino.Net app 23 | `Program.cs` 24 | ```cs 25 | // Create RemoteServiceProviderBuilder 26 | var appBuilder = PhotinoBlazorWASMAppBuilder.CreateDefault(args); 27 | 28 | // Blazor WebAssembly instances can call these services using expressions or 29 | // an interface DispatchProxy provided by the PhotinoAppDispatcher service 30 | // Singleton services are shared with all windows 31 | // Scoped services are per-window 32 | // Transient are per call 33 | 34 | // The demo uses this service via an interface DispatchProxy 35 | appBuilder.Services.AddSingleton(); 36 | 37 | // build 38 | var app = appBuilder.Build(); 39 | 40 | /// 41 | /// If true, closing the main window will hide it instead of closing it.
42 | /// This allows the app to stay alive until all windows are closed.
43 | /// NOTE: Only supported when PhotinoWindow.IsWindowsPlatform == true
44 | /// Default: false 45 | ///
46 | app.IndependentWindows = false; 47 | 48 | /// 49 | /// If true the app will not exit when there are no windows except invisible MainWindow.
50 | /// Setting this to true is useful for a system tray icon that can be used to create a new window or show the main one.
51 | /// NOTE: Only supported when PhotinoWindow.IsWindowsPlatform == true
52 | /// Default: false 53 | ///
54 | app.InvisibleKeepAlive = false; 55 | 56 | #if DEBUG 57 | // Set the Url where the Blazor WebAssembly dev server is hosting when DEBUG 58 | // if not set, the app's "wwwroot/index.html" path will be used. 59 | // In production a release build of your Blazor WASM app could be served from there. 60 | app.SetAppBaseUri("https://localhost:7174/"); 61 | #endif 62 | 63 | // Start app. Show main window 64 | app.Run(); 65 | ``` 66 | 67 | Blazor WebAssembly app 68 | `Program.cs` 69 | ```cs 70 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 71 | builder.RootComponents.Add("#app"); 72 | builder.RootComponents.Add("head::after"); 73 | 74 | // BlazorJSRuntime (PhotinoAppDispatcher dependency) 75 | builder.Services.AddBlazorJSRuntime(); 76 | 77 | // PhotinoAppDispatcher lets Blazor WASM call into the Photino hosting app (if available) using: 78 | // Expressions: 79 | // var result = await PhotinoAppDispatcher.Run(service => service.SomeMethod(someVariable1, someVariable2)); 80 | // - or - 81 | // Interface DispatchProxy: 82 | // var service = PhotinoAppDispatcher.GetService() where TService : interface 83 | // var result = await service.SomeMethod(someVariable1, someVariable2); 84 | // - or - 85 | // Register Photino host app service interface DispatchProxy and use as a normal service 86 | // (See IConsoleLogger below) 87 | builder.Services.AddSingleton(); 88 | 89 | // This adds IConsoleLogger provided by PhotinoAppDispatcher which will relay all 90 | // async method calls to the Photino app instance via an interface DispatchProxy 91 | builder.Services.AddSingleton(sp => sp.GetRequiredService().GetService()); 92 | 93 | // Start 94 | await builder.Build().BlazorJSRunAsync(); 95 | ``` 96 | 97 | Example usage: 98 | ```razor 99 | Connected to Photino app services: @PhotinoAppDispatcher.IsReady 100 |
101 | 102 | 103 | 104 | @code { 105 | [Inject] 106 | PhotinoAppDispatcher PhotinoAppDispatcher { get; set; } = default!; 107 | 108 | [Inject] 109 | IConsoleLogger ConsoleLogger { get; set; } = default!; 110 | 111 | private async Task OpenWindow() 112 | { 113 | // this calls IConsoleLogger.LogAsync() which relays the call to the Photino host app IConsoleLogger service 114 | await ConsoleLogger.LogAsync(">> Window being opened by " + PhotinoAppDispatcher.WindowId); 115 | 116 | // call PhotinoBlazorWASMApp.OpenWindow() in the Photino host app on the PhotinoBlazorWASMApp service 117 | var windowId = await PhotinoAppDispatcher.Run(s => s.OpenWindow()); 118 | 119 | // this calls IConsoleLogger.LogAsync() which relays the call to the Photino host app IConsoleLogger service 120 | await ConsoleLogger.LogAsync(">> Window opened: " + windowId); 121 | } 122 | 123 | private async Task CloseThisWindow() 124 | { 125 | // this calls IConsoleLogger.LogAsync() which relays the call to the Photino host app IConsoleLogger service 126 | await ConsoleLogger.LogAsync(">> Window closing: " + PhotinoAppDispatcher.WindowId); 127 | 128 | // call PhotinoBlazorWASMWindow.Close() in the Photino host app on this window's PhotinoBlazorWASMWindow instance 129 | await PhotinoAppDispatcher.Run(s => s.Close()); 130 | } 131 | } 132 | ``` 133 | 134 | ### Blazor WebAssembly libraries 135 | Javascript `<->` C# interop is provided by [SpawnDev.BlazorJS](https://github.com/LostBeard/SpawnDev.BlazorJS). 136 | Here are some Blazor WebAssembly libraries ready to use in your next Photino Blazor WebAssembly app. 137 | 138 | 139 | - [TransformersJS](https://github.com/LostBeard/SpawnDev.BlazorJS.TransformersJS) - Use Transformers.js to run pretrained models with the ONNX Runtime 140 | - [WebTorrents](https://github.com/LostBeard/SpawnDev.BlazorJS.WebTorrents) - WebTorrent peer to peer file sharing 141 | - [SocketIO](https://github.com/LostBeard/SpawnDev.BlazorJS.SocketIO) - Socket.IO bidirectional and low-latency communication for every platform 142 | - [PeerJS](https://github.com/LostBeard/SpawnDev.BlazorJS.PeerJS) - PeerJS simplifies peer-to-peer data, video, and audio calls 143 | - [Cryptography](https://github.com/LostBeard/SpawnDev.BlazorJS.Cryptography) - A cross platform cryptography library ECDSA, ECDH, AES-CBC, etc 144 | - [More](https://github.com/LostBeard) - More Blazor WebAssembly projects by LostBeard 145 | - [Nuget Packages](https://www.nuget.org/profiles/LostBeard) - Blazor WebAssembly Nuget packages by LostBeard 146 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd 364 | 365 | # Ignore the publish build of the Balzor WASM app in the Photino apps wwwroot 366 | SpawnDev.BlazorJS.Photino.App.Demo/wwwroot/** 367 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/PhotinoBlazorWASMApp.cs: -------------------------------------------------------------------------------- 1 | using Photino.NET; 2 | using SpawnDev.BlazorJS.Photino.JsonConverters; 3 | using System.Text.Json; 4 | using File = System.IO.File; 5 | 6 | namespace SpawnDev.BlazorJS.Photino; 7 | /// 8 | /// 9 | /// 10 | public class PhotinoBlazorWASMApp 11 | { 12 | IWebRootServer WebRootServer; 13 | //TaskCompletionSource exitTokenSource = new TaskCompletionSource(); 14 | /// 15 | /// Returns the window count 16 | /// 17 | /// 18 | public int GetWindowCount() 19 | { 20 | return Windows.Count; 21 | } 22 | /// 23 | /// Active windows 24 | /// 25 | public List Windows { get; } = new List(); 26 | /// 27 | /// Serialization options used for interop 28 | /// 29 | public JsonSerializerOptions SerializerOptions { get; private set; } = new JsonSerializerOptions(); 30 | /// 31 | /// Service provider 32 | /// 33 | public IServiceProvider Services { get; private set; } 34 | /// 35 | /// New instance 36 | /// 37 | /// 38 | /// 39 | public PhotinoBlazorWASMApp(IServiceProvider serviceProvider, IWebRootServer webRootServer) 40 | { 41 | WebRootServer = webRootServer; 42 | Services = serviceProvider; 43 | SerializerOptions.Converters.Add(new IntPtrJsonConverter()); 44 | SerializerOptions.Converters.Add(new ClaimsIdentityConverter()); 45 | } 46 | /// 47 | /// Returns true if running 48 | /// 49 | public bool Running { get; private set; } 50 | /// 51 | /// Starts the root window 52 | /// 53 | public void Run() 54 | { 55 | if (Running) return; 56 | Running = true; 57 | if (MainWindow == null) 58 | { 59 | OpenWindow(); 60 | } 61 | MainWindow!.WaitForClose(); 62 | // wait for all windows to close 63 | //exitTokenSource.Task.Wait(); 64 | } 65 | PhotinoBlazorWASMWindow AddWindow(PhotinoWindow window) 66 | { 67 | var instance = Windows.FirstOrDefault(x => x.Window == window); 68 | if (instance != null) return instance; 69 | instance = new PhotinoBlazorWASMWindow(Services, window, SerializerOptions); 70 | Windows.Add(instance); 71 | window.WindowClosing += Window_WindowClosing; 72 | return instance; 73 | } 74 | /// 75 | /// If true, closing the main window will hide it instead of closing it.
76 | /// This allows the app to stay alive until all windows are closed.
77 | /// NOTE: Only supported when PhotinoWindow.IsWindowsPlatform == true
78 | /// Default: false 79 | ///
80 | public bool IndependentWindows 81 | { 82 | get => _IndependentWindows; 83 | set 84 | { 85 | if (_IndependentWindows == value) return; 86 | if (PhotinoWindow.IsWindowsPlatform) 87 | { 88 | _IndependentWindows = value; 89 | } 90 | } 91 | } 92 | bool _IndependentWindows = false; 93 | /// 94 | /// If true the app will not exit when there are no windows except invisible MainWindow.
95 | /// Setting this to true is useful for a system tray icon that can be used to create a new window or show the main one.
96 | /// NOTE: Only supported when PhotinoWindow.IsWindowsPlatform == true
97 | /// Default: false 98 | ///
99 | public bool InvisibleKeepAlive 100 | { 101 | get => _InvisibleKeepAlive; 102 | set 103 | { 104 | if (_InvisibleKeepAlive == value) return; 105 | if (PhotinoWindow.IsWindowsPlatform) 106 | { 107 | _InvisibleKeepAlive = value; 108 | } 109 | } 110 | } 111 | bool _InvisibleKeepAlive = false; 112 | private bool Window_WindowClosing(object sender, EventArgs e) 113 | { 114 | var cancelClose = false; 115 | var photinoWindow = (PhotinoWindow)sender!; 116 | if (photinoWindow == MainWindow?.Window) 117 | { 118 | if (IndependentWindows && MainWindow.CanHide && MainWindow.Visible) 119 | { 120 | // cancel the close and just hide the main window (only supported on Windows) 121 | // I read that on Mac OS, the main window can be safely closed and the other windows will still work 122 | MainWindow.Visible = false; 123 | cancelClose = true; 124 | return cancelClose; 125 | } 126 | } 127 | RemoveWindow(photinoWindow); 128 | return cancelClose; 129 | } 130 | /// 131 | /// The first Uri of the first window opened (root window) AppUri if not already set.
132 | /// used for new windows 133 | ///
134 | public Uri? AppBaseUri { get; private set; } 135 | /// 136 | /// Set the app's base Uri 137 | /// 138 | /// 139 | public void SetAppBaseUri(string path) 140 | { 141 | Log(".Load(" + path + ")"); 142 | if (path.Contains("http://") || path.Contains("https://")) 143 | { 144 | SetAppBaseUri(new Uri(path)); 145 | return; 146 | } 147 | string text = Path.GetFullPath(path); 148 | if (!File.Exists(text) && !Directory.Exists(text)) 149 | { 150 | text = AppContext.BaseDirectory + "/" + path; 151 | if (File.Exists(AppContext.BaseDirectory + "/" + path) || Directory.Exists(AppContext.BaseDirectory + "/" + path)) 152 | { 153 | text = AppContext.BaseDirectory + "/" + path; 154 | } 155 | } 156 | SetAppBaseUri(new Uri(text, UriKind.Absolute)); 157 | } 158 | /// 159 | /// Set the app's base Uri 160 | /// 161 | public void SetAppBaseUri(Uri path) 162 | { 163 | var appUri = GetAppUri(path); 164 | if (appUri != null) 165 | { 166 | AppBaseUri = appUri; 167 | } 168 | } 169 | /// 170 | /// Get the Uri, relative to the AppBaseUri if the given uri is relative 171 | /// 172 | /// 173 | /// 174 | public Uri? GetAppUri(Uri path) 175 | { 176 | if (!path.IsAbsoluteUri) 177 | { 178 | if (AppBaseUri == null) 179 | { 180 | var text = Path.GetFullPath(path.ToString()); 181 | if (!File.Exists(text)) 182 | { 183 | text = AppContext.BaseDirectory + "/" + path; 184 | if (!File.Exists(text)) 185 | { 186 | Log(" ** File \"" + path + "\" could not be found."); 187 | return null; 188 | } 189 | } 190 | path = new Uri(text, UriKind.Absolute); 191 | } 192 | else 193 | { 194 | path = new Uri(AppBaseUri, path); 195 | } 196 | } 197 | return path; 198 | } 199 | void Log(string msg) 200 | { 201 | Console.WriteLine(msg); 202 | } 203 | /// 204 | /// Main window 205 | /// 206 | public PhotinoBlazorWASMWindow? MainWindow => Windows.FirstOrDefault(); 207 | /// 208 | /// All windows that are not main 209 | /// 210 | public List NonMainWindows => Windows.Where(o => o != MainWindow).ToList(); 211 | /// 212 | /// Visible windows 213 | /// 214 | public List VisibleWindows => Windows.Where(o => o.Visible).ToList(); 215 | /// 216 | /// Create the main window 217 | /// 218 | /// 219 | PhotinoBlazorWASMWindow CreateMainWindow() 220 | { 221 | if (MainWindow == null) 222 | { 223 | if (AppBaseUri == null) SetAppBaseUri("wwwroot"); 224 | if (AppBaseUri!.Scheme == "file") 225 | { 226 | var localPath = AppBaseUri.LocalPath; 227 | // start http server so we can use http instead of file or Blazor will fail to load and some features will not work 228 | WebRootServer.CreateStaticFileServer(localPath, out string baseUrl); 229 | SetAppBaseUri(baseUrl); 230 | } 231 | var window = new PhotinoWindow() 232 | .Load(AppBaseUri); 233 | AddWindow(window); 234 | } 235 | return MainWindow!; 236 | } 237 | /// 238 | /// Open new app window 239 | /// 240 | /// 241 | /// 242 | public string OpenWindow() 243 | { 244 | if (MainWindow == null) 245 | { 246 | return CreateMainWindow().Id; 247 | } 248 | if (MainWindow == null) throw new Exception($"{nameof(MainWindow)} not set"); 249 | var cts = new TaskCompletionSource(); 250 | MainWindow!.Window.Invoke(() => 251 | { 252 | var window = new PhotinoWindow() 253 | .SetTitle(""); 254 | window.Load(AppBaseUri); 255 | var win = AddWindow(window); 256 | cts.SetResult(win.Id); 257 | win.WaitForClose(); 258 | }); 259 | var id = cts.Task.Result; 260 | return id; 261 | } 262 | /// 263 | /// Open window at the specified url 264 | /// 265 | /// 266 | /// 267 | /// 268 | public string OpenWindow(Uri url) 269 | { 270 | if (url == null) throw new Exception($"{nameof(url)} not set"); 271 | if (MainWindow == null) 272 | { 273 | SetAppBaseUri(url); 274 | return CreateMainWindow().Id; 275 | } 276 | var cts = new TaskCompletionSource(); 277 | MainWindow!.Window.Invoke(() => 278 | { 279 | var window = new PhotinoWindow() 280 | .SetTitle(""); 281 | window.Load(url); 282 | var win = AddWindow(window); 283 | cts.SetResult(win.Id); 284 | win.WaitForClose(); 285 | }); 286 | var id = cts.Task.Result; 287 | return id; 288 | } 289 | /// 290 | /// Returns the PhotinoBlazorWASMWindow that owns the given PhotinoWindow, or null if not found 291 | /// 292 | /// 293 | /// 294 | public PhotinoBlazorWASMWindow? GetBlazorWASMWindow(PhotinoWindow window) => Windows.FirstOrDefault(x => x.Window == window); 295 | void RemoveWindow(PhotinoWindow window) 296 | { 297 | var instance = Windows.FirstOrDefault(x => x.Window == window); 298 | if (instance == null) return; 299 | RemoveWindow(instance); 300 | } 301 | void RemoveWindow(PhotinoBlazorWASMWindow instance) 302 | { 303 | if (Windows.Contains(instance)) 304 | { 305 | if (instance != MainWindow) 306 | { 307 | Windows.Remove(instance); 308 | instance.Window.WindowClosing -= Window_WindowClosing; 309 | instance.Dispose(); 310 | //if (!NonMainWindows.Any() && RootWindowFauxClosed) 311 | //{ 312 | // exitTokenSource.TrySetResult(); 313 | //} 314 | if (!NonMainWindows.Any() && MainWindow?.Visible != true && !InvisibleKeepAlive) 315 | { 316 | // no other windows and main window is not visible and InvisibleKeepAlive == false 317 | MainWindow!.Dispose(); 318 | } 319 | } 320 | else 321 | { 322 | // when the root window is closed, all windows need to 323 | // be closed to prevent orphaned windows from freezing 324 | foreach (var win in NonMainWindows.ToList()) 325 | { 326 | win.Close(); 327 | } 328 | } 329 | } 330 | } 331 | } 332 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/AsyncCallDispatcherSlim.cs: -------------------------------------------------------------------------------- 1 | using SpawnDev.BlazorJS.WebWorkers; 2 | using System.Linq.Expressions; 3 | using System.Reflection; 4 | 5 | namespace SpawnDev.BlazorJS.Photino 6 | { 7 | /// 8 | /// A slimmed down version of AsyncCallDispatcher
9 | /// Supports GetService interface proxies and Run expressions for method calls only (not getters or setters.) 10 | ///
11 | public abstract class AsyncCallDispatcherSlim 12 | { 13 | /// 14 | /// All calls are handled by this method.
15 | /// Usually serialized, and sent somewhere else to be ran. 16 | ///
17 | /// 18 | /// 19 | /// 20 | /// 21 | protected abstract Task Call(Type serviceType, MethodInfo methodInfo, object?[]? args = null); 22 | 23 | #region Expressions 24 | /// 25 | /// Converts an Expression into a MethodInfo and a call arguments array
26 | /// Then calls DispatchCall with them 27 | ///
28 | /// 29 | /// 30 | /// 31 | /// 32 | protected Task CallStatic(Expression expr, object?[]? argsExt = null) 33 | { 34 | if (expr is MethodCallExpression methodCallExpression) 35 | { 36 | var methodInfo = methodCallExpression.Method; 37 | var serviceType = methodInfo.ReflectedType; 38 | var args = methodCallExpression.Arguments.Select(arg => Expression.Lambda>(Expression.Convert(arg, typeof(object)), null).Compile()()).ToArray(); 39 | return Call(serviceType!, methodInfo, args); 40 | } 41 | else if (expr is MemberExpression memberExpression) 42 | { 43 | if (argsExt == null || argsExt.Length == 0) 44 | { 45 | // get call 46 | if (memberExpression.Member is PropertyInfo propertyInfo) 47 | { 48 | var methodInfo = propertyInfo.GetMethod; 49 | if (methodInfo == null) 50 | { 51 | throw new Exception("Property getter does not exist."); 52 | } 53 | var serviceType = methodInfo.ReflectedType; 54 | return Call(serviceType!, methodInfo); 55 | } 56 | else if (memberExpression.Member is FieldInfo fieldInfo) 57 | { 58 | throw new Exception("Fields are not supported. Properties are supported."); 59 | } 60 | throw new Exception("Property getter does not exist."); 61 | } 62 | else 63 | { 64 | // set call 65 | if (memberExpression.Member is PropertyInfo propertyInfo) 66 | { 67 | var methodInfo = propertyInfo.SetMethod; 68 | if (methodInfo == null) 69 | { 70 | throw new Exception("Property setter does not exist."); 71 | } 72 | var serviceType = methodInfo.ReflectedType; 73 | return Call(serviceType!, methodInfo, argsExt); 74 | } 75 | else if (memberExpression.Member is FieldInfo fieldInfo) 76 | { 77 | throw new Exception("Fields are not supported. Properties are supported."); 78 | } 79 | throw new Exception("Property setter does not exist."); 80 | } 81 | } 82 | else if (expr is NewExpression newExpression) 83 | { 84 | throw new Exception("Run does not support constructors. Use New()"); 85 | } 86 | else 87 | { 88 | throw new Exception($"Unsupported dispatch call: {expr.GetType().Name}"); 89 | } 90 | } 91 | /// 92 | /// Converts an Expression into a MethodInfo and a call arguments array
93 | /// Then calls DispatchCall with them 94 | ///
95 | /// 96 | /// 97 | /// 98 | /// 99 | /// 100 | protected Task Call(Type serviceType, Expression expr, object?[]? argsExt = null) 101 | { 102 | if (expr is MethodCallExpression methodCallExpression) 103 | { 104 | var methodInfo = methodCallExpression.Method; 105 | var args = methodCallExpression.Arguments.Select(arg => Expression.Lambda>(Expression.Convert(arg, typeof(object)), null).Compile()()).ToArray(); 106 | return Call(serviceType, methodInfo, args); 107 | } 108 | else if (expr is MemberExpression memberExpression) 109 | { 110 | if (argsExt == null || argsExt.Length == 0) 111 | { 112 | // get call 113 | if (memberExpression.Member is PropertyInfo propertyInfo) 114 | { 115 | var methodInfo = propertyInfo.GetMethod; 116 | if (methodInfo == null) 117 | { 118 | throw new Exception("Property getter does not exist."); 119 | } 120 | return Call(serviceType, methodInfo); 121 | } 122 | else if (memberExpression.Member is FieldInfo fieldInfo) 123 | { 124 | throw new Exception("Fields are not supported. Properties are supported."); 125 | } 126 | throw new Exception("Property getter does not exist."); 127 | } 128 | else 129 | { 130 | // set call 131 | if (memberExpression.Member is PropertyInfo propertyInfo) 132 | { 133 | var methodInfo = propertyInfo.SetMethod; 134 | if (methodInfo == null) 135 | { 136 | throw new Exception("Property setter does not exist."); 137 | } 138 | return Call(serviceType, methodInfo, argsExt); 139 | } 140 | else if (memberExpression.Member is FieldInfo fieldInfo) 141 | { 142 | throw new Exception("Fields are not supported. Properties are supported."); 143 | } 144 | throw new Exception("Property setter does not exist."); 145 | } 146 | } 147 | else if (expr is NewExpression newExpression) 148 | { 149 | throw new Exception("Run does not support constructors. Use New()"); 150 | } 151 | else 152 | { 153 | throw new Exception($"Unsupported dispatch call: {expr.GetType().Name}"); 154 | } 155 | } 156 | 157 | #region Non-Keyed 158 | // Static 159 | // Method Calls 160 | // Action 161 | /// 162 | /// Call a method or get the value of a property 163 | /// 164 | /// 165 | /// 166 | public async Task Run(Expression expr) => await CallStatic(expr.Body); 167 | // Func 168 | /// 169 | /// Call a method or get the value of a property 170 | /// 171 | /// 172 | /// 173 | public async Task Run(Expression> expr) => await CallStatic(expr.Body); 174 | // Func 175 | /// 176 | /// Call a method or get the value of a property 177 | /// 178 | /// 179 | /// 180 | public async Task Run(Expression> expr) => await CallStatic(expr.Body); 181 | // Func<...,TResult> 182 | /// 183 | /// Call a method or get the value of a property 184 | /// 185 | /// 186 | /// 187 | /// 188 | public async Task Run(Expression> expr) => (TResult)(await CallStatic(expr.Body))!; 189 | // Func<...,Task> 190 | /// 191 | /// Call a method or get the value of a property 192 | /// 193 | /// 194 | /// 195 | /// 196 | public async Task Run(Expression>> expr) => (TResult)(await CallStatic(expr.Body))!; 197 | // Func<...,ValueTask> 198 | /// 199 | /// Call a method or get the value of a property 200 | /// 201 | /// 202 | /// 203 | /// 204 | public async Task Run(Expression>> expr) => (TResult)(await CallStatic(expr.Body))!; 205 | // Property set 206 | /// 207 | /// Set a property value 208 | /// 209 | /// 210 | /// 211 | /// 212 | /// 213 | public async Task Set(Expression> expr, TProperty value) => await CallStatic(expr.Body, new object[] { value }); 214 | 215 | // Instance 216 | // Method Calls and Property Getters 217 | // Action 218 | /// 219 | /// Call a service method or get the value of a service property 220 | /// 221 | /// 222 | /// 223 | /// 224 | public async Task Run(Expression> expr) => await Call(typeof(TInstance), expr.Body); 225 | // Func 226 | /// 227 | /// Call a service method or get the value of a service property 228 | /// 229 | /// 230 | /// 231 | /// 232 | public async Task Run(Expression> expr) => await Call(typeof(TInstance), expr.Body); 233 | // Func 234 | /// 235 | /// Call a service method or get the value of a service property 236 | /// 237 | /// 238 | /// 239 | /// 240 | public async Task Run(Expression> expr) => await Call(typeof(TInstance), expr.Body); 241 | // Func<...,TResult> 242 | /// 243 | /// Call a service method or get the value of a service property 244 | /// 245 | /// 246 | /// 247 | /// 248 | /// 249 | public async Task Run(Expression> expr) => (TResult)(await Call(typeof(TInstance), expr.Body))!; 250 | // Func<...,Task> 251 | /// 252 | /// Call a service method or get the value of a service property 253 | /// 254 | /// 255 | /// 256 | /// 257 | /// 258 | public async Task Run(Expression>> expr) => (TResult)(await Call(typeof(TInstance), expr.Body))!; 259 | // Func<...,ValueTask> 260 | /// 261 | /// Call a service method or get the value of a service property 262 | /// 263 | /// 264 | /// 265 | /// 266 | /// 267 | public async Task Run(Expression>> expr) => (TResult)(await Call(typeof(TInstance), expr.Body))!; 268 | // Property set 269 | /// 270 | /// Set a service property value 271 | /// 272 | /// 273 | /// 274 | /// 275 | /// 276 | /// 277 | public async Task Set(Expression> expr, TProperty value) => await Call(typeof(TInstance), expr.Body, new object[] { value }); 278 | #endregion 279 | #endregion 280 | 281 | #region DispatchProxy 282 | Dictionary ServiceInterfaces = new Dictionary(); 283 | /// 284 | /// Returns a service call dispatcher that can call async methods using the returned interface 285 | /// 286 | /// 287 | /// 288 | public TServiceInterface GetService() where TServiceInterface : class 289 | { 290 | var typeofT = typeof(TServiceInterface); 291 | if (ServiceInterfaces.TryGetValue(typeofT, out var serviceWorker)) return (TServiceInterface)serviceWorker; 292 | var ret = InterfaceCallDispatcher.CreateInterfaceDispatcher(Call); 293 | ServiceInterfaces[typeofT] = ret; 294 | return ret; 295 | } 296 | #endregion 297 | } 298 | } 299 | -------------------------------------------------------------------------------- /SpawnDev.BlazorJS.Photino/RemoteDispatcher.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using SpawnDev.BlazorJS; 3 | using SpawnDev.BlazorJS.WebWorkers; 4 | using System.Reflection; 5 | using System.Security.Claims; 6 | using System.Text.Json; 7 | using System.Text.RegularExpressions; 8 | using MessagePackList = System.Collections.Generic.List; 9 | 10 | namespace SpawnDev.BlazorJS.Photino 11 | { 12 | /// 13 | /// Client and server implementation for remotely calling .Net methods 14 | /// 15 | public abstract class RemoteDispatcher : AsyncCallDispatcherSlim, IDisposable 16 | { 17 | /// 18 | /// This ClaimsPrincipal can be used to store identity information on the remote instance 19 | /// 20 | public ClaimsPrincipal User { get; protected set; } = new ClaimsPrincipal(new ClaimsIdentity(nameof(RemoteDispatcher), ClaimTypes.Name, ClaimTypes.Role)); 21 | /// 22 | /// WhenReady source 23 | /// 24 | protected TaskCompletionSource WhenReadySource { get; set; } = new TaskCompletionSource(); 25 | /// 26 | /// Completes when connected and ready state has been reached. 27 | /// 28 | public Task WhenReady => WhenReadySource.Task; 29 | /// 30 | /// Returns true if connected and ready state has been reached. 31 | /// 32 | public bool IsReady => WhenReady.IsCompletedSuccessfully; 33 | /// 34 | /// Service provider scope 35 | /// 36 | protected IServiceScope? ServiceProviderScope { get; private set; } = null; 37 | /// 38 | /// Scoped service provider 39 | /// 40 | protected IServiceProvider ScopedServiceProvider { get; private set; } 41 | private Dictionary> waitingResponse = new Dictionary>(); 42 | private object waitingResponseLock = new object(); 43 | /// 44 | /// 45 | /// 46 | protected bool InheritAttributes { get; set; } = true; 47 | /// 48 | /// If set to true, calls from the remote peer onto this peer are enabled
49 | /// Per call access, if enabled, will apply 50 | ///
51 | protected bool ServeEnabled { get; set; } = true; 52 | /// 53 | /// If false, static methods cannot be called 54 | /// 55 | protected bool AllowStaticMethods { get; set; } = true; 56 | /// 57 | /// If false, protected methods cannot be called 58 | /// 59 | protected bool AllowPrivateMethods { get; set; } = true; 60 | /// 61 | /// If true, static methods in non-service types can be called.
62 | ///
63 | protected bool AllowNonServiceStaticMethods { get; set; } = true; 64 | /// 65 | /// If true, special methods (like getters and setters) will be allowed 66 | /// 67 | protected bool AllowSpecialMethods { get; set; } = false; 68 | /// 69 | /// If true, the RemoteCallable attribute must be present on the method or the containing class 70 | /// 71 | protected bool RequireRemoteCallableAttribute { get; set; } = true; 72 | /// 73 | /// Returns true if this instance has been disposed 74 | /// 75 | public bool IsDisposed { get; protected set; } 76 | public JsonSerializerOptions JsonSerializerOptions { get; } = new JsonSerializerOptions { }; 77 | public RemoteDispatcher(IServiceProvider serviceProvider, JsonSerializerOptions? jsonSerializerOptions = null, bool createNewScope = true) 78 | { 79 | //ServiceDescriptors = serviceProvider.GetRequiredService(); 80 | if (jsonSerializerOptions != null) JsonSerializerOptions = jsonSerializerOptions; 81 | if (createNewScope) 82 | { 83 | ServiceProviderScope = serviceProvider.CreateScope(); 84 | ScopedServiceProvider = ServiceProviderScope.ServiceProvider; 85 | } 86 | else 87 | { 88 | ScopedServiceProvider = serviceProvider; 89 | } 90 | } 91 | /// 92 | /// This method should be called when the connection is closed 93 | /// 94 | protected void ResetWhenReady() 95 | { 96 | NeedRemoteReadyFlag = true; 97 | if (WhenReadySource.Task.IsCompleted) 98 | WhenReadySource = new TaskCompletionSource(); 99 | CancelAllWaitingRequests("Tray reset"); 100 | ReadyStateChanged?.Invoke(this); 101 | } 102 | /// 103 | /// This method will be called with the call data
104 | /// The inheriting class should pass the call to the remote side where it will be imported via HandleCall as an Array 105 | ///
106 | /// 107 | protected abstract void SendCall(object?[] args); 108 | /// 109 | /// This should be called when the connection is established or after creation if already established 110 | /// 111 | protected virtual void SendReadyFlag() => SendCall(new object?[] { RemoteDispatcherMessageType.ReadyFlag, NeedRemoteReadyFlag, GetReadyFlagData() }); 112 | 113 | protected virtual object? GetReadyFlagData() => null; 114 | 115 | public event Action ReadyStateChanged; 116 | protected bool NeedRemoteReadyFlag { get; set; } = true; 117 | protected virtual async Task ReadyFlagReceived() 118 | { 119 | 120 | return null; 121 | } 122 | protected virtual async Task ReadyFlagResultReceived() 123 | { 124 | 125 | } 126 | public enum RemoteDispatcherMessageType 127 | { 128 | Unknown, 129 | Message, // "." 130 | Call, // "?" 131 | Response, // "=" 132 | ReadyFlag, // "!" 133 | ReadyFlagResult,// "+" 134 | } 135 | /// 136 | /// The inheriting class must call this method with the incoming message
137 | /// msg is an Array the resides in the Javascript environment 138 | ///
139 | /// 140 | /// 141 | protected async Task HandleCall(MessagePackList msg) 142 | { 143 | { 144 | try 145 | { 146 | var msgType = msg.Shift(); 147 | switch (msgType) 148 | { 149 | case RemoteDispatcherMessageType.Message: 150 | await HandleCall(msg, false); 151 | return; 152 | case RemoteDispatcherMessageType.Call: 153 | await HandleCall(msg, true); 154 | return; 155 | case RemoteDispatcherMessageType.Response: 156 | HandleReply(msg); 157 | return; 158 | case RemoteDispatcherMessageType.ReadyFlag: 159 | NeedRemoteReadyFlag = false; 160 | var remoteNeedsReadyFlag = msg.Shift(); 161 | if (remoteNeedsReadyFlag) SendReadyFlag(); 162 | var ret = await ReadyFlagReceived(); 163 | SendCall(new object?[] { RemoteDispatcherMessageType.ReadyFlagResult, ret }); 164 | return; 165 | case RemoteDispatcherMessageType.ReadyFlagResult: 166 | try 167 | { 168 | await ReadyFlagResultReceived(); 169 | if (!WhenReady.IsCompleted) 170 | { 171 | Console.WriteLine("IsReady set"); 172 | WhenReadySource.TrySetResult(); 173 | ReadyStateChanged?.Invoke(this); 174 | } 175 | } 176 | catch 177 | { 178 | 179 | } 180 | return; 181 | } 182 | //if (DynamicCallables.TryGetValue(((int)msgType), out var dynamicCallable)) 183 | //{ 184 | // await dynamicCallable(msg); 185 | //} 186 | } 187 | catch (Exception ex) 188 | { 189 | Console.WriteLine($"DataConnection_OnData: {ex.Message}"); 190 | } 191 | } 192 | } 193 | /// 194 | /// This method will be called be a call is sent to the remote dispatcher
195 | /// If this method returns a non-empty string an exception will be thrown aborting the call 196 | ///
197 | /// 198 | /// 199 | /// 200 | protected virtual async Task PreCallCheck(MethodInfo methodInfo, object?[]? args = null) 201 | { 202 | return null; 203 | } 204 | /// 205 | /// 206 | /// 207 | /// 208 | /// 209 | /// 210 | /// 211 | /// 212 | protected override async Task Call(Type serviceType, MethodInfo methodInfo, object?[]? args) 213 | { 214 | if (!IsReady) throw new Exception("Connection not ready"); 215 | var callError = await PreCallCheck(methodInfo, args); 216 | if (!string.IsNullOrEmpty(callError)) throw new Exception($"DispatchCall error: {callError}"); 217 | object? retValue = null; 218 | var methodInfoSerialized = SerializableMethodInfoSlim.SerializeMethodInfo(methodInfo); 219 | var serviceTypeName = TypeExtensions.GetFullName(serviceType); 220 | var msgId = Guid.NewGuid().ToString(); 221 | var outArgs = await PreSerializeArgs(msgId, methodInfo, args); 222 | var remoteCallableAttribute = methodInfo.GetCustomAttribute(true); 223 | var resultRequested = remoteCallableAttribute == null || !remoteCallableAttribute.NoReply; 224 | try 225 | { 226 | SendCall(new object?[] 227 | { 228 | resultRequested ? RemoteDispatcherMessageType.Call : RemoteDispatcherMessageType.Message, 229 | msgId, 230 | serviceTypeName, 231 | methodInfoSerialized, 232 | outArgs 233 | }); 234 | if (resultRequested) 235 | { 236 | var tcs = new TaskCompletionSource(); 237 | lock (waitingResponseLock) 238 | waitingResponse.Add(msgId, tcs); 239 | var finalReturnType = methodInfo.GetFinalReturnType(); 240 | var ret = await tcs.Task; 241 | var retError = ret.Shift(); 242 | if (!string.IsNullOrEmpty(retError)) 243 | { 244 | var error = DeserializeException(retError); 245 | throw error; 246 | } 247 | if (finalReturnType != typeof(void)) 248 | { 249 | // custom deserialization of result if needed 250 | retValue = await PostDeserializeArgument(msgId, methodInfo, methodInfo.ReturnParameter, true, ret, 0); 251 | } 252 | } 253 | return retValue; 254 | } 255 | finally 256 | { 257 | StartRequestCleanup(msgId); 258 | } 259 | } 260 | protected void CancelAllWaitingRequests(string message) => CancelAllWaitingRequests(new Exception(message)); 261 | protected void CancelAllWaitingRequests(Exception? exception = null) 262 | { 263 | exception ??= new TargetException(); 264 | 265 | lock (waitingResponseLock) 266 | { 267 | foreach (var waiting in waitingResponse.Values) 268 | { 269 | waiting.TrySetException(exception); 270 | } 271 | waitingResponse.Clear(); 272 | } 273 | } 274 | /// 275 | /// Disposes resources 276 | /// 277 | public virtual void Dispose() 278 | { 279 | if (IsDisposed) return; 280 | IsDisposed = true; 281 | ServiceProviderScope?.Dispose(); 282 | CancelAllWaitingRequests(); 283 | } 284 | /// 285 | /// This method should return an error string or throw an exception if the call pre-check fails
286 | /// This method can be overridden to alter call permissions. It is recommended to use the Allow* bool properties for most uses.
287 | ///
288 | /// 289 | /// 290 | /// 291 | /// 292 | /// 293 | protected virtual async Task CanCallCheck(MethodInfo methodInfo, RemoteCallableAttribute? remoteCallableAttr, object? instance) 294 | { 295 | if (!AllowNonServiceStaticMethods && instance == null && methodInfo.IsStatic) 296 | { 297 | return "HandleCallError: Access denied to static method on non-service"; 298 | } 299 | if (!AllowSpecialMethods && methodInfo.IsSpecialName) 300 | { 301 | return "HandleCallError: Access denied to special methods"; 302 | } 303 | if (!AllowPrivateMethods && methodInfo.IsPrivate) 304 | { 305 | return "HandleCallError: Access denied protected method"; 306 | } 307 | if (!AllowStaticMethods && methodInfo.IsStatic) 308 | { 309 | return "HandleCallError: Access denied static method"; 310 | } 311 | if (RequireRemoteCallableAttribute && remoteCallableAttr == null) 312 | { 313 | return "HandleCallError: Access denied not RemoteCallable"; 314 | } 315 | return null; 316 | } 317 | /// 318 | /// This method is called when a parameter is marked with [FromLocal] is a called method to populate the argument with the local variable.
319 | /// This method can be overridden to provide access to types not registered to the service provider. 320 | ///
321 | /// 322 | /// 323 | protected virtual async Task ResolveLocalInstance(Type parameterType) 324 | { 325 | if (typeof(RemoteDispatcher).IsAssignableFrom(parameterType)) 326 | { 327 | return this; 328 | } 329 | return parameterType.GetDefaultValue(); 330 | } 331 | protected async Task PreSerializeArgument(string msgId, MethodInfo methodInfo, ParameterInfo parameterInfo, bool isReturnValue, object? value, int paramIndex) 332 | { 333 | object? ret = null; 334 | var attributes = parameterInfo.GetCustomAttributes(InheritAttributes).Cast().ToArray(); 335 | var methodParamType = parameterInfo.ParameterType; 336 | #if NET8_0_OR_GREATER 337 | var fromKeyedServicesAttr = attributes.FirstOrDefault(o => o is FromKeyedServicesAttribute); 338 | if (fromKeyedServicesAttr != null) return ret; 339 | #endif 340 | var fromServicesAttr = attributes.FirstOrDefault(o => o is FromServicesAttribute); 341 | if (fromServicesAttr != null) return ret; 342 | var fromLocalAttr = attributes.FirstOrDefault(o => o is FromLocalAttribute); 343 | if (fromLocalAttr != null) return ret; 344 | Type? genericType = null; 345 | if (methodParamType.IsGenericTypeDefinition) genericType = methodParamType; 346 | else if (methodParamType.IsGenericType) genericType = methodParamType.GetGenericTypeDefinition(); 347 | var coreType = genericType ?? methodParamType; 348 | // custom serialization can be done here tp package args![i] 349 | if (value is CancellationToken token) 350 | { 351 | if (token.IsCancellationRequested) 352 | { 353 | // "" represents an already cancelled token 354 | ret = ""; 355 | } 356 | else if (token.CanBeCanceled) 357 | { 358 | // a token id will be sent which can be referenced later to cancel the token 359 | // listen for the token cancellation event and send the cancel request at that time 360 | var tokenId = Guid.NewGuid().ToString(); 361 | token.Register(() => 362 | { 363 | try 364 | { 365 | SendCall(new object?[] { tokenId }); 366 | } 367 | catch { } 368 | }); 369 | ret = tokenId; 370 | } 371 | else 372 | { 373 | // null represents CancellationToken.None (the default) 374 | ret = null; 375 | } 376 | } 377 | else if (value is Delegate argDelegate) 378 | { 379 | var genericTypes = methodParamType.GenericTypeArguments; 380 | if (IsAction(coreType)) 381 | { 382 | var actionParameterTypes = argDelegate.Method.GetParameters().Select(o => o.ParameterType).ToArray(); 383 | var actionId = Guid.NewGuid().ToString(); 384 | AddDynamicCallable(msgId, actionId, async (msg) => 385 | { 386 | var actionArgs = new object?[actionParameterTypes.Length]; 387 | if (actionArgs.Length > 0) 388 | { 389 | var argsLength = msg.Count; 390 | if (actionArgs.Length != argsLength) 391 | { 392 | throw new Exception("Invalid argument count on Action callback"); 393 | } 394 | for (var n = 0; n < actionArgs.Length; n++) 395 | { 396 | // TODO - use post-deserialize 397 | actionArgs[n] = msg.GetItem(actionParameterTypes[n], n); 398 | } 399 | } 400 | argDelegate.DynamicInvoke(actionArgs); 401 | }); 402 | ret = actionId; 403 | } 404 | else if (IsFunc(coreType)) 405 | { 406 | throw new Exception("Func delegate parameters are not supported."); 407 | } 408 | else 409 | { 410 | throw new Exception("Unknown delegate parameter type"); 411 | } 412 | } 413 | else 414 | { 415 | ret = value; 416 | } 417 | return ret; 418 | } 419 | protected void OnRequestCleanup(string msgId, Action action) 420 | { 421 | if (action == null) return; 422 | lock (waitingResponseLock) 423 | { 424 | if (!RequestCleanup.TryGetValue(msgId, out var cleanUps)) 425 | { 426 | cleanUps = new List(); 427 | RequestCleanup[msgId] = cleanUps; 428 | } 429 | cleanUps.Add(action); 430 | } 431 | } 432 | protected void StartRequestCleanup(string msgId) 433 | { 434 | lock (waitingResponseLock) 435 | { 436 | if (RequestCleanup.TryGetValue(msgId, out var cleanUps)) 437 | { 438 | RequestCleanup.Remove(msgId); 439 | foreach (var cleanUp in cleanUps) cleanUp(); 440 | } 441 | } 442 | } 443 | /// 444 | /// Override this method to customize callable targets 445 | /// 446 | /// 447 | /// 448 | protected virtual async Task GetServiceAsync(Type serviceType) 449 | { 450 | try 451 | { 452 | return await ScopedServiceProvider.GetServiceAsync(serviceType); 453 | } 454 | catch (Exception ex) 455 | { 456 | var nmt = true; 457 | } 458 | return null; 459 | } 460 | protected Dictionary> RequestCleanup = new Dictionary>(); 461 | protected async Task PostDeserializeArgument(string msgId, MethodInfo methodInfo, ParameterInfo parameterInfo, bool isReturnValue, MessagePackList? callArgs, int paramIndex) 462 | { 463 | var callArgsLength = callArgs?.Count ?? 0; 464 | var finalType = isReturnValue ? parameterInfo.ParameterType.AsyncReturnType() ?? parameterInfo.ParameterType : parameterInfo.ParameterType; 465 | var genericTypes = finalType.GenericTypeArguments; 466 | //var attributes = parameterInfo.GetCustomAttributes(InheritAttributes).Cast().ToArray(); 467 | #if NET8_0_OR_GREATER 468 | var fromKeyedServicesAttr = parameterInfo.GetCustomAttribute(InheritAttributes); 469 | if (fromKeyedServicesAttr != null) 470 | { 471 | return ScopedServiceProvider.GetRequiredKeyedService(finalType, fromKeyedServicesAttr.Key); 472 | } 473 | #endif 474 | var fromServicesAttr = parameterInfo.GetCustomAttribute(InheritAttributes); 475 | if (fromServicesAttr != null) 476 | { 477 | return ScopedServiceProvider.GetRequiredService(finalType); 478 | } 479 | var fromLocalAttr = parameterInfo.GetCustomAttribute(InheritAttributes); 480 | if (fromLocalAttr != null) 481 | { 482 | return await ResolveLocalInstance(finalType); 483 | } 484 | if (paramIndex < callArgsLength) 485 | { 486 | // custom deserialization can be done here to get type methodParamType from callArgs Array 487 | if (typeof(Delegate).IsAssignableFrom(finalType)) 488 | { 489 | // Create a local action that can be called to relay the call to the remote endpoint 490 | var actionId = callArgs!.GetItem(paramIndex); 491 | if (genericTypes.Length == 0) 492 | { 493 | return new Action(() => SendCall(new object?[] { actionId })); 494 | } 495 | else 496 | { 497 | return CreateTypedAction(genericTypes, new Action((args) => 498 | { 499 | // TODO - pre-serialize args 500 | var callbackMsg = new List { actionId }; 501 | callbackMsg.AddRange(args); 502 | SendCall(callbackMsg.ToArray()); 503 | })); 504 | } 505 | } 506 | else if (finalType == typeof(CancellationToken)) 507 | { 508 | // Create a local action that can be called to relay the call to the remote endpoint 509 | var tokenId = callArgs!.GetItem(paramIndex); 510 | if (tokenId == null) 511 | { 512 | // default token 513 | return CancellationToken.None; 514 | } 515 | else if (tokenId == "") 516 | { 517 | // already cancelled 518 | return new CancellationToken(true); 519 | } 520 | else 521 | { 522 | // can be cancelled 523 | var tokenSource = new CancellationTokenSource(); 524 | AddDynamicCallable(msgId, tokenId, async (msg) => tokenSource.Cancel()); 525 | return tokenSource.Token; 526 | } 527 | } 528 | else 529 | { 530 | return callArgs!.GetItem(finalType, paramIndex); 531 | } 532 | } 533 | else if (parameterInfo.HasDefaultValue) 534 | { 535 | return parameterInfo.DefaultValue; 536 | } 537 | return finalType.GetDefaultValue(); 538 | } 539 | protected async Task PreSerializeArgs(string msgId, MethodInfo methodInfo, object?[]? args) 540 | { 541 | var methodParams = methodInfo.GetParameters(); 542 | var ret = new object?[methodParams.Length]; 543 | var callArgsLength = args == null ? 0 : args.Length; 544 | for (var i = 0; i < methodParams.Length; i++) 545 | { 546 | ret[i] = await PreSerializeArgument(msgId, methodInfo, methodParams[i], false, i < callArgsLength ? args[i] : null, i); 547 | } 548 | return ret; 549 | } 550 | protected async Task PostDeserializeArgs(string msgId, MethodInfo methodInfo, MessagePackList? callArgs) 551 | { 552 | var methodParams = methodInfo.GetParameters(); 553 | var ret = new object?[methodParams.Length]; 554 | var callArgsLength = callArgs == null ? 0 : callArgs.Count; 555 | for (var i = 0; i < methodParams.Length; i++) 556 | { 557 | var methodParam = methodParams[i]; 558 | var methodParamType = methodParam.ParameterType; 559 | ret[i] = await PostDeserializeArgument(msgId, methodInfo, methodParams[i], false, callArgs, i); 560 | } 561 | return ret; 562 | } 563 | async Task HandleCall(MessagePackList msg, bool resultRequested) 564 | { 565 | object? instance = null; 566 | object? retValue = null; 567 | string? retError = null; 568 | string? msgId = null; 569 | Type? targetType = null; 570 | string? serviceTypeName = null; 571 | MethodInfo? methodInfo = null; 572 | object?[]? args = null; 573 | RemoteCallableAttribute? remoteCallableAttr = null; 574 | // rebuild request MethodInfo and arguments 575 | MessagePackList? argsPreDeser = null; 576 | try 577 | { 578 | msgId = msg.Shift(); 579 | if (string.IsNullOrEmpty(msgId)) return; 580 | if (!ServeEnabled) 581 | { 582 | retError = "HandleCallError: Offline"; 583 | goto SendResponse; 584 | } 585 | serviceTypeName = msg.Shift(); 586 | targetType = TypeExtensions.GetType(serviceTypeName); 587 | var methodInfoSerialized = msg.Shift(); 588 | methodInfo = string.IsNullOrWhiteSpace(methodInfoSerialized) ? null : SerializableMethodInfoSlim.DeserializeMethodInfo(methodInfoSerialized); 589 | if (methodInfo == null) 590 | { 591 | retError = "HandleCallError: Method not found"; 592 | goto SendResponse; 593 | } 594 | targetType ??= methodInfo!.ReflectedType; 595 | if (targetType == null) 596 | { 597 | retError = $"HandleCallError: Target not found: {serviceTypeName}"; 598 | goto SendResponse; 599 | } 600 | // locate info about the type being called 601 | instance = await GetServiceAsync(targetType); 602 | // what is left in `msg` is the call arguments 603 | argsPreDeser = msg.Shift(); 604 | args = argsPreDeser == null ? null : await PostDeserializeArgs(msgId, methodInfo, argsPreDeser); 605 | } 606 | catch (Exception ex) 607 | { 608 | //JS.Log($"HandleCall failed to rebuild the request method or args: {ex.Message}"); 609 | retError = $"HandleCallError: Failed to rebuild the request method or args: {ex.Message}"; 610 | goto SendResponse; 611 | } 612 | // get the instance for this call (if non-static) 613 | if (!methodInfo.IsStatic) 614 | { 615 | if (instance == null) 616 | { 617 | retError = $"HandleCallError: Target not found: {serviceTypeName}"; 618 | goto SendResponse; 619 | } 620 | } 621 | remoteCallableAttr = methodInfo.GetCustomAttribute(); 622 | remoteCallableAttr ??= targetType.GetCustomAttribute(); 623 | if (remoteCallableAttr == null && instance != null) 624 | { 625 | remoteCallableAttr = instance.GetType().GetCustomAttribute(); 626 | } 627 | var deniedError = await CanCallCheck(methodInfo, remoteCallableAttr, instance); 628 | if (!string.IsNullOrEmpty(deniedError)) 629 | { 630 | retError = deniedError; 631 | goto SendResponse; 632 | } 633 | // Authorize check 634 | var authorized = true; 635 | if (remoteCallableAttr != null) 636 | { 637 | if (!string.IsNullOrEmpty(remoteCallableAttr.Roles)) 638 | { 639 | var allowedRoles = Regex.Split(remoteCallableAttr.Roles, @",\s*|,?\s+"); 640 | authorized = allowedRoles.Any(User.IsInRole); 641 | } 642 | } 643 | if (!authorized) 644 | { 645 | retError = "HandleCallError: Access denied"; 646 | goto SendResponse; 647 | } 648 | // invoke the call capturing the result or exception 649 | try 650 | { 651 | retValue = await methodInfo.InvokeAsync(instance, args); 652 | } 653 | catch (Exception ex) 654 | { 655 | retError = SerializeException(ex); 656 | goto SendResponse; 657 | } 658 | SendResponse: 659 | try 660 | { 661 | if (!resultRequested) return; 662 | if (remoteCallableAttr?.NoReply == true) return; 663 | if (retError == null) 664 | { 665 | retValue = await PreSerializeArgument(msgId!, methodInfo!, methodInfo!.ReturnParameter, true, retValue, 0); 666 | } 667 | SendCall(new object?[] { RemoteDispatcherMessageType.Response, msgId, retError, retValue }); 668 | } 669 | catch (Exception ex) 670 | { 671 | Console.WriteLine($"DataConnection.Send failed: {ex.Message}"); 672 | } 673 | finally 674 | { 675 | StartRequestCleanup(msgId!); 676 | } 677 | } 678 | void HandleReply(MessagePackList? msg) 679 | { 680 | if (msg == null) return; 681 | var msgId = msg.Shift(); 682 | lock (waitingResponseLock) 683 | { 684 | if (waitingResponse.TryGetValue(msgId, out var waiter)) 685 | { 686 | waitingResponse.Remove(msgId); 687 | waiter.TrySetResult(msg); 688 | } 689 | } 690 | //msg.Dispose(); 691 | } 692 | protected static string SerializeException(Exception exception) 693 | { 694 | return exception.ToString(); 695 | } 696 | protected static Exception DeserializeException(string exception) 697 | { 698 | var ret = new Exception(exception); 699 | return ret; 700 | } 701 | protected void AddDynamicCallable(string msgId, string key, Func handler) 702 | { 703 | AddDynamicCallable(key, handler); 704 | OnRequestCleanup(msgId, () => RemoveDynamicHandler(key)); 705 | } 706 | protected void AddDynamicCallable(string key, Func handler) => DynamicCallables.Add(key, handler); 707 | protected bool RemoveDynamicHandler(string key) => DynamicCallables.Remove(key); 708 | protected Dictionary> DynamicCallables = new Dictionary>(); 709 | protected static Action CreateTypedActionT1(Action arg) => new Action((t0) => arg(new object[] { t0 })); 710 | protected static Action CreateTypedActionT2(Action arg) => new Action((t0, t1) => arg(new object[] { t0, t1 })); 711 | protected static Action CreateTypedActionT3(Action arg) => new Action((t0, t1, t2) => arg(new object[] { t0, t1 })); 712 | protected static Action CreateTypedActionT4(Action arg) => new Action((t0, t1, t2, t3) => arg(new object[] { t0, t1, t2, t3 })); 713 | protected static Action CreateTypedActionT5(Action arg) => new Action((t0, t1, t2, t3, t4) => arg(new object[] { t0, t1, t2, t3, t4 })); 714 | protected static object CreateTypedAction(Type[] paramTypes, Action arg) 715 | { 716 | var methodKey = $"CreateTypedActionT{paramTypes.Length}"; 717 | if (!ActionMakerCache.TryGetValue(methodKey, out var methodInfo)) 718 | { 719 | methodInfo = typeof(RemoteDispatcher).GetMethod(methodKey, BindingFlags.NonPublic | BindingFlags.Static); 720 | ActionMakerCache[methodKey] = methodInfo; 721 | } 722 | var gmeth = methodInfo.MakeGenericMethod(paramTypes); 723 | var genericAction = gmeth.Invoke(null, new object[] { arg }); 724 | return genericAction; 725 | } 726 | protected static Dictionary ActionMakerCache = new Dictionary(); 727 | protected static List GenericActions = new List { 728 | typeof(Action), 729 | typeof(Action<>), 730 | typeof(Action<,>), 731 | typeof(Action<,,>), 732 | typeof(Action<,,,>), 733 | typeof(Action<,,,,>), 734 | typeof(Action<,,,,,>), 735 | typeof(Action<,,,,,,>), 736 | typeof(Action<,,,,,,,>), 737 | typeof(Action<,,,,,,,,>), 738 | typeof(Action<,,,,,,,,,>), 739 | typeof(Action<,,,,,,,,,,>), 740 | typeof(Action<,,,,,,,,,,,>), 741 | typeof(Action<,,,,,,,,,,,,>), 742 | }; 743 | protected static List GenericFuncs = new List { 744 | typeof(Func<>), 745 | typeof(Func<,>), 746 | typeof(Func<,,>), 747 | typeof(Func<,,,>), 748 | typeof(Func<,,,,>), 749 | typeof(Func<,,,,,>), 750 | typeof(Func<,,,,,,>), 751 | typeof(Func<,,,,,,,>), 752 | typeof(Func<,,,,,,,,>), 753 | typeof(Func<,,,,,,,,,>), 754 | typeof(Func<,,,,,,,,,,>), 755 | typeof(Func<,,,,,,,,,,,>), 756 | typeof(Func<,,,,,,,,,,,,>), 757 | }; 758 | protected static bool IsFunc(Type type) 759 | { 760 | Type? generic = null; 761 | if (type.IsGenericTypeDefinition) generic = type; 762 | else if (type.IsGenericType) generic = type.GetGenericTypeDefinition(); 763 | if (generic == null) return false; 764 | return GenericFuncs.Contains(generic); 765 | } 766 | protected static bool IsAction(Type type) 767 | { 768 | if (type == typeof(Action)) return true; 769 | Type? generic = null; 770 | if (type.IsGenericTypeDefinition) generic = type; 771 | else if (type.IsGenericType) generic = type.GetGenericTypeDefinition(); 772 | if (generic == null) return false; 773 | return GenericActions.Contains(generic); 774 | } 775 | } 776 | } 777 | --------------------------------------------------------------------------------