Thursday, July 22, 2010

Load external DLL from Silverlight

public partial class MainPage : UserControl
{
private string xmlPath;

public MainPage()
{
InitializeComponent();

this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("http://localhost:56121/SL/Test/Test1.dll", UriKind.RelativeOrAbsolute));
}

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
AssemblyPart assemblyPart = new AssemblyPart();
Assembly assembly = assemblyPart.Load(e.Result);

UserControl userControl = assembly.CreateInstance("Test1.MainPage") as UserControl;

if (userControl != null)
{
LayoutRoot.Children.Add(userControl);
}
Type type = userControl.GetType();
MethodInfo[] methodInfoArray = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (MethodInfo methodInfo in methodInfoArray)
{
if (methodInfo.Name == "XMLLoad1")
{
methodInfo.Invoke(userControl, new object[] { "http://localhost:56121/SL/Test/Test1.xml" });
break;
}
}
}
}