.NET/Link: Integrating Mathematica with the
Next Generation of Microsoft Technology

Todd Gayley
Directory of Java Technology, Wolfram Research, Inc.

What is .NET?

From the Microsoft .NET Developer Home Page:

"Microsoft .NET is an XML Web services platform that will enable developers to create programs that transcend device boundaries and fully harness the connectivity of the Internet."

What is .NET?

From the Microsoft .NET Developer Home Page:

"Microsoft .NET is an XML Web services platform that will enable developers to create programs that transcend device boundaries and fully harness the connectivity of the Internet."

BALONEY!

.NET is a completely new development paradigm for all Windows programming.

What is .NET?

From the Microsoft .NET Developer Home Page:

"Microsoft .NET is an XML Web services platform that will enable developers to create programs that transcend device boundaries and fully harness the connectivity of the Internet."

BALONEY!

.NET is a completely new development paradigm for all Windows programming.

It has lots of nice features to enable XML Web Services, but that is a small part of .NET, and .NET's success is not dependent on widespread adoption of XML Web Services.

What is .NET?

From the Microsoft .NET Developer Home Page:

"Microsoft .NET is an XML Web services platform that will enable developers to create programs that transcend device boundaries and fully harness the connectivity of the Internet."

BALONEY!

.NET is a completely new development paradigm for all Windows programming.

It has lots of nice features to enable XML Web Services, but that is a small part of .NET, and .NET's success is not dependent on widespread adoption of XML Web Services.

It is comparable in many ways to the entire Java universe (Java on the desktop, Java in the browser, J2EE, Java Micro Edition, etc.)

What is .NET?

From the Microsoft .NET Developer Home Page:

"Microsoft .NET is an XML Web services platform that will enable developers to create programs that transcend device boundaries and fully harness the connectivity of the Internet."

BALONEY!

.NET is a completely new development paradigm for all Windows programming.

It has lots of nice features to enable XML Web Services, but that is a small part of .NET, and .NET's success is not dependent on widespread adoption of XML Web Services.

It is comparable in many ways to the entire Java universe (Java on the desktop, Java in the browser, J2EE, Java Micro Edition, etc.)

It represents the future of Windows programming. Bill Gates has called .NET a "bet-the-company" technology.

What is .NET?

The core of .NET technology is the Common Language Runtime (CLR), a byte code-based runtime very much like Java's.

What is .NET?

The core of .NET technology is the Common Language Runtime (CLR), a byte code-based runtime very much like Java's.

Code that runs in the CLR is "managed", meaning that it is subject to security checks, array-index checking, garbage collection, etc.

What is .NET?

The core of .NET technology is the Common Language Runtime (CLR), a byte code-based runtime very much like Java's.

Code that runs in the CLR is "managed", meaning that it is subject to security checks, array-index checking, garbage collection, etc.

Any language that can be compiled into CLR bytecodes can run in the CLR. Microsoft ships compilers for C#, Visual Basic .NET, and C++ with Managed Extensions. Compilers exist for many other languages (Fortran, Eiffel, PERL, Python, etc.)

What is .NET?

.NET includes an extensive class library called the .NET Framework. It includes classes for GUIs, Web services, XML manipulation, Internet connectivity, database access, code generation, collections, debugging, etc.

It is comparable in size and breadth to the current standard Java class library.

What is .NET?

Projects are underway to port .NET to other platforms:
	Mono: Open Source Linux Implementation
	Rotor: "Shared Source" FreeBSD/Mac OSX Implementation from Microsoft

What is .NET?

Quick Quiz: What do all these technologies have in common?

COM/ActiveX

MFC

ATL

ASP

ADO

.. and many others

What is .NET?

Quick Quiz: What do all these technologies have in common?

They are all obsolete!

COM/ActiveX

MFC

ATL

ASP

ADO

.. and many others

The C# Language

A fine language, very similar to Java.

Intermediate in complexity between Java and C++.

The C# Language

Sieve Benchmark Timings

.NET/Link

Goal: Do for .NET what J/Link does for Java: Seamless interoperability between .NET and Mathematica in both directions.

.NET/Link

Goal: Do for .NET what J/Link does for Java: Seamless interoperability between .NET and Mathematica in both directions.

Implemented in C# and Mathematica.

.NET/Link

Goal: Do for .NET what J/Link does for Java: Seamless interoperability between .NET and Mathematica in both directions.

Implemented in C# and Mathematica.

Bundled with Mathematica 5.0. A very alpha version is installed with the conference Mathematica 5.0 beta.

.NET/Link Outline

Calling .NET from Mathematica

Calling DLLs from Mathematica

Calling COM from Mathematica

Calling Mathematica from .NET

Calling Mathematica from COM

Calling .NET From Mathematica

Like J/Link: Load arbitrary classes into .Mathematica, create objects and call methods on them directly, with no preparation.

