diff --git a/src/AddIns/Uno.UI.MSAL/WasmHttpFactory.wasm.cs b/src/AddIns/Uno.UI.MSAL/WasmHttpFactory.wasm.cs index 0818232cf0a7..93ffafa2c24c 100644 --- a/src/AddIns/Uno.UI.MSAL/WasmHttpFactory.wasm.cs +++ b/src/AddIns/Uno.UI.MSAL/WasmHttpFactory.wasm.cs @@ -1,6 +1,5 @@ using System.Net.Http; using Microsoft.Identity.Client; -using Uno.UI.Wasm; namespace Uno.UI.MSAL { diff --git a/src/SamplesApp/SamplesApp.Shared/Samples/UnitTests/HttpUnitTests.xaml.cs b/src/SamplesApp/SamplesApp.Shared/Samples/UnitTests/HttpUnitTests.xaml.cs index 8c37922bca97..343bd3fbd797 100644 --- a/src/SamplesApp/SamplesApp.Shared/Samples/UnitTests/HttpUnitTests.xaml.cs +++ b/src/SamplesApp/SamplesApp.Shared/Samples/UnitTests/HttpUnitTests.xaml.cs @@ -16,11 +16,7 @@ public HttpUnitTests() private async void Go(object sender, RoutedEventArgs e) { -#if __WASM__ - var handler = new Uno.UI.Wasm.WasmHttpHandler(); -#else var handler = new HttpClientHandler(); -#endif try { diff --git a/src/Uno.Analyzers.Tests/WasmHttpHandlerDeprecatedTests.cs b/src/Uno.Analyzers.Tests/WasmHttpHandlerDeprecatedTests.cs deleted file mode 100644 index a61306bdc68d..000000000000 --- a/src/Uno.Analyzers.Tests/WasmHttpHandlerDeprecatedTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Microsoft.CodeAnalysis.Testing; -using Uno.Analyzers.Tests.Verifiers; -using System.Threading.Tasks; - -namespace Uno.Analyzers.Tests -{ - using Verify = CSharpCodeFixVerifier; - - [TestClass] - public class WasmHttpHandlerDeprecatedTests - { - private static string Stub = @" -namespace Uno.UI.Wasm -{ - public class WasmHttpHandler - { - public void M() { } - } -} -"; - - [TestMethod] - public async Task When_Method_Is_Invoked() - { - var test = @" -using Uno.UI.Wasm; - -public class C -{ - public void M(WasmHttpHandler handler) => [|handler.M()|]; -} -" + Stub; - - await Verify.VerifyAnalyzerAsync(test); - } - - [TestMethod] - public async Task When_Object_Is_Instantiated() - { - var test = @" -using Uno.UI.Wasm; - -public class C -{ - public void M1() => _ = [|new WasmHttpHandler()|]; - public void M2() { WasmHttpHandler handler = [|new()|]; } -} -" + Stub; - - await Verify.VerifyAnalyzerAsync(test); - } - - [TestMethod] - public async Task When_Inherited() - { - var test = @" -using Uno.UI.Wasm; - -public class [|C|] : WasmHttpHandler -{ -} -" + Stub; - - await Verify.VerifyAnalyzerAsync(test); - } - } -} diff --git a/src/Uno.Analyzers/WasmHttpHandlerDeprecatedAnalyzer.cs b/src/Uno.Analyzers/WasmHttpHandlerDeprecatedAnalyzer.cs deleted file mode 100644 index 11600104acf3..000000000000 --- a/src/Uno.Analyzers/WasmHttpHandlerDeprecatedAnalyzer.cs +++ /dev/null @@ -1,78 +0,0 @@ -#nullable enable - -using System; -using System.Collections.Immutable; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -namespace Uno.Analyzers -{ - [DiagnosticAnalyzer(LanguageNames.CSharp)] - public class WasmHttpHandlerDeprecatedAnalyzer : DiagnosticAnalyzer - { - internal const string Title = "'WasmHttpHandler' is deprecated"; - internal const string MessageFormat = "'WasmHttpHandler' is deprecated, use 'HttpClient' and 'HttpHandler' instead."; - internal const string Category = "Usage"; - - internal static DiagnosticDescriptor Rule = new( - "Uno0002", - Title, - MessageFormat, - Category, - DiagnosticSeverity.Warning, - isEnabledByDefault: true - ); - - public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); - - public override void Initialize(AnalysisContext context) - { - context.EnableConcurrentExecution(); - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); - - context.RegisterCompilationStartAction(context => - { - var wasmHttpHandlerSymbol = context.Compilation.GetTypeByMetadataName("Uno.UI.Wasm.WasmHttpHandler"); - if (wasmHttpHandlerSymbol is null) - { - return; - } - - context.RegisterOperationAction(c => AnalyzeOperation(c, wasmHttpHandlerSymbol), OperationKind.Invocation, OperationKind.ObjectCreation); - context.RegisterSymbolAction(c => AnalyzeNamedType(c, wasmHttpHandlerSymbol), SymbolKind.NamedType); - }); - } - - private void AnalyzeNamedType(SymbolAnalysisContext context, INamedTypeSymbol wasmHttpHandlerSymbol) - { - var namedType = (INamedTypeSymbol)context.Symbol; - if (wasmHttpHandlerSymbol.Equals(namedType.BaseType)) - { - context.ReportDiagnostic(Diagnostic.Create(Rule, context.Symbol.Locations.First())); - } - } - - private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol wasmHttpHandlerSymbol) - { - var symbol = GetTypeSymbolFromOperation(context.Operation); - if (wasmHttpHandlerSymbol.Equals(symbol, SymbolEqualityComparer.Default)) - { - context.ReportDiagnostic(Diagnostic.Create(Rule, context.Operation.Syntax.GetLocation())); - } - } - - private INamedTypeSymbol? GetTypeSymbolFromOperation(IOperation operation) - { - return operation switch - { - IInvocationOperation invocationOperation => invocationOperation.TargetMethod.ContainingType, - IObjectCreationOperation objectCreation => objectCreation.Constructor.ContainingType, - IFieldReferenceOperation fieldReferenceOperation => fieldReferenceOperation.Field.ContainingType, - IPropertyReferenceOperation propertyReferenceOperation => propertyReferenceOperation.Property.ContainingType, - _ => throw new InvalidOperationException("This code path is unreachable.") - }; - } - } -} diff --git a/src/Uno.UI.Runtime.WebAssembly/WasmHttpHandler.cs b/src/Uno.UI.Runtime.WebAssembly/WasmHttpHandler.cs deleted file mode 100644 index b512b6e1777c..000000000000 --- a/src/Uno.UI.Runtime.WebAssembly/WasmHttpHandler.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Collections.Immutable; -using System.Globalization; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Uno.Foundation; -using Uno.Threading; - -namespace Uno.UI.Wasm -{ - public class WasmHttpHandler : HttpMessageHandler - { - private static long RequestsCounter; - - private static ImmutableDictionary> PendingExecutions = - ImmutableDictionary>.Empty; - - protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - var requestId = Interlocked.Increment(ref RequestsCounter); - - string requestPayload; - string requestPayloadType; - if (request.Content != null) - { - var bytes = await request.Content.ReadAsByteArrayAsync(); - var base64 = Convert.ToBase64String(bytes); - requestPayload = string.Concat("\"", base64, "\""); - requestPayloadType = string.Concat("\"", request.Content.Headers.ContentType.MediaType, "\""); - } - else - { - requestPayload = "null"; - requestPayloadType = "null"; - } - - string Escape(string s) => WebAssemblyRuntime.EscapeJs(s); - - var requestHeaders = request.Headers - .SelectMany(h => h.Value - .Select(v => string.Concat("[\"", Escape(h.Key), "\", \"", Escape(v), "\"]"))); - - var command = string.Concat( - "Uno.Http.HttpClient.send({id: \"", - requestId, - "\", method:\"", - request.Method, - "\", url:\"", - request.RequestUri, - "\", headers:[", - string.Join(",", requestHeaders), - "], payload:", - requestPayload, - ", payloadType:", - requestPayloadType, - "});"); - WebAssemblyRuntime.InvokeJS(command); - - var tcs = new FastTaskCompletionSource<(int status, string headers, string payload)>(); - ImmutableInterlocked.TryAdd(ref PendingExecutions, requestId, tcs); - - try - { - var response = await tcs.Task; - - var responseMessage = new HttpResponseMessage((HttpStatusCode)response.status); - var responseContent = new ByteArrayContent(Convert.FromBase64String(response.payload)); - responseMessage.Content = responseContent; - responseMessage.RequestMessage = request; - - var headers = response.headers - .Split('\n') - .Select(h => h.Split(new[] { ':' }, 2)) - .Where(h => h.Length == 2) - .GroupBy(h => h[0], h => h[1]); - - foreach (var header in headers) - { - if (!responseMessage.Content.Headers.TryAddWithoutValidation(header.Key, header)) - { - responseMessage.Headers.TryAddWithoutValidation(header.Key, header); - } - } - - return responseMessage; - } - catch (Exception ex) - { - Console.Error.WriteLine(ex); - throw; - } - } - - [Preserve] - public static void DispatchResponse(string requestId, string status, string headers, string payload) - { - var id = long.Parse(requestId, CultureInfo.InvariantCulture); - var s = int.Parse(status, CultureInfo.InvariantCulture); - - if (ImmutableInterlocked.TryRemove(ref PendingExecutions, id, out var v)) - { - v.SetResult((s, headers, payload)); - } - } - - [Preserve] - public static void DispatchError(string requestId, string errorMessage) - { - var id = long.Parse(requestId, CultureInfo.InvariantCulture); - if (ImmutableInterlocked.TryRemove(ref PendingExecutions, id, out var v)) - { - v.SetException(new Exception(errorMessage)); - } - } - } -} diff --git a/src/Uno.UI/LinkerDefinition.Wasm.xml b/src/Uno.UI/LinkerDefinition.Wasm.xml index c1795ca8b213..1659d5bc3535 100644 --- a/src/Uno.UI/LinkerDefinition.Wasm.xml +++ b/src/Uno.UI/LinkerDefinition.Wasm.xml @@ -1,7 +1,5 @@  - - diff --git a/src/Uno.UI/ts/HttpClient.ts b/src/Uno.UI/ts/HttpClient.ts deleted file mode 100644 index 6b51813b5ce6..000000000000 --- a/src/Uno.UI/ts/HttpClient.ts +++ /dev/null @@ -1,88 +0,0 @@ -namespace Uno.Http { - export interface IHttpClientConfig { - id: string; - method: string; - url: string; - headers?: string[] []; - payload?: string; - payloadType?: string; - cacheMode?: RequestCache; - } - - export class HttpClient { - - public static async send(config: IHttpClientConfig) { - - const params: RequestInit = { - method: config.method, - cache: config.cacheMode || "default", - headers: new Headers(config.headers) - }; - - if (config.payload) { - params.body = await this.blobFromBase64(config.payload, config.payloadType); - } - - try { - const response = await fetch(config.url, params); - - let responseHeaders = ""; - response.headers.forEach( - (v: string, k: string) => responseHeaders += `${k}:${v}\n` - ); - - const responseBlob = await response.blob(); - const responsePayload = responseBlob ? await this.base64FromBlob(responseBlob) : ""; - - this.dispatchResponse(config.id, response.status, responseHeaders, responsePayload); - - - } catch (error) { - this.dispatchError(config.id, `${error.message || error}`); - console.error(error); - } - } - - private static async blobFromBase64(base64: string, contentType: string): Promise { - contentType = contentType || "application/octet-stream"; - const url = `data:${contentType};base64,${base64}`; - return await (await fetch(url)).blob(); - } - - private static base64FromBlob(blob: Blob): Promise { - return new Promise(resolve => { - const reader = new FileReader(); - reader.onloadend = () => { - const dataUrl: string = reader.result as string; - const base64 = dataUrl.split(",", 2)[1]; - resolve(base64); - }; - reader.readAsDataURL(blob); - }); - } - - private static dispatchResponse(requestId: string, status: number, headers: string, payload: string) { - - this.initMethods(); - this.dispatchResponseMethod("" + requestId, "" + status, headers, payload); - } - - private static dispatchError(requestId: string, error: string) { - - this.initMethods(); - this.dispatchErrorMethod(requestId, error); - } - - private static dispatchResponseMethod: any; - private static dispatchErrorMethod: any; - - private static initMethods() { - if (this.dispatchResponseMethod) { - return; // already initialized. - } - - this.dispatchResponseMethod = (Module).mono_bind_static_method("[Uno.UI.Runtime.WebAssembly] Uno.UI.Wasm.WasmHttpHandler:DispatchResponse"); - this.dispatchErrorMethod = (Module).mono_bind_static_method("[Uno.UI.Runtime.WebAssembly] Uno.UI.Wasm.WasmHttpHandler:DispatchError"); - } - } -}