Checker.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace Avalonia.DesignerSupport.Tests
  10. {
  11. public class Checker : MarshalByRefObject
  12. {
  13. private string _appDir;
  14. private IntPtr _window;
  15. public void DoCheck(string baseAsset, string xamlText)
  16. {
  17. _appDir = new FileInfo(baseAsset).Directory.FullName;
  18. AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
  19. foreach (var asm in Directory.GetFiles(_appDir).Where(f => f.ToLower().EndsWith(".dll") || f.ToLower().EndsWith(".exe")))
  20. try
  21. {
  22. Assembly.LoadFrom(asm);
  23. }
  24. catch (Exception)
  25. {
  26. }
  27. var dic = new Dictionary<string, object>();
  28. var api = new DesignerApi(dic) { OnResize = OnResize, OnWindowCreated = OnWindowCreated };
  29. LookupStaticMethod("Avalonia.DesignerSupport.DesignerAssist", "Init").Invoke(null, new object[] { dic });
  30. api.UpdateXaml2(new DesignerApiXamlFileInfo
  31. {
  32. Xaml = xamlText,
  33. AssemblyPath = baseAsset
  34. }.Dictionary);
  35. if (_window == IntPtr.Zero)
  36. throw new Exception("Something went wrong");
  37. SendMessage(_window, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
  38. }
  39. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  40. public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
  41. public const uint WM_CLOSE = 0x0010;
  42. private void OnWindowCreated(IntPtr lastIntPtr)
  43. {
  44. _window = lastIntPtr;
  45. }
  46. private void OnResize()
  47. {
  48. }
  49. static Type LookupType(params string[] names)
  50. {
  51. var asms = AppDomain.CurrentDomain.GetAssemblies();
  52. foreach (var asm in asms)
  53. {
  54. foreach (var name in names)
  55. {
  56. var found = asm.GetType(name, false, true);
  57. if (found != null)
  58. return found;
  59. }
  60. }
  61. throw new TypeLoadException("Unable to find any of types: " + string.Join(",", names));
  62. }
  63. static MethodInfo LookupStaticMethod(string typeName, string method)
  64. {
  65. var type = LookupType(typeName);
  66. var methods = type.GetMethods();
  67. return methods.First(m => m.Name == method);
  68. }
  69. private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  70. {
  71. string assemblyPath = Path.Combine(_appDir, new AssemblyName(args.Name).Name + ".dll");
  72. if (File.Exists(assemblyPath) == false) return null;
  73. Assembly assembly = Assembly.LoadFrom(assemblyPath);
  74. return assembly;
  75. }
  76. }
  77. }