[wasm][debugger] Allow invoking property getters for objects (#19726)
[mono-project.git] / sdks / wasm / sample.cs
blob59c4071c13b88a88376024b213bd64245d4ec0da
1 using System;
2 using System.Linq;
3 using System.Net.Http;
4 using System.Reflection;
5 using WebAssembly;
7 public class SampleMath {
8 public static int IntAdd (int a, int b) {
9 var cp = new Simple.Complex (10, "hello");
10 int c = a + b;
11 int d = c + b;
12 int e = d + a;
14 e += cp.DoStuff ();
16 return e;
20 public int First (int[] x) {
21 return x.FirstOrDefault ();
24 public static void Run ()
26 DebuggerTests.EntryClass.run ();
31 namespace GeoLocation
33 class Program
36 static DOMObject navigator;
37 static DOMObject global;
38 static string BaseApiUrl = string.Empty;
39 static HttpClient httpClient;
41 static void Main(string[] args)
43 global = new DOMObject(string.Empty);
44 navigator = new DOMObject("navigator");
46 using (var window = (JSObject)WebAssembly.Runtime.GetGlobalObject("window"))
47 using (var location = (JSObject)window.GetObjectProperty("location"))
49 BaseApiUrl = (string)location.GetObjectProperty("origin");
52 httpClient = new HttpClient() { BaseAddress = new Uri(BaseApiUrl) };
56 static int requests = 0;
57 static void GeoFindMe(JSObject output)
59 GeoLocation geoLocation;
60 try
62 geoLocation = new GeoLocation(navigator.GetProperty("geolocation"));
64 catch
66 output.SetObjectProperty("innerHTML", "<p>Geolocation is not supported by your browser</p>");
67 return;
70 output.SetObjectProperty("innerHTML", "<p>Locating…</p>");
72 geoLocation.OnSuccess += async (object sender, Position position) =>
74 using (position)
76 using (var coords = position.Coordinates)
78 var latitude = coords.Latitude;
79 var longitude = coords.Longitude;
81 output.SetObjectProperty("innerHTML", $"<p>Latitude is {latitude} ° <br>Longitude is {longitude} °</p>");
83 try {
85 var ApiFile = $"https://maps.googleapis.com/maps/api/staticmap?center={latitude},{longitude}&zoom=13&size=300x300&sensor=false";
87 var rspMsg = await httpClient.GetAsync(ApiFile);
88 if (rspMsg.IsSuccessStatusCode)
91 var mimeType = getMimeType(rspMsg.Content?.ReadAsByteArrayAsync().Result);
92 Console.WriteLine($"Request: {++requests} ByteAsync: {rspMsg.Content?.ReadAsByteArrayAsync().Result.Length} MimeType: {mimeType}");
93 global.Invoke("showMyPosition", mimeType, Convert.ToBase64String(rspMsg.Content?.ReadAsByteArrayAsync().Result));
95 else
97 output.SetObjectProperty("innerHTML", $"<p>Latitude is {latitude} ° <br>Longitude is {longitude} </p><br>StatusCode: {rspMsg.StatusCode} <br>Response Message: {rspMsg.Content?.ReadAsStringAsync().Result}</p>");
100 catch (Exception exc2)
102 Console.WriteLine($"GeoLocation HttpClient Exception: {exc2.Message}");
103 Console.WriteLine($"GeoLocation HttpClient InnerException: {exc2.InnerException?.Message}");
111 geoLocation.OnError += (object sender, PositionError e) =>
113 output.SetObjectProperty("innerHTML", $"Unable to retrieve your location: Code: {e.Code} - {e.message}");
116 geoLocation.GetCurrentPosition();
118 geoLocation = null;
121 static string getMimeType (byte[] imageData)
123 if (imageData.Length < 4)
124 return string.Empty;
126 if (imageData[0] == 0x89 && imageData[1] == 0x50 && imageData[2] == 0x4E && imageData[3] == 0x47)
127 return "image/png";
128 else if (imageData[0] == 0xff && imageData[1] == 0xd8)
129 return "image/jpeg";
130 else if (imageData[0] == 0x47 && imageData[1] == 0x49 && imageData[2] == 0x46)
131 return "image/gif";
132 else
133 return string.Empty;
138 // Serves as a wrapper around a JSObject.
139 class DOMObject : IDisposable
141 public JSObject ManagedJSObject { get; private set; }
143 public DOMObject(object jsobject)
145 ManagedJSObject = jsobject as JSObject;
146 if (ManagedJSObject == null)
147 throw new NullReferenceException($"{nameof(jsobject)} must be of type JSObject and non null!");
151 public DOMObject(string globalName) : this((JSObject)Runtime.GetGlobalObject(globalName))
154 public object GetProperty(string property)
156 return ManagedJSObject.GetObjectProperty(property);
159 public object Invoke(string method, params object[] args)
161 return ManagedJSObject.Invoke(method, args);
164 public void Dispose()
166 // Dispose of unmanaged resources.
167 Dispose(true);
168 // Suppress finalization.
169 GC.SuppressFinalize(this);
172 // Protected implementation of Dispose pattern.
173 protected virtual void Dispose(bool disposing)
176 if (disposing)
179 // Free any other managed objects here.
183 // Free any unmanaged objects here.
185 ManagedJSObject?.Dispose();
186 ManagedJSObject = null;
191 class PositionEventArgs : EventArgs
193 public Position Position { get; set; }
196 class GeoLocation : DOMObject
200 public event EventHandler<Position> OnSuccess;
201 public event EventHandler<PositionError> OnError;
203 public GeoLocation(object jsobject) : base(jsobject)
207 public void GetCurrentPosition()
209 var success = new Action<object>((pos) =>
211 OnSuccess?.Invoke(this, new Position(pos));
214 var error = new Action<object>((err) =>
216 OnError?.Invoke(this, new PositionError(err));
219 ManagedJSObject.Invoke("getCurrentPosition", success, error);
224 class Position : DOMObject
227 public Position(object jsobject) : base(jsobject)
231 public Coordinates Coordinates => new Coordinates(ManagedJSObject.GetObjectProperty("coords"));
235 class PositionError : DOMObject
238 public PositionError(object jsobject) : base(jsobject)
242 public int Code => (int)ManagedJSObject.GetObjectProperty("code");
243 public string message => (string)ManagedJSObject.GetObjectProperty("message");
247 class Coordinates : DOMObject
250 public Coordinates(object jsobject) : base(jsobject)
254 public double Latitude => (double)ManagedJSObject.GetObjectProperty("latitude");
255 public double Longitude => (double)ManagedJSObject.GetObjectProperty("longitude");