({{obj  =  new Namespace . 
                    ClassName (args)        , \(\(obj\  = \ \(\(NETNew\)\([\)\(\*"""Namespace . 
                        ClassName\)\)\*""", \ args\)\(]\)\)}, {obj . Method[args], obj@Method[args]}, {obj . FieldOrProperty, obj@FieldOrProperty}, {ClassName . StaticMethod[args], ClassName`StaticMethod[args]}})

Calling .NET From Mathematica

Simple Example

<<NETLink`

InstallNET[]

dirInfo = NETNew["System.IO.DirectoryInfo", $TopDirectory]

dirInfo@GetFiles[]

#@ToString[]& /@ %

dirInfo@LastAccessTime

%@ToString[]

Calling .NET From Mathematica

GUI Example

form = NETNew["System.Windows.Forms.Form"]

form@Show[]
form@Activate[]

LoadNETType["System.Drawing.Color"]

form@BackColor = Color`Red

Syntax for Adding an Event Handler:

// C#
form.Click += new EventHandler(onClick);

// VB.NET
AddHandler form.Click, New EventHandler(AddressOf Me.onClick)

(**  Mathematica code using J/Link  **)
listener = JavaNew["com.wolfram.jlink.MathMouseListener"];
listener@setHandler["mouseClicked" -> "onClick"];
form@addMouseListener[listener];

AddEventHandler[form@Click, onClick]

onClick[args___] :=
	form@BackColor = Color`FromArgb[Random[Integer, {0, 255}],
									Random[Integer, {0, 255}],
									Random[Integer, {0, 255}]]

DoNETModal[form]

Calling .NET From Mathematica

Getting Type Information

NETTypeInfo["System.Windows.Forms.Form", Inherited->False]

NETTypeInfo["System.Windows.Forms.Form", "Methods", Inherited->False, LanguageSyntax->"VB"]

Calling .NET From Mathematica

Support for "out" and "ref" parameters:

LoadNETAssembly["e:\\netlink\\project\\testing\\bin\\debug\\testing.exe"];
LoadNETType["Wolfram.NETLink.Testing"];

public static void OutParamA(int i, out int j)

Testing`OutParamA[42, k]

Calling Fortran

Salford FTN95 for .NET
http://www.salford.co.uk

LoadNETAssembly["E:\\NETLink\\Fortran\\FortranCalculator\\bin\\Debug\\Calculator.dll"];
LoadNETType["Calculator"];

real*8 function add (x, y)
   		real*8 x, y
   		add = x + y
	end

Calculator`ADD[5, 6]

SetComplexType["Salford.Fortran.Complex8"]

Calculator`Double[1 + 2I]

Calling .NET From Mathematica

The .NET Framework has good support for on-the-fly code generation.

This enables a number of features in .NET/Link, including "inline" C# or VB in Mathematica function definitions.

CSAddTwo = DefineNETMethod["int addtwo(int i, int j) { return i+j; }"]

CSAddTwo[3, 4]

Calling .NET From Mathematica

LoadNETType["System.Text.RegularExpressions.Regex"];

ChangeDate[s_String] :=
	Regex`Replace[s, "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
		 			"${day}-${month}-${year}"]

ChangeDate["My birthday is 8/16/61."]

ChangeDate /@ Table["My birthday is 8/16/61.", {10000}];

Calling .NET From Mathematica

CSChangeDate =
	DefineNETMethod["
		string[] ChangeDate(string[] s) {
			for (int i = 0; i < s.Length; i++)
				s[i] = Regex.Replace(s[i],
\"\\\\b(?<month>\\\\d{1,2})/(?<day>\\\\d{1,2})/(?<year>\\\\d{2,4})\\\\b\",
		 				\"${day}-${month}-${year}\");
			return s;
		}",
		ImportNamespaces -> {"System.Text.RegularExpressions"}
	]

CSChangeDate[Table["My birthday is 8/16/61.", {10000}]];

Calling DLLs From Mathematica

Visual Basic .NET and C# (and many other non-.NET languages) let you "declare" a function that resides in an external DLL so that it can be called as if it were defined in the language itself.

BZFILE * BZ2_bzopen  ( const char *path, const char *mode );

bzopen = DefineDLLFunction["BZ2_bzopen", "libbz2-1.0.0.dll", "IntPtr", {"char*", "char*"}]

int BZ2_bzwrite ( BZFILE* b, void* buf, int len );
void BZ2_bzclose ( BZFILE* b );

bzwrite = DefineDLLFunction["BZ2_bzwrite", "libbz2-1.0.0.dll", "int", {"IntPtr", "byte[]", "int"}];
bzclose = DefineDLLFunction["BZ2_bzclose", "libbz2-1.0.0.dll", "void", {"IntPtr"}];

bz = bzopen["e:\\myfile.bz2", "w"]

bzwrite[bz, ToCharacterCode["BZip Me"], 7]

bzclose[bz]

!!e:\myfile.bz2

Calling COM From Mathematica

Who Needs Visual Basic?

excel = GetActiveCOMObject["Excel.Application"]

wb = excel@Workbooks[1]

ws = wb@Worksheets[1]

ws@Range["A1"]@Value = "North";
ws@Range["A2"]@Value = "South";
ws@Range["A3"]@Value = "East";
ws@Range["A4"]@Value = "West";
ws@Range["B1"]@Value = "5.2";
ws@Range["B2"]@Value = "10";
ws@Range["B3"]@Value = "8";
ws@Range["B4"]@Value = "20";

srcRange = ws@Range["A1:B4"];
chrt = wb@Charts@Add;
chrt@ChartWizard[srcRange, -4102, 7, 2, 1, 0, 2, "Sales Percentages"];

({{\(\(Set\ wb\  = \ 
                Application . Workbooks \((1)\)\)
\(Set\ ws\  = \ 
                wb . Worksheets \((1)\)\)
\(ws . Range \(("A1")\) . 
                    Value\  = \ "North"\)
\(ws . Range \(("A2")\) . 
                    Value\  = \ "South"\)
\(ws . Range \(("A3")\) . 
                    Value\  = \ "East"\)
\(ws . Range \(("A4")\) . 
                    Value\  = \ "West"\)
\(ws . Range \(("B1")\) . 
                    Value\  = \ 
                5.2\)
\(ws . Range \(("B2")\) . Value\  = \ 
                10\)
\(ws . Range \(("B3")\) . Value\  = \ 
                8\)
\(ws . Range \(("B4")\) . Value\  = \ 
                20\)
\(Set\ sourceRange\  = \ 
                ws . Range \(("A1:B4")\)\)
\(Set\ chrt\  = \ 
                wb . Charts . Add\)
\(chrt . ChartWizard\ sourceRange, \ 
              xl3DPie, \ 7, \ xlColumns, 
		\ 1, \ 0, \ 
              2, \ "Sales Percentages"\)\), \(\(wb = excel@Workbooks[1]; \)
\(ws = 
                wb@Worksheets[1]; \)
\(ws@\(Range["A1"]@
                    Value\) = "North"; \)
\(ws@\(Range["A2"]@
                    Value\) = "South"; \)
\(ws@\(Range["A3"]@
                    Value\) = "East"; \)
\(ws@\(Range["A4"]@
                    Value\) = "West"; \)
\(ws@\(Range["B1"]@
                    Value\) = "5.2"; \)
\(ws@\(Range["B2"]@
                    Value\) = "10"; \)
\(ws@\(Range["B3"]@
                    Value\) = "8"; \)
\(ws@\(Range["B4"]@
                    Value\) = "20"; \)
\(srcRange = 
                ws@Range["A1:B4"]; \)
\(chrt = 
                wb@\(Charts@Add\); \)
\(chrt@
                ChartWizard[srcRange, \(-4102\), 7, 
                  2, 
		1, 0, 
                  2, "Sales Percentages"]; \)\)}})

Calling Mathematica From .NET

Mathematica: The Ultimate Game Platform ??

<<e:\netlink\notebooks\asteroids.m

Asteroids[]

Calling Mathematica From .NET

For all .NET  languages, .NET/Link provides an API very similar to J/Link's.

MathLinkFactory class for creating links

IMathLink low-level interface:
	Put(int i)
	double GetDouble()
	double[] GetDoubleArray()
	string GetFunction(out int argCount)

IKernelLink high-level interface:
	void Evaluate(string s)
	int WaitForAnswer()
	byte[] EvaluateToImage(string s, int width, int height);

MathKernel class for very-high-level access, designed for component-based programming:
	Properties: Input, Result, Graphics, Messages, etc.

Expr class to represent aribtrary Mathematica expressions.

Calling Mathematica From .NET

C# sample program:

using System;
	using Wolfram.NETLink;
	
	public static void Main(string[] args) {

		IKernelLink ml = MathLinkFactory.CreateKernelLink();
		ml.DiscardAnswer();

		ml.Evaluate("2+2");
		ml.WaitForAnswer();
		string result = ml.GetString();
		Console.WriteLine("2+2 = " + result);

		ml.Close();
	}

Calling Mathematica From .NET

Demo: TrivialApp Built With MathKernel Component

Calling Mathematica From COM

VBScript program:

Set factory = GetObject("Wolfram.NETLink.MathLinkFactory")
Set link = factory.CreateKernelLink
link.WaitAndDiscardAnswer

MsgBox "2 + 2 = " & link.EvaluateToOutputForm("2+2", 0)

link.Evaluate("3+3")
link.WaitForAnswer
MsgBox "3 + 3 = " & link.GetInteger

link.Close

Summary

.NET is the future of Windows programming. Get used to it.

.NET/Link lets you transparently call code written in any .NET language from Mathematica. It also provides a very high-level programming interface for writing .NET programs that call Mathematica.

.NET/Link == Win/Link ?  (DLLs and COM for people who don't see an immediate need for .NET)

Bundled in Mathematica 5.0; can be downloaded and used with 4.x