Jan 3, 2010

Silverlight 4 Communicating with Matlab

I have taken it on myself to try and expand and inspire people’s view of what a web application can do.  In this installment I’m leveraging Silverlight 4 and Matlab to build a simple Matlab console.

Again I am using COM automation to communicate with Silverlight.  Why would anyone want to do this? Well, I’m slowly porting some Matlab code to c# so it is nice to check my code by communicating with Matlab.  Matlab also has an insane amount of its own functions so if you wanted to build a neural network but use Silverlight to display and distribute your code then Silverlight 4 is for you!

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;

namespace SLMatlab
{
public partial class MainPage : UserControl
{
dynamic matlab;
public MainPage()
{
InitializeComponent();
input.IsEnabled = false;
output.IsEnabled = false;
Install.Visibility = Visibility.Collapsed;
if (Application.Current.InstallState != InstallState.Installed)
{
MessageBox.Show("To run this, this application must be installed, Please click install.");
Install.Visibility = Visibility.Visible;
Connect.IsEnabled = false;
}
else if (!Application.Current.IsRunningOutOfBrowser)
{
MessageBox.Show("This application is installed but is running inside the browser. Please launch this from the desktop!");
Connect.IsEnabled = false;
}
}

private void Connect_Click(object sender, RoutedEventArgs e)
{
try
{
matlab = ComAutomationFactory.CreateObject("Matlab.Application");
matlab.Visible = 0;
input.IsEnabled = true;
output.IsEnabled = true;
}
catch { }

}

private void input_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.Key == Key.Enter)
{
dynamic result = matlab.Execute(input.Text);
input.Text = "";
output.Text = result.ToString() + Environment.NewLine + output.Text;
}
}
catch { }
}

private void Install_Click(object sender, RoutedEventArgs e)
{
App.Current.Install();
}
}
}



<UserControl x:Class="SLMatlab.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">

<
Grid x:Name="LayoutRoot" Background="White">
<
Grid.RowDefinitions>
<
RowDefinition Height="Auto"></RowDefinition>
<
RowDefinition Height="Auto"></RowDefinition>
<
RowDefinition Height="Auto"></RowDefinition>
<
RowDefinition Height="*"></RowDefinition>
</
Grid.RowDefinitions>
<
Button Name="Install" Content="Install" Grid.Row="0" Click="Install_Click"></Button>
<
Button Name="Connect" Content="Connect" Grid.Row="1" Click="Connect_Click"></Button>
<
TextBox Name="input" Grid.Row="2" KeyDown="input_KeyDown"></TextBox>
<
TextBox Name="output" Grid.Row="3"></TextBox>
</
Grid>
</
UserControl>


No comments:

Post a Comment

Followers