PageRenderTime 86ms CodeModel.GetById 4ms app.highlight 55ms RepoModel.GetById 1ms app.codeStats 2ms

/IronPython_2_0/Tutorial/Tutorial.htm

#
HTML | 2996 lines | 2969 code | 26 blank | 1 comment | 0 complexity | 1623e1b5d96dc0645c03a305c88dde4e MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<html xmlns="http://www.w3.org/1999/xhtml">
   2
   3<head>
   4<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
   5<title>IronPython Tutorial</title>
   6<!--link rel="stylesheet" type="text/css" href="../Doc/IronPython.css"-->
   7<style type="text/css">
   8	p.AntiVerify { display : none; }
   9	p.Code-Background { color : gray; }
  10	p.Code-Highlighted { color : gray; }
  11	p.CodeSample { color:blue; }
  12	p.DOSCommand { color:green; }
  13	p.ExceptionExample { color:green; }
  14	p.ExceptionOutput {display : none; }
  15	p.HiddenCode { display : none; }
  16	p.HiddenOutput {display : none; }
  17	p.LooseVerify { display : none; }
  18	p.Stepnonumbering { text-indent: 2em; }
  19	p.TypedExample { color : green; }
  20	p.UserCode { color:green; }
  21</style>
  22
  23</head>
  24
  25<body lang="EN-US">
  26
  27<div class="Section1">
  28	<p class="Title1">IronPython Tutorial</p>
  29	<p class="Title2">A tour of Python on .NET</p>
  30	<p class="Title2">&nbsp;</p>
  31	<hr />
  32	<p class="CopyrightText">Information in this document is subject to change without
  33	notice. The example companies, organizations, products, people, and events depicted
  34	herein are fictitious. No association with any real company, organization, product,
  35	person or event is intended or should be inferred. Complying with all applicable
  36	copyright laws is the responsibility of the user. Without limiting the rights
  37	under copyright, no part of this document may be reproduced, stored in or introduced
  38	into a retrieval system, or transmitted in any form or by any means (electronic,
  39	mechanical, photocopying, recording, or otherwise), or for any purpose, without
  40	the express written permission of Microsoft Corporation.</p>
  41	<p class="CopyrightText">&nbsp;</p>
  42	<p class="CopyrightText">Microsoft may have patents, patent applications, trademarked,
  43	copyrights, or other intellectual property rights covering subject matter in
  44	this document. Except as expressly provided in any written license agreement
  45	from Microsoft, the furnishing of this document does not give you any license
  46	to these patents, trademarks, copyrights, or other intellectual property.</p>
  47	<p class="CopyrightText">&nbsp;</p>
  48	<p class="CopyrightText">Š Microsoft Corporation. All rights reserved.</p>
  49	<p class="CopyrightText">&nbsp;</p>
  50	<p class="CopyrightText">Microsoft, MS-DOS, MS, Windows, Windows NT, MSDN, Active
  51	Directory, BizTalk, SQL Server, SharePoint, Outlook, PowerPoint, FrontPage,
  52	Visual Basic, Visual C++, Visual J++, Visual InterDev, Visual SourceSafe, Visual
  53	C#, Visual J#,&nbsp; and Visual Studio are either registered trademarks or trademarks
  54	of Microsoft Corporation in the U.S.A. and/or other countries.</p>
  55	<p class="CopyrightText">&nbsp;</p>
  56	<p class="CopyrightText">Other product and company names herein may be the trademarks of their respective owners.</p>
  57	<hr />
  58	<p class="ContentsHeading">Contents</p>
  59	<p class="Toc1"><a href="#Intro">Introduction</a></p>
  60	<p class="Toc1">Tutorial 1: <a href="#T1">Basic IronPython</a></p>
  61	<p class="Toc2">Exercise 1: <a href="#T1.1">The IronPython interactive console</a></p>
  62	<p class="Toc3">Task 1: <a href="#T1.1.1">IronPython console</a></p>
  63	<p class="Toc3">Task 2: <a href="#T1.1.2">Built-in modules and interactive exploration</a></p>
  64	<p class="Toc3">Task 3: <a href="#T1.1.3">External Python modules</a></p>
  65	<p class="Toc2">Exercise 2: <a href="#T1.2">Using the standard .NET libraries from IronPython</a></p>
  66	<p class="Toc3">Task 1: <a href="#T1.2.1">Basic .NET library use</a></p>
  67	<p class="Toc3">Task 2: <a href="#T1.2.2">Working with .NET classes</a></p>
  68	<p class="Toc3">Task 3: <a href="#T1.2.3">Generics</a></p>
  69	<p class="Toc2">Exercise 3: <a href="#T1.3">Loading .NET libraries</a></p>
  70	<p class="Toc3">Task 1: <a href="#T1.3.1">Using System.Xml - AddReference</a></p>
  71	<p class="Toc3">Task 2: <a href="#T1.3.2">Mapack - Loading the .NET libraries - AddReferenceToFile</a></p>
  72	<p class="Toc2">Exercise 4: <a href="#T1.4">Obtaining and Using Python Standard Library</a></p>
  73	<p class="Toc3">Task 1: <a href="#T1.4.1">Configuring IronPython to use the Python standard library</a></p>
  74	<p class="Toc1">Tutorial 2: <a href="#T2">Advanced IronPython</a></p>
  75	<p class="Toc2">Exercise 1: <a href="#T2.1">Events and Delegates</a></p>
  76	<p class="Toc3">Task 1: <a href="#T2.1.1">File System Watcher</a></p>
  77	<p class="Toc3">Task 2: <a href="#T2.1.2">Improving the event handler</a></p>
  78	<p class="Toc3">Task 3: <a href="#T2.1.3">Defining events in Python</a></p>
  79	<p class="Toc2">Exercise 2: <a href="#T2.2">Windows Forms</a></p>
  80	<p class="Toc3">Task 1: <a href="#T2.2.1">Simple Windows Forms application</a></p>
  81	<p class="Toc2">Exercise 3: <a href="#T2.3">Windows Presentation Foundation (Avalon)</a></p>
  82	<p class="Toc3">Task 1: <a href="#T2.3.1">Simple Avalon Application</a></p>
  83	<p class="Toc3">Task 2: <a href="#T2.3.2">Avalon calculator</a></p>
  84	<p class="Toc1">Tutorial 3: <a href="#T3">IronPython and COM interoperability</a></p>
  85	<p class="Toc2">Exercise 1: <a href="#T3.1">Merlin the Wizard</a></p>
  86	<p class="Toc3">Task 1: <a href="#T3.1.1">Creating COM interop assemblies</a></p>
  87	<p class="Toc3">Task 2: <a href="#T3.1.2">Using COM objects from IronPython</a></p>
  88	<p class="Toc2">Exercise 2: <a href="#T3.2">Use Word for Spell Checking</a></p>
  89	<p class="Toc3">Task 1: <a href="#T3.2.1">Accessing Word and Checking
  90	Spelling</a></p>
  91	<p class="Toc3">Task 2: <a href="#T3.2.2">Use Windows Form Dialog to Correct
  92	Spelling</a></p>
  93	<p class="Toc1">Tutorial 4: <a href="#T4">Debugging IronPython program</a></p>
  94	<p class="Toc2">Exercise 1: <a href="#T4.1">Debugging IronPython programs</a></p>
  95	<p class="Toc3">Task 1: <a href="#T4.1.1">Debugging IronPython programs using Microsoft CLR Debugger</a></p>
  96	<p class="Toc1">Tutorial 5: <a href="#T5">Extending IronPython</a></p>
  97	<p class="Toc2">Exercise 1: <a href="#T5.1">Extending using C#</a></p>
  98	<p class="Toc3">Task 1: <a href="#T5.1.1">Implementing simple class - constructor and ToString</a></p>
  99	<p class="Toc3">Task 2: <a href="#T5.1.2">Making the object enumerable</a></p>
 100	<p class="Toc3">Task 3: <a href="#T5.1.3">Adding custom operator</a></p>
 101	<p class="Toc3">Task 4: <a href="#T5.1.4">Adding delegate</a></p>
 102	<p class="Toc2">Exercise 2: <a href="#T5.2">Extending using Visual Basic.NET</a></p>
 103	<p class="Toc3">Task 1: <a href="#T5.2.1">Implementing simple class - constructor and ToString</a></p>
 104	<p class="Toc3">Task 2: <a href="#T5.2.2">Making the object enumerable</a></p>
 105	<p class="Toc3">Task 3: <a href="#T5.2.3">Adding custom operator</a></p>
 106	<p class="Toc3">Task 4: <a href="#T5.2.4">Adding delegate</a></p>
 107    <p class="Toc1">Tutorial 6: <a href="#T7">Using Visual Studio to Edit .py
 108	Files and Debug Them</a></p>
 109	<p class="Toc2">Exercise 1: <a href="#T6.1">Setting up Visual Studio for
 110	IronPython Debugging</a></p>
 111	<p class="Toc3">Task 1: <a href="#T6.1.1">Setting up Visual Studio for
 112	IronPython Debugging</a></p>
 113</div>
 114<div class="Section2">
 115	<h1><a name="Intro">Introduction</a></h1>
 116	<p class="Normal">IronPython is the .NET implementation of the Python programming language
 117        (<a href="http://www.python.org">www.python.org</a>).&nbsp; It's a dynamically typed language with support
 118        for many programming paradigms such as object-oriented programming, and also allows
 119	you to seamlessly use .NET code.</p>
 120	<p class="Normal">&nbsp;</p>
 121	<p class="Normal">The goal of this tutorial is to quickly
 122	familiarize you with the IronPython console, and to show you how to make use of the extensive .NET libraries available.&nbsp;
 123	This tutorial also shows you how to get started in more specialized areas
 124	such as interoperating with COM, extending IronPython with C#, and embedding
 125	IronPython.&nbsp; This tutorial is NOT meant to be an introduction to Python
 126	itself, and if you're looking for that, we recommend you start with the
 127	tutorial at <a href="http://docs.python.org/tut/tut.html">www.python.org</a>
 128	or the often recommended book <i>Learning Python</i> by Mark Lutz and David
 129	Ascher. For an introduction to both the Python language as well as the unique
 130	capabilities of IronPython, we recommend <i>IronPython in Action</i> by 
 131	Michael Foord<br><br>
 132        Some of the exercises in this tutorial require prerequisites.&nbsp; The prerequisites to successfully complete the whole tutorial are:</p>
 133	<ul type="disc">
 134		<li class="Normal">Microsoft .NET Framework Version 3.5
 135		<ul type="circle">
 136			<li class="Normal">Required to run IronPython on Windows Vista.</li>
 137			<li class="Normal">Microsoft .NET Framework Version 3.0 SP1 or higher needed for Windows operating systems released prior to Windows Vista</li>
 138			<li class="Normal">Download from
 139			<a href="http://www.microsoft.com/downloads/details.aspx?familyid=333325FD-AE52-4E35-B531-508D977D32A6&displaylang=en   ">
 140			here</a>.</li>
 141		</ul>
 142		</li>
 143	</ul>
 144	<ul>
 145		<li class="Normal">Visual Studio 2005 or 2008<ul type="circle">
 146			<li class="Normal">Required for &quot;Setting up Visual Studio for IronPython Debugging&quot; tutorials.</li>
 147		</ul>
 148		</li>
 149	</ul>
 150	<ul>
 151		<li class="Normal">Microsoft Word<ul type="circle">
 152			<li class="Normal">Required for &quot;Use Word for Spell Checking&quot; and &quot;Merlin the Wizard&quot; tutorials.</li>
 153		</ul>
 154		</li>
 155	</ul>
 156	<ul>
 157		<li class="Normal"><a name="Mapack">Mapack</a> (example assembly found
 158		on the internet)<ul>
 159			<li>Required for the &quot;Basic IronPython&quot; tutorial, exercise &quot;Loading .NET
 160			Libraries&quot;.</li>
 161			<li>Download Mapack from
 162			<a href="http://www.lutzroeder.com/dotnet/">here</a> (direct link
 163			to the Mapack.zip download is
 164			<a href="http://www.lutzroeder.com/dotnet/Download.aspx?File=Mapack">
 165			here</a>).</li>
 166			<li>Extract Mapack.dll from the zip file directly into the Tutorial
 167			directory.</li>
 168		</ul>
 169		</li>
 170	</ul>
 171	<p class="Normal">&nbsp;</p>
 172	<p class="Body">Visual Studio 2005 or 2008 can be used in place of the Microsoft .NET
 173	Framework Version 2.0 and the .NET Framework 2.0 Software Development Kit (SDK).
 174	Since Visual Studio installs both the .NET Framework 2.0 and the .NET Framework
 175	SDK, there is no need to install those explicitly if you have Visual Studio
 176	2005 available. Visual Studio 2008 also installs .NET Framework 3.5. </p>
 177	<p class="Body">This tutorial also assumes that you will launch the
 178	IronPython console (c:\ironpython\ipy.exe) from the tutorial directory.&nbsp;
 179	When the tutorials direct you to start the IronPython console from the tutorial directory,
 180	you should change to the tutorial directory (&gt;cd c:\ironpython\tutorial)
 181	and launch the console with the tutorial as your working directory (&gt;..\ipy.exe). If you
 182	install IronPython via the MSI installer, it will install to c:\Program Files\IronPython 2.0 
 183	by default. In this scenario, you can still run the tutorial, but several tutorials require 
 184	write access to the tutorial directory, which will require administrator access if IronPython
 185	is installed under Program Files.</p>
 186	<p class="Body">&nbsp;</p>
 187	<h1><a name="T1">Tutorial 1: Basic IronPython</a></h1>
 188	<p class="Body">The emphasis of this tutorial is on the basic interaction with
 189	the IronPython interpreter and using the interactive environment to explore
 190	the .NET libraries.</p>
 191	<p class="Body">Estimated time to complete this tutorial: <b>30 minutes</b></p>
 192	<p class="Body">The objective of this tutorial is to launch the IronPython interpreter,
 193	explore the environment of the interactive console and use IronPython to interact
 194	with .NET libraries.</p>
 195	<p class="Body">The exercises in this tutorial are:</p>
 196	<ul>
 197		<li>
 198		<p class="ExerciseList"><a href="#T1.1">The IronPython interactive console</a></p>
 199		</li>
 200		<li>
 201		<p class="ExerciseList"><a href="#T1.2">Using the standard .NET libraries
 202		from IronPython</a></p>
 203		</li>
 204		<li>
 205		<p class="ExerciseList"><a href="#T1.3">Loading additional .NET libraries</a></p>
 206		</li>
 207	</ul>
 208	<h2><a name="T1.1">Exercise 1: The IronPython interactive console</a></h2>
 209	<p class="Body">In this exercise, you will start the IronPython interactive
 210	interpreter and perform simple tasks to become acquainted with the IronPython
 211	environment.</p>
 212	<p class="Normal">If you are familiar with using the Python interactive console,
 213	the import statement and exploring the Python interactive environment using
 214	dir() function and __doc__ attribute, you can <a href="#T1.2">skip this exercise</a>.</p>
 215	<h3><a name="T1.1.1">Task 1: IronPython console</a></h3>
 216	<ol>
 217		<li>
 218		<p class="Step">Start the IronPython console from the tutorial directory
 219		by changing to the tutorial directory (&gt;cd c:\ironpython\tutorial) and
 220		launching the console c:\ironpython\ipy.exe executable (&gt;..\ipy.exe).&nbsp;
 221		This is how you should always launch the console for the tutorials, but
 222		from now on, we'll just direct you to &quot;start the IronPython console from
 223		the tutorial directory&quot;.</p>
 224		</li>
 225	</ol>
 226	<p class="Code-Highlighted">IronPython 2.0 (2.0.0.0) on .NET 2.0.50727.3053<br />
 227	Copyright (c) Microsoft Corporation. All rights reserved.</p>
 228	<p class="Code-Highlighted">&gt;&gt;&gt; _</p>
 229	<ol start="2">
 230		<li>
 231		<p class="Step">Execute simple statements listed below.&nbsp; After each statement IronPython prints the result, if any, and awaits more input.&nbsp;
 232		(The input line starting with &quot;for&quot; requires an extra return or enter
 233		key press because the interpreter prompts for more statements in the
 234		'for' loop.)</p>
 235		</li>
 236	</ol>
 237	<p class="TypedExample">2+2</p>
 238	<p class="TypedExample">print &quot;Hello World!&quot;</p>
 239	<p class="TypedExample">for i in range(3): print i</p>
 240	<p class="TypedExample">x = 10</p>
 241	<p class="TypedExample">print x</p>
 242	<p class="Stepnonumbering">&nbsp;</p>
 243	<p class="Stepnonumbering">After this step, the console window will contain
 244	the following text:</p>
 245	<p class="Code-Highlighted">&gt;&gt;&gt; 2+2</p>
 246	<p class="Code-Background">4</p>
 247	<p class="Code-Highlighted">&gt;&gt;&gt; print &quot;Hello World!&quot;</p>
 248	<p class="Code-Background">Hello World!</p>
 249	<p class="Code-Highlighted">&gt;&gt;&gt; for i in range(3): print i</p>
 250	<p class="Code-Highlighted">...</p>
 251	<p class="Code-Background">0<br />
 252	1<br />
 253	2</p>
 254	<p class="Code-Highlighted">&gt;&gt;&gt; x = 10<br />
 255	&gt;&gt;&gt; print x</p>
 256	<p class="Code-Background"></p>
 257	<p class="Code-Background">10</p>
 258	<p class="Code-Highlighted">&gt;&gt;&gt; </p>
 259	<ol start="3">
 260		<li>
 261		<p class="Step">IronPython console supports multi-line statements, often
 262		used by function definitions.&nbsp; IronPython prompts for additional lines of
 263		multi-line statements using:</p>
 264		</li>
 265	</ol>
 266	<p class="Code-Highlighted">...</p>
 267	<p class="Code-Background"></p>
 268	<p class="Stepnonumbering">Unlike C# or Java, where blocks of code are grouped by curly brackets "{...}",
 269        blocks of code in Python are grouped based on their level of indentation.&nbsp; Every new block of code
 270        must be indented one more level than the previous block of code.&nbsp; Blocks of code are used for
 271        function and class definitions as well as 'if' statements and loops. </p>
 272	<p class="Stepnonumbering">Define the &quot;add&quot; function (note, you
 273	need to enter spaces before the 'return' statement):</p>
 274	<p class="TypedExample">def add(a, b):<br>
 275&nbsp;&nbsp;&nbsp; return a + b</p>
 276	<p class="Stepnonumbering">To complete the function definition, press Enter
 277	once more at this point</p>
 278	<p class="TypedExample">add(3, 2)</p>
 279	<p class="TypedExample">add(&quot;Iron&quot;, &quot;Python&quot;)</p>
 280	<p class="Stepnonumbering">After this step, the console contents will be:</p>
 281	<p class="Code-Highlighted">&gt;&gt;&gt; def add(a, b):<br />
 282	...&nbsp;&nbsp;&nbsp;&nbsp; return a + b<br />
 283	...<br />
 284	&gt;&gt;&gt; add(3, 2)</p>
 285	<p class="Code-Background">5</p>
 286	<p class="Code-Highlighted">&gt;&gt;&gt; add(&quot;Iron&quot;, &quot;Python&quot;)</p>
 287	<p class="Code-Background">&#39;IronPython&#39;</p>
 288	<p class="Code-Highlighted">&gt;&gt;&gt; </p>
 289	<p class="Step">&nbsp;</p>
 290	<ol start="4">
 291		<li>
 292		<p class="Step">To exit the IronPython interactive console, type Ctrl+Z and Enter (alternatively,
 293		press F6 followed by Enter).</p>
 294		</li>
 295	</ol>
 296	<p class="TypedExample">^Z</p>
 297	<h3><a name="T1.1.2">Task 2: Built-in modules and interactive exploration</a></h3>
 298	<ol>
 299		<li>
 300		<p class="Step">Start the IronPython console from the tutorial directory
 301		(see <a href="#Intro">Introduction</a> for details).</p>
 302		</li>
 303		<li>
 304		<p class="Step">Using the built-in dir() function, list the contents of
 305		the IronPython environment:</p>
 306		</li>
 307	</ol>
 308	<p class="TypedExample">dir()</p>
 309	<p class="Stepnonumbering">The output in the console window will be:</p>
 310	<p class="Code-Highlighted">&gt;&gt;&gt; dir()</p>
 311	<p class="Code-Background">['__builtins__', '__doc__', '__name__']<br />
 312</p>
 313	<ol start="3">
 314		<li>
 315		<p class="Step">IronPython comes with several built-in modules, the most
 316		frequently used one being &quot;sys&quot;.&nbsp; Import &quot;sys&quot; module using the &quot;import&quot;
 317		statement:</p>
 318		</li>
 319	</ol>
 320	<p class="TypedExample">import sys</p>
 321	<ol start="4">
 322		<li>
 323		<p class="Step">The Python import statement is similar to the &quot;using&quot; statement
 324		of C# or &quot;Imports&quot; statement of Visual Basic. The important difference is
 325		that the C# and VB statements bring the names from the imported namespace
 326		into the global namespace to be accessed directly. Python’s import doesn’t
 327		do that. To access the names or attributes in an imported module, prefix
 328		the
 329		names with the module's name:</p>
 330		</li>
 331	</ol>
 332	<p class="UserExample">sys.version</p>
 333	<ol start="5">
 334		<li>
 335		<p class="Step">Use the dir() function to explore the environment:</p>
 336		</li>
 337	</ol>
 338	<p class="TypedExample">dir()</p>
 339	<p class="Stepnonumbering" style="margin-left: 0.5in">The environment (global namespace) has changed, now
 340	it contains the &quot;sys&quot; module:</p>
 341	<p class="Code-Highlighted">&gt;&gt;&gt; dir()</p>
 342	<p class="Code-Background">['__builtins__', '__doc__', '__name__', 'sys']</p>
 343	<ol start="6">
 344		<li>
 345		<p class="Step">Use the dir() function to explore the contents of the &quot;sys&quot;
 346		module:</p>
 347		</li>
 348	</ol>
 349	<p class="TypedExample">dir(sys)</p>
 350	<p class="HiddenOutput">['__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getrecursionlimit', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdefaultencoding', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions', 'winver']</p>
 351	<ol start="7">
 352		<li>
 353		<p class="Step">Print the values of some of the &quot;sys&quot; module attributes:</p>
 354		</li>
 355	</ol>
 356	<p class="TypedExample">sys.path</p>
 357	<p class="LooseVerify">['.', '%MERLIN_ROOT%\\Test\\IronPythonTutorial', '%MERLIN_ROOT%\\Test', '%MERLIN_ROOT%\\Languages\\IronPython\\Tutorial', '%MERLIN_ROOT%\\Languages\\IronPython\\Tests', '%MERLIN_ROOT%\\Bin\\Debug\\Lib']</p>
 358	<p class="TypedExample">sys.executable</p>
 359	<p class="LooseVerify">'%MERLIN_ROOT%\\Bin\\Debug\\ipy.exe'</p>
 360	<h3><a name="T1.1.3">Task 3: External Python modules</a></h3>
 361	<p class="Normal">This task uses the module &quot;first.py&quot; located in the Tutorial
 362	folder.</p>
 363	<ol>
 364		<li>
 365		<p class="Step">Import the &quot;first.py&quot; module located in the Tutorial
 366		(because you launched ipy.exe from the Tutorial directory, &quot;first&quot; will
 367		be found on your sys.path):</p>
 368		</li>
 369	</ol>
 370	<p class="TypedExample">import first</p>
 371	<p class="Code-Background"></p>
 372	<ol start="2">
 373		<li>
 374		<p class="Step">Explore the module &quot;first&quot; using dir() function:</p>
 375		</li>
 376	</ol>
 377	<p class="TypedExample">dir(first)</p>
 378	<p class="Code-Highlighted">&gt;&gt;&gt; dir(first)</p>
 379	<p class="Code-Background">['__builtins__', '__file__', '__name__', 'add', 'factorial', 'hi']</p>
 380	<ol start="3">
 381		<li>
 382		<p class="Step">Print the documentation for the &quot;add&quot; and &quot;factorial&quot; functions,
 383		using __doc__ attribute:</p>
 384		</li>
 385	</ol>
 386	<p class="TypedExample">first.add.__doc__</p>
 387	<p class="TypedExample">first.factorial.__doc__</p>
 388	<p class="Stepnonumbering">&nbsp;</p>
 389	<p class="Stepnonumbering">The __doc__ attribute will be later used also for
 390	exploring .NET methods and their parameter types.</p>
 391	<p class="Code-Highlighted">&gt;&gt;&gt; first.add.__doc__</p>
 392	<p class="Code-Background">&#39;add(a, b) -&gt; returns a + b&#39;</p>
 393	<p class="Code-Highlighted">&gt;&gt;&gt; first.factorial.__doc__</p>
 394	<p class="Code-Background">&#39;factorial(n) -&gt; returns factorial of n&#39;</p>
 395	<ol start="4">
 396		<li>
 397		<p class="Step">Call the methods in the &quot;first&quot; module and print the contents
 398		of the &quot;hi&quot; attribute</p>
 399		</li>
 400	</ol>
 401	<p class="TypedExample">first.add(1,2)</p>
 402	<p class="TypedExample">first.factorial(5)</p>
 403	<p class="TypedExample">first.hi</p>
 404	<p class="Stepnonumbering">The expected output is:</p>
 405	<p class="Code-Highlighted">&gt;&gt;&gt; first.add(1,2)</p>
 406	<p class="Code-Background">3</p>
 407	<p class="Code-Highlighted">&gt;&gt;&gt; first.factorial(5)</p>
 408	<p class="Code-Background">120</p>
 409	<p class="Code-Highlighted">&gt;&gt;&gt; first.hi</p>
 410	<p class="Code-Background">&#39;Hello from IronPython!&#39;</p>
 411	<ol start="5">
 412		<li>
 413		<p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
 414		by Enter)</p>
 415		</li>
 416	</ol>
 417	<h2><a name="T1.2">Exercise 2: Using the standard .NET libraries from IronPython</a></h2>
 418	<p class="Body">The power of IronPython lies within the ability to seamlessly
 419	access the wealth of .NET libraries. This exercise will demonstrate how the
 420	.NET libraries can be used from IronPython.</p>
 421	<p class="Body">In this exercise, you will use the standard .NET libraries from
 422	IronPython. </p>
 423	<h3><a name="T1.2.1">Task 1: Basic .NET library use</a></h3>
 424	<ol>
 425		<li>
 426		<p class="Step">Start the IronPython console from the tutorial directory
 427		(see <a href="#Intro">Introduction</a> for details).</p>
 428		</li>
 429		<li>
 430		<p class="Step">Using the &quot;import&quot; statement, import the .NET System namespace:</p>
 431		</li>
 432	</ol>
 433	<p class="TypedExample">import System</p>
 434	<p class="Code-Background"></p>
 435	<ol start="3">
 436		<li>
 437		<p class="Step">Explore the System.Environment class and access some of
 438		its properties:</p>
 439		</li>
 440	</ol>
 441	<p class="TypedExample">dir(System.Environment)</p>
 442	<p class="UserCode">System.Environment.OSVersion</p>
 443	<p class="TypedExample">System.Environment.CommandLine</p>
 444	<p class="Stepnonumbering">The expected output of these commands is as follows
 445	(with some ellipsis for convenience):</p>
 446	<p class="Code-Highlighted">&gt;&gt;&gt; dir(System.Environment)</p>
 447	<p class="HiddenOutput">['CommandLine', 'CurrentDirectory', 'Equals', 'Exit', 'ExitCode', 'ExpandEnvironmentVariables', 'FailFast', 'GetCommandLineArgs', 'GetEnvironmentVariable', 'GetEnvironmentVariables', 'GetFolderPath', 'GetHashCode', 'GetLogicalDrives', 'GetType', 'HasShutdownStarted', 'MachineName', 'MemberwiseClone', 'NewLine', 'OSVersion', 'ProcessorCount', 'ReferenceEquals', 'SetEnvironmentVariable', 'SpecialFolder', 'StackTrace', 'SystemDirectory', 'TickCount', 'ToString', 'UserDomainName', 'UserInteractive', 'UserName', 'Version', 'WorkingSet', '__all__', '__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__']</p>
 448	<p class="Code-Highlighted">&gt;&gt;&gt; System.Environment.OSVersion</p>
 449	<p class="Code-Highlighted">&lt;System.OperatingSystem object at 0x000000000000002B [Microsoft Windows NT 6.0.6000.0]</p>
 450	<p class="Code-Highlighted">&gt;&gt;&gt; System.Environment.CommandLine</p>
 451	<p class="Code-Highlighted">&#39;C:\\IronPython\\ipy.exe&#39;
 452	<p class="LooseVerify">'"%MERLIN_ROOT%\\Bin\\Debug\\ipy.exe"'
 453	</p>
 454	<ol start="4">
 455		<li>
 456		<p class="Step">The import statement can be used also to import contents of
 457		a class or module into the global namespace.&nbsp; Use the &quot;from ... import ...&quot;
 458		flavor of the import statement to do that and explore the contents of the
 459		global namespace using dir().</p>
 460		</li>
 461	</ol>
 462	<p class="TypedExample">from System.Math import *</p>
 463	<p class="UserCode">dir()</p>
 464	<p class="HiddenCode">set1 = set(dir())
 465set2 = set(dir(object))
 466list(set1-set2)
 467	</p>
 468	<p class="HiddenOutput">
 469
 470	['Tan','Sqrt','Acos','Sin','Abs','Round','Pow','Floor','Exp','Log','Atan2','IEEERemainder','Atan','__builtins__','Asin','System','E','Cosh','__name__', 'Ceiling','DivRem','BigMul','Cos','Truncate','Min','Tanh','Log10','Sign','Max','Sinh','PI']</p>
 471	<p class="Stepnonumbering">Now you can call Math methods without having to specify
 472	the namespace and class name prefix:</p>
 473	<p class="TypedExample">Sin(PI/2)</p>
 474	<p class="Stepnonumbering">The expected output is:</p>
 475	<p class="Code-Highlighted">&gt;&gt;&gt; from System.Math import *</p>
 476	<p class="Code-Highlighted">&gt;&gt;&gt; dir()</p>
 477	<p class="Code-Highlighted">[&#39;Abs&#39;, &#39;Acos&#39;, &#39;Asin&#39;, &#39;Atan&#39;, &#39;Atan2&#39;, &#39;BigMul&#39;, &#39;Ceiling&#39;, &#39;Cos&#39;, &#39;Cosh&#39;, &#39;DivRem&#39;, &#39;E&#39;, &#39;Equals&#39;, &#39;Exp&#39;, &#39;Floor&#39;, &#39;GetHashCode&#39;, &#39;GetType&#39;, &#39;IEEERemainder&#39;, &#39;Log&#39;, &#39;Log10&#39;, &#39;Max&#39;, &#39;Min&#39;, &#39;PI&#39;, &#39;Pow&#39;, &#39;Round&#39;, &#39;Sign&#39;, &#39;Sin&#39;, &#39;Sinh&#39;, &#39;Sqrt&#39;, &#39;System&#39;, &#39;Tan&#39;, &#39;Tanh&#39;, &#39;ToString&#39;, &#39;Truncate&#39;, &#39;__builtins__&#39;, &#39;__doc__&#39;, &#39;__name__&#39;]</p>
 478	<p class="Code-Highlighted">&gt;&gt;&gt; Sin(PI/2)</p>
 479	<p class="Code-Background">1.0</p>
 480	<h3><a name="T1.2.2">Task 2: Working with .NET classes</a></h3>
 481	<ol>
 482		<li>
 483		<p class="Step">Import the contents of the &quot;System.Collections&quot; namespace
 484		into the global namespace:</p>
 485		</li>
 486	</ol>
 487	<p class="TypedExample">from System.Collections import *</p>
 488	<p class="Code-Background"></p>
 489	<ol start="2">
 490		<li>
 491		<p class="Step">Create instance of the Hashtable class and explore the instance
 492		using dir():</p>
 493		</li>
 494	</ol>
 495	<p class="TypedExample">h = Hashtable()</p>
 496	<p class="Code-Background"></p>
 497	<p class="UserCode">dir(h)</p>
 498	<p class="HiddenCode">set1 = set(dir(h))
 499set2 = set(dir(object))
 500list(set1-set2)</p>
 501	<p class="HiddenOutput">
 502        
 503        ['Clone','ContainsValue','SyncRoot','hcp','__setitem__','__contains__','KeyEquals','IsSynchronized','GetEnumerator','GetHash','Contains','Item','Values','ContainsKey','Remove','OnDeserialization','__iter__','Add','Synchronized','EqualityComparer','__len__','comparer','Keys','Clear','IsReadOnly','CopyTo','IsFixedSize','__add__','GetObjectData','Count','__getitem__']</p>
 504	<ol start="3">
 505		<li>
 506		<p class="Step">Insert&nbsp;a few elements into the hash table:</p>
 507		</li>
 508	</ol>
 509	<p class="TypedExample">h[&quot;a&quot;] = &quot;IronPython&quot;</p>
 510	<p class="Code-Background"></p>
 511	<p class="TypedExample">h[&quot;b&quot;] = &quot;Tutorial&quot;</p>
 512	<p class="Code-Background"></p>
 513	<p class="Stepnonumbering">&nbsp;</p>
 514	<p class="Stepnonumbering">IronPython supports the C# - style syntax for accessing
 515	the hash table elements.&nbsp; The same syntax applies to any index-able object (Arrays,
 516	Array lists etc):</p>
 517	<p class="TypedExample">h[&quot;a&quot;]</p>
 518	<p class="Stepnonumbering" style="page-break-after:avoid">&nbsp;</p>
 519	<p class="Stepnonumbering" style="page-break-after:avoid">The output of this
 520	step will be:</p>
 521	<p class="Code-Background" style="page-break-after:avoid">&gt;&gt;&gt; h[&quot;a&quot;] = &quot;IronPython&quot;<br />
 522	&gt;&gt;&gt; h[&quot;b&quot;] = &quot;Tutorial&quot;</p>
 523	<p class="Code-Highlighted" style="page-break-after:avoid">&gt;&gt;&gt; h[&quot;a&quot;]</p>
 524	<p class="Code-Background">&#39;IronPython&#39;</p>
 525	<ol start="4">
 526		<li>
 527		<p class="Step">Enumerate the contents of the hash table using the &quot;for
 528		... in ...&quot; statement. The hash table elements are instances of &quot;DictionaryEntry&quot;
 529		class. Print the &quot;Key&quot; and &quot;Value&quot; properties of each entry:</p>
 530		</li>
 531	</ol>
 532	<p class="TypedExample">for e in h: print e.Key, &quot;:&quot;, e.Value</p>
 533	<p class="Stepnonumbering">&nbsp;</p>
 534	<p class="Stepnonumbering">The expected output in the console is (the input
 535	line starting with &quot;for&quot; requires an extra return or enter key press because
 536	the interpreter prompts for more statements in the 'for' loop.):</p>
 537	<p class="Code-Highlighted">&gt;&gt;&gt; for e in h: print e.Key, &quot;:&quot;, e.Value<br>
 538	...</p>
 539	<p class="Code-Background">a : IronPython<br />
 540	b : Tutorial</p>
 541	<ol start="5">
 542		<li>
 543		<p class="Step">You can initialize the collection classes by passing in
 544		the Python built-in list or tuple data types as arguments.&nbsp; You can
 545		create a Python list by specifying the list of elements in square brackets: [1,2,3].&nbsp;
 546		You create tuples by specifying elements in the parentheses: (1,2,3).</p>
 547		</li>
 548	</ol>
 549	<p class="TypedExample">l = ArrayList([1,2,3])</p>
 550	<p class="Code-Background"></p>
 551	<p class="TypedExample">for i in l: print i</p>
 552	<p class="TypedExample">s = Stack((1,2,3))</p>
 553	<p class="TypedExample">while s.Count: s.Pop()</p>
 554	<p class="Stepnonumbering">&nbsp;</p>
 555	<p class="Stepnonumbering">The expected output is:</p>
 556	<p class="Code-Highlighted">&gt;&gt;&gt; l = ArrayList([1,2,3])<br />
 557	&gt;&gt;&gt; for i in l: print i<br>
 558	...</p>
 559	<p class="Code-Background">1<br />
 560	2<br />
 561	3</p>
 562	<p class="Code-Background"></p>
 563	<p class="Code-Highlighted">&gt;&gt;&gt; s = Stack((1,2,3))<br />
 564	&gt;&gt;&gt; while s.Count: s.Pop()<br>...</p>
 565	<p class="Code-Background">3<br />
 566	2<br />
 567	1</p>
 568	<h3><a name="T1.2.3">Task 3: Generics</a></h3>
 569	<ol>
 570		<li>
 571		<p class="Step">Import the Generic collections from the System.Collections.Generic
 572		namespace:</p>
 573		</li>
 574	</ol>
 575	<p class="TypedExample">from System.Collections.Generic import *</p>
 576	<p class="Code-Background"></p>
 577	<ol start="2">
 578		<li>
 579		<p class="Step">To instantiate a generic class, the generic type arguments
 580		must be specified.&nbsp; IronPython uses the following syntax to specify the type
 581		arguments: generic_type[type_argument, ...].&nbsp; Create an instance of generic
 582        list of string:</p>
 583		</li>
 584	</ol>
 585	<p class="TypedExample">l = List[str]()</p>
 586		<p class="Code-Background"></p>
 587	<ol start="3">
 588		<li>
 589		<p class="Step">Add string values into the list. Since we created a list of
 590		string, adding strings is possible:</p>
 591		</li>
 592	</ol>
 593	<p class="TypedExample">l.Add(&quot;Hello&quot;)</p>
 594		<p class="Code-Background"></p>
 595	<p class="TypedExample">l.Add(&quot;Hi&quot;)</p>
 596		<p class="Code-Background"></p>
 597	<ol start="4">
 598		<li>
 599		<p class="Step">Try adding objects of types other than string:</p>
 600		</li>
 601	</ol>
 602	<p class="ExceptionExample">l.Add(3)</p>
 603	<p class="Code-Background"></p>
 604	<p class="ExceptionExample">l.Add(2.5)</p>
 605	<p class="Code-Background"></p>
 606	<p class="ExceptionExample">l.Add([1,2,3])</p>
 607	<p class="Code-Background"></p>
 608	<p class="Stepnonumbering">&nbsp;</p>
 609	<p class="Stepnonumbering">Obviously, adding non-strings will fail with type
 610	error:</p>
 611	<p class="Code-Highlighted">&gt;&gt;&gt; l.Add(3)</p>
 612	<p class="Code-Highlighted">Traceback (most recent call last):<br>
 613
 614  File , line unknown, in Initialize##40
 615	<br>
 616TypeError: expected str, got int
 617	<br></p>
 618	<ol start="5">
 619		<li>
 620		<p class="Step">Enumerate the generic collection:</p>
 621		</li>
 622	</ol>
 623	<p class="TypedExample">for i in l: print i</p>
 624	<p class="Stepnonumbering">The output will be:</p>
 625	<p class="Code-Highlighted">&gt;&gt;&gt; for i in l: print i<br>...</p>
 626	<p class="Code-Background">Hello<br />
 627	Hi</p>
 628	<p class="ExceptionOutput">TypeError: expected str, got int
 629TypeError: expected str, got float
 630TypeError: expected str, got list</p>
 631	<ol start="6">
 632		<li>
 633		<p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
 634		by Enter)</p>
 635		</li>
 636	</ol>
 637	<h2><a name="T1.3">Exercise 3: Loading .NET libraries</a></h2>
 638	<p class="Body">IronPython can directly import only some of the .NET libraries
 639	- the most commonly used ones.&nbsp; To use additional .NET libraries, they must be
 640	explicitly referenced.&nbsp; IronPython maintains a list of all referenced
 641	assemblies (see clr.References in Task 1).&nbsp; To add a reference to a .NET assembly, use the functions
 642	available in the built-in &quot;clr&quot; module:</p>
 643	<ul>
 644		<li>
 645		<p class="Body"><b>clr.AddReference</b> adds a reference to the .NET assembly
 646		either by passing the .NET assembly object directly, or specifying the file
 647		name or the assembly name (full or partial). This function is provided primarily
 648		for the interactive exploration. We recommend using the following functions
 649		in the code modules, since they provide more control over which assembly
 650		is being loaded.</p>
 651		</li>
 652		<li>
 653		<p class="Body"><b>clr.AddReferenceToFile</b> adds reference to the assembly
 654		specified by its file name. This function will load the assembly from the
 655		file regardless of the assembly version. As a result, it doesn&#39;t guarantee
 656		that the correct assembly version is being loaded. To guarantee that correct
 657		assembly version is being loaded, use clr.AddReferenceByName. Moreover,
 658		AddReferenceToFile requires that the assembly be located in a
 659		directory listed in sys.path.</p>
 660		</li>
 661		<li>
 662		<p class="Body"><b>clr.AddReferenceToFileAndPath</b> provides similar
 663		functionality to AddReferenceToFile. The difference is that it accepts
 664		absolute path and before loading the assembly, AddReferenceToFileAndPath
 665		adds the file path into sys.path.</p>
 666		</li>
 667		<li>
 668		<p class="Body"><b>clr.AddReferenceByName</b> adds reference to the assembly
 669		specified by its full assembly name, for example: &#39;System.Xml, Version=2.0.0.0,
 670		Culture=neutral, PublicKeyToken=b77a5c561934e089&#39;.</p>
 671		</li>
 672		<li>
 673		<p class="Body"><b>clr.AddReferenceByPartialName</b> adds reference to the
 674		assembly by specifying a partial assembly name. This function cannot guarantee
 675		that the correct version of the assembly is being loaded. Use clr.AddReferenceByName
 676		to add reference to specific version of the assembly.</p>
 677		</li>
 678	</ul>
 679	<h3><a name="T1.3.1">Task 1: Using System.Xml - AddReference</a></h3>
 680	<ol>
 681		<li>
 682		<p class="Step">Start the IronPython console from the tutorial directory
 683		(see <a href="#Intro">Introduction</a> for details).</p>
 684		</li>
 685		<li>
 686		<p class="Step">To import System.Xml, the reference to the assembly containing
 687		the Xml components must be first added to IronPython.&nbsp; Add reference to System.Xml
 688		using the following code&nbsp; (you can enter &quot;clr.References&quot; before
 689		and after the call to clr.AddReference to see it change if you want):</p>
 690		</li>
 691	</ol>
 692	<p class="TypedExample">import clr</p>
 693	<p class="Code-Background"></p>
 694	<p class="TypedExample">clr.AddReference(&quot;System.Xml&quot;)</p>
 695	<p class="Code-Background"></p>
 696	<p class="TypedExample">from System.Xml import *</p>
 697	<p class="Code-Background"></p>
 698	<p class="TypedExample">dir()</p>
 699	<p class="HiddenOutput">['ConformanceLevel', 'EntityHandling', 'Formatting', 'IHasXmlNode', 'IXmlLineInfo', 'IXmlNamespaceResolver', 'NameTable', 'NewLineHandling', 'ReadState', 'Schema', 'Serialization', 'ValidationType', 'WhitespaceHandling', 'WriteState', 'XPath', 'XmlAttribute', 'XmlAttributeCollection', 'XmlCDataSection', 'XmlCharacterData', 'XmlComment', 'XmlConvert', 'XmlDateTimeSerializationMode', 'XmlDeclaration', 'XmlDocument', 'XmlDocumentFragment', 'XmlDocumentType', 'XmlElement', 'XmlEntity', 'XmlEntityReference', 'XmlException', 'XmlImplementation', 'XmlLinkedNode', 'XmlNameTable', 'XmlNamedNodeMap', 'XmlNamespaceManager', 'XmlNamespaceScope', 'XmlNode', 'XmlNodeChangedAction', 'XmlNodeChangedEventArgs', 'XmlNodeChangedEventHandler', 'XmlNodeList', 'XmlNodeOrder', 'XmlNodeReader', 'XmlNodeType', 'XmlNotation', 'XmlOutputMethod', 'XmlParserContext', 'XmlProcessingInstruction', 'XmlQualifiedName', 'XmlReader', 'XmlReaderSettings', 'XmlResolver', 'XmlSecureResolver', 'XmlSignificantWhitespace', 'XmlSpace', 'XmlText', 'XmlTextReader', 'XmlTextWriter', 'XmlTokenizedType', 'XmlUrlResolver', 'XmlValidatingReader', 'XmlWhitespace', 'XmlWriter', 'XmlWriterSettings', 'Xsl', '__builtins__', '__doc__', '__name__', 'clr']</p>
 700	<ol start="3">
 701		<li>
 702		<p class="Step">Note that the clr.AddReference function accepts either System.Reflection.Assembly object or string
 703		as a parameter. The string parameter can
 704		be a full assembly name, a partial assembly name, or a file name. For more control
 705		over the assembly references, use the appropriate functions described
 706		above. </p>
 707		<p class="Step">For example, consider the following alternatives for the statement clr.AddReference(&quot;System.Xml&quot;) above:</p>
 708		</li>
 709	</ol>
 710	<p class="TypedExample">clr.AddReferenceByName(&#39;System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&#39;)</p>
 711	<p class="Code-Background"></p>
 712	<p class="TypedExample">clr.AddReferenceByPartialName(&quot;System.Xml&quot;)</p>
 713	<p class="Code-Background"></p>
 714	<ol start="4">
 715		<li>
 716		<p class="Step">Load the XML file &quot;load.xml&quot; into the XmlDocument. The
 717		xml file contains sample savegame data from the IronPython sample &quot;Puzzle&quot; .
 718		For direct viewing, the load.xml file is located in the Tutorial folder</p>
 719		</li>
 720	</ol>
 721	<p class="TypedExample">d = XmlDocument()</p>
 722	<p class="Code-Background"></p>
 723	<p class="TypedExample">d.Load(&quot;load.xml&quot;)</p>
 724	<p class="Code-Background"></p>
 725	<ol start="5">
 726		<li>
 727		<p class="Step">We can now query the document. Query for all the saved games using the query below:</p>
 728		</li>
 729	</ol>
 730	<p class="TypedExample">n = d.SelectNodes(&quot;//Puzzle/SavedGames/Game/@caption&quot;)</p>
 731	<p class="TypedExample">for e in n: print e.Value</p>
 732	<p class="Stepnonumbering">&nbsp;</p>
 733	<p class="Stepnonumbering">The output in the console window will be:</p>
 734	<p class="Code-Highlighted">&gt;&gt;&gt; n = d.SelectNodes(&quot;//Puzzle/SavedGames/Game/@caption&quot;)<br />
 735	&gt;&gt;&gt; for e in n: print e.Value<br>...</p>
 736	<p class="Code-Background">
 737	Seattle (default game)<br />
 738	New York<br />
 739	World<br />
 740	North America<br />
 741	</p>
 742	<ol start="6">
 743		<li>
 744		<p class="Step">(Optional) Import the &quot;xmlutil.py&quot; module located in the
 745		Tutorial directory and use the function provided in the module to walk the
 746		contents of the Xml document:</p>
 747		</li>
 748	</ol>
 749	<p class="TypedExample">import xmlutil</p>
 750	<p class="TypedExample">for e in xmlutil.Walk(d): print e.Name, e.Value</p>
 751	<p class="HiddenOutput">#document None
 752#comment  *************************************************************************
 753 *
 754 * Copyright (c) Microsoft Corporation.&nbsp;
 755 *
 756 * This source code is subject to terms and conditions of the Microsoft Public License. A&nbsp;
 757 * copy of the license can be found in the License.html file at the root of this distribution. If&nbsp;
 758 * you cannot locate the  Microsoft Public License, please send an email to&nbsp;
 759 * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound&nbsp;
 760 * by the terms of the Microsoft Public License.
 761 *
 762 * You must not remove this notice, or any other, from this software.
 763 *
 764 *
 765 * ***************************************************************************&nbsp;
 766Puzzle None
 767SavedGames None
 768Game None
 769caption Seattle (default game)
 770type a
 771y 714
 772x 327
 773level 11
 774dimension 3
 775Game None
 776caption New York
 777type r
 778y 1538
 779x 1205
 780level 12
 781dimension 3
 782Game None
 783caption World
 784type h
 785y 0
 786x 0
 787level 2
 788dimension 4
 789Game None
 790caption North America
 791type a
 792x 2
 793y 5
 794level 4
 795dimension 3
 796TopLeftPreviewTile None
 797x -3
 798y -3
 799dimension 3
 800level 5
 801Cache None
 802allow true</p>
 803	<p class="Stepnonumbering">The Walk function is a generator (a Python function
 804	that contains a &quot;yield&quot; statement). As the Walk function executes, it returns
 805	(yields) the XML nodes one by one to the caller who iterates over the generator.
 806	The source for the Walk function is:</p>
 807	<p class="CodeSample">def Walk(xml):</br>
 808	&nbsp;&nbsp;&nbsp; yield xml</br><br>
 809	&nbsp;&nbsp;&nbsp; if hasattr(xml, &quot;Attributes&quot;):<br />
 810&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; attrs = xml.Attributes<br />
 811&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if attrs:<br />
 812&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for attr in attrs:</br>
 813	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 814	yield attr</br><br>
 815	&nbsp;&nbsp;&nbsp; for child in xml:<br />
 816&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for c in Walk(child):</br>
 817	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 818	yield c</p>
 819	<ol start="7">
 820		<li>
 821		<p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
 822		by Enter)</p>
 823		</li>
 824	</ol>
 825	<h3><a name="T1.3.2">Task 2: Mapack - Loading the .NET libraries - AddReferenceToFile</a></h3>
 826	<p class="Normal">This task requires the Mapack.dll library for linear algebra computations.&nbsp;
 827	The library is not part of the IronPython distribution. See <a href="#Mapack">prerequisites</a>
 828	for download details.</p>
 829	<ol>
 830		<li>
 831		<p class="Step">Start the IronPython console from the tutorial directory
 832		(see <a href="#Intro">Introduction</a> for details).</p>
 833		</li>
 834		<li>
 835		<p class="Step">Use the clr.AddReferenceToFile function to load the Matrix
 836		library &quot;Mapack.dll&quot;:</p>
 837		</li>
 838	</ol>
 839	<p class="TypedExample">import clr</p>
 840	<p class="Code-Background"></p>
 841	<p class="TypedExample">clr.AddReferenceToFile(&quot;Mapack.dll&quot;)</p>
 842	<p class="Code-Background"></p>
 843	<p class="TypedExample">from Mapack import *</p>
 844	<p class="Code-Background"></p>
 845	<p class="TypedExample">dir()</p>
 846	<p class="Stepnonumbering">The expected output will be:</p>
 847	<p class="Code-Highlighted">&gt;&gt;&gt; import clr<br />
 848	&gt;&gt;&gt; clr.AddReferenceToFile(&quot;Mapack.dll&quot;)<br />
 849	&gt;&gt;&gt; from Mapack import *<br />
 850	&gt;&gt;&gt; dir()</p>
 851	<p class="Code-Background">['CholeskyDecomposition', 'EigenvalueDecomposition', 'LuDecomposition', 'Matrix', 'QrDecomposition', 'SingularValueDecomposition', '__builtins__', '__doc__', '__name__', 'clr']</p>
 852	<ol start="3">
 853		<li>
 854		<p class="Step">Create instance of Matrix class:</p>
 855		</li>
 856	</ol>
 857	<p class="ExceptionExample">m = Matrix()</p>
 858	<p class="Code-Background"></p>
 859	<p class="Stepnonumbering">Oops, bad arguments for the constructor.&nbsp; In the next
 860	step you&#39;ll learn the way to discover the constructors available.</p>
 861	<p class="Code-Highlighted">Traceback (most recent call last):
 862		<br>
 863	  File , line unknown, in Initialize##30
 864		<br>
 865	TypeError: Matrix() takes at least 1 argument (0 given)</p>
 866	<ol start="4">
 867		<li>
 868		<p class="Step">Using the __doc__ attribute, find out information about
 869		Matrix constructors:</p>
 870		</li>
 871	</ol>
 872	<p class="TypedExample">print Matrix.__new__.__doc__</p>
 873	<p class="Code-Highlighted">&gt;&gt;&gt; print Matrix.__new__.__doc__</p>
 874	<p class="Code-Background">__new__(cls, int rows, int columns)<br />
 875	__new__(cls, int rows, int columns, float value)<br />
 876	__new__(cls, Array[Array[float]] value)
 877	</p>
 878	<ol start="5">
 879		<li>
 880		<p class="Step">Create instances of the Matrix class using the correct constructors
 881		and set some matrix elements manually.&nbsp; IronPython supports custom indexing
 882		on .NET classes. </p>
 883		</li>
 884	</ol>
 885	<p class="TypedExample">m = Matrix(2, 2, 1.2)</p>
 886	<p class="Code-Background"></p>
 887	<p class="TypedExample">n = Matrix(2,1)</p>
 888	<p class="Code-Background"></p>
 889	<p class="TypedExample">n[0,0] = 4</p>
 890	<p class="Code-Background"></p>
 891	<p class="TypedExample">print m</p>
 892	<p class="TypedExample">print n</p>
 893	<p class="Code-Highlighted">&gt;&gt;&gt; m = Matrix(2, 2, 1.2)<br />
 894	&gt;&gt;&gt; n = Matrix(2,1)<br />
 895	&gt;&gt;&gt; n[0,0] = 4<br />
 896	&gt;&gt;&gt; print m</p>
 897	<p class="Code-Background">1.2 0 <br />
 898	0 1.2&nbsp;
 899	</p>
 900	<p class="Code-Highlighted">&gt;&gt;&gt; print n</p>
 901	<p class="Code-Background">4 <br />
 902	0&nbsp;
 903	</p>
 904	<ol start="6">
 905		<li>
 906		<p class="Step">(Optional) IronPython also supports overloaded operators.&nbsp; Matrix does overload operators +, - (binary and unary) and *.&nbsp; You can see
 907		Python representation of the operators (__add__, __mul__, __sub__, ...)
 908		using dir():</p>
 909		</li>
 910	</ol>
 911	<p class="UserCode">dir(m)</p>
 912	<p class="HiddenCode">set1 = set(dir(m))
 913set2 = set(dir(object))
 914list(set1-set2)</p>
 915	<p class="HiddenOutput">
 916
 917        ['Submatrix','Symmetric','Clone','__sub__','Columns','Trace','__ne__','InfinityNorm','Rows','__setitem__','Multiply','__neg__','Diagonal','Random','Subtract','Item','Square','FrobeniusNorm','Solve','__rmul__','Negate','Add','Inverse','__radd__','__rsub__','__mul__','Determinant','__add__','__eq__','__getitem__','Norm1','Transpose']</p>
 918	<ol start="7">
 919		<li>
 920		<p class="Step">Make simple calculations with the matrices:</p>
 921		</li>
 922	</ol>
 923	<p class="TypedExample">m * n</p>
 924	<p class="TypedExample">n.Transpose() * m</p>
 925	<p class="TypedExample">m * 3</p>
 926	<p class="TypedExample">n + -n</p>
 927	<p class="Stepnonumbering">The expected output of this step is:</p>
 928	<p class="Code-Highlighted">&gt;&gt;&gt; m * n</p>
 929	<p class="LooseVerify">Mapack.Matrix</p>
 930	<p class="Code-Highlighted">&gt;&gt;&gt; n.Transpose() * m</p>
 931	<p class="LooseVerify">Mapack.Matrix</p>
 932	<p class="Code-Highlighted">&gt;&gt;&gt; m * 3</p>
 933	<p class="LooseVerify">Mapack.Matrix</p>
 934	<p class="Code-Highlighted">&gt;&gt;&gt; n + -n</p>
 935	<p class="LooseVerify">Mapack.Matrix</p>
 936	<p class="ExceptionOutput">TypeError: Matrix() takes at least 1 argument (0 given)</p>
 937	<ol start="8">
 938		<li>
 939		<p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
 940		by Enter)</p>
 941		</li>
 942	</ol>
 943	<h2><a name="T1.4">Exercise 4: Obtaining and Using Python Standard Library</a></h2>
 944	<p class="Body">In this exercise, you will obtain Python and point
 945	IronPython at the Python standard library. If you installed IronPython from the MSI installer, 
 946	the Python standard library is installed by default and you can skip this exercise.</p>
 947	<h3><a name="T1.4.1">Task 1: Configuring IronPython to use the Python standard library</a></h3>
 948	<ol>
 949		<li>
 950		<p class="Step">Download the latest Python installer from
 951		<a href="http://www.python.org/download/">http://www.python.org/download/</a>
 952		and install Python.&nbsp; The rest of this exercise will assume you used
 953		defaults (and installed to c:\python25, for example).</p>
 954		</li>
 955		<li>
 956		<p class="Step">Create a file named &quot;site.py&quot; and place it into your
 957		IronPython &quot;Lib&quot; directory.&nbsp; There might be one there
 958		already, so you can just edit it.&nbsp; The &quot;site.py&quot; file is executed every time
 959		you run IronPython.&nbsp; To tell IronPython where the Python standard library
 960		is, you can add the &quot;lib&quot; directory of Python to IronPython's path.&nbsp; To
 961		do so, put the following code into IronPython's &quot;site.py&quot; file (replace
 962		c:\python25\lib with your actual path to the Python lib directory):</p>
 963		</li>
 964	</ol>
 965	<p class="TypedExample">import sys</p>
 966    <p class="TypedExample">sys.path.append(r&quot;c:\python25\lib&quot;)</p>
 967	<ol start="3">
 968		<li>
 969		<p class="Step">Start the IronPython console from the tutorial directory
 970		(see <a href="#Intro">Introduction</a> for details).</p>
 971		</li>
 972		<li>
 973		<p class="Step">Now you can use the Python standard library from
 974		IronPython, for example to get the current working directory (output
 975		uses assumed location of your IronPython installation):</p>
 976		</li>
 977	</ol>
 978	<p class="TypedExample">import os</p>
 979	<p class="Code-Background"></p>
 980	<p class="TypedExample">os.getcwd()</p>
 981	<p class="Code-Highlighted">'C:\\ironpython\\Tutorial'</p>
 982	<p class="LooseVerify">
 983
 984	'%MERLIN_ROOT%\\Test\\IronPythonTutorial'</p>
 985	<p class="LabSummary">Tutorial Summary</p>
 986	<p class="Body">In this tutorial you performed the following exercises.</p>
 987	<ul>
 988		<li>
 989		<p class="Body"><a href="#T1.1">The IronPython interactive console</a></p>
 990		</li>
 991		<li>
 992		<p class="Body"><a href="#T1.2">Using the standard .NET libraries from IronPython</a></p>
 993		</li>
 994		<li>
 995		<p class="Body"><a href="#T1.3">Loading .NET libraries</a></p>
 996		</li>
 997		<li>
 998		<p class="Body"><a href="#T1.4">Obtaining and Using Python Standard
 999		Library</a></p>
1000		</li>
1001	</ul>
1002	<p class="Body">In this tutorial, you became acquainted with IronPython interactive
1003	console, including the dynamic exploratory way of development using the dir() function
1004	and __doc__ attribute to explore the en…

Large files files are truncated, but you can click here to view the full file