IronPython for the Visual Basic .NET Developer

In this detailed seminar, get aquainted with Dynamic Language Runtime and IronPython. Topics and Demos in this session include Syntax basics, IronPython and .Net and Data access.

Download

Video Transcript

Hello, I’m Nancy Strickland from IT Mentors. In this session, I’m going to be presenting an introduction to the syntax of IronPython for Visual Basic Developers.

This session will focus only on syntax. It’s just about the code. So we’re going to be working most of the time just from the command line, typing in commands and executing them live because that’s fast and easy. I will show you some script files and run them from the command line so that you see how that works but if you want to know about using IronPython with Silverlight, or in Visual Studio or other tools, then there’s another video called Fundamentals of a DLR which is part of this series and it covers those tools more but with less syntax. I’m going to assume that you already know how to obtain and install IronPython and how to enter and execute commands. If you don’t, the fundamentals of the DLR video also cover those things.

So we’ll start with the basics, variables, expressions, loops, conditionals, functions and then we’ll cover using object orientation and interoperating with .NET and finally, we’ll talk about how to access data external to the program and files or databases. Of course, I can’t cover all the syntax of a language in an hour so I’ll try to present some basics that will get you started and then at the end of this session, I’ll give you some references that you can use to get more information on your own. Again, this class is pretty much all demo. I’ll make comparisons to VB Syntax where IronPython differs from VB and I’ll give an example interacting with VB Code.

Syntax Basics

I’m going to start IronPython from the command line and at the prompt, which is these three right angle brackets; I’ll just enter the simple print HelloWorld command so that you can see how IronPython responds in interactive mode. You get immediate processing of the line just entered and you see its output, if there’s any. You can also see that like Visual Basic, IronPython has no symbol to terminate lines, logical lines terminate at the end of the physical line when you press enter so you can’t put two logical lines of code on the same physical line. Now, if I enter an expression like T+2 I’ll get the result of IronPython’s evaluation of the expression but you should know that this works only at the command line. If you created text file of Python commands and then you execute it as script, this won’t work. You’ll have to say Print T+2.

IronPython can also process complex expressions following the usual precedents rules. So, I’ll parenthesize 2+2 and multiply it by 3. This means most raised to a power so that’s a 3 squares so first we square 3, get 9 and then multiply it by 2 + 2 which is 4. IronPython again follows normal precedents, rules and uses parentheses to override them. You can also see that it uses the standard operators for addition and multiplication. It also uses the standard operators for subtraction and division and it can use the % sign for the mod operator you might call it the modulus or the remainder operator. If you use integers, of course, you’re doing integer arithmetic of the result of dividing 6 by 3 is 2 but the result of dividing 7 by 4 is only 1 because there’s no fractional part.

Now if you change and use floating points, so I’ll put 7.0 divided by 4.0, then I’ll get 1.75, I get a floating point answer. I’m going to use exponentiation again to create a really big number so that you can that L, the L suffix shows that the number is long. You can also mix integers and floats and if you do, you’re getting a float answer but if you want an integer answer, you can use the INT function here and that takes off the decimal part. If you want to go the other way around, we’ll divide 6.3 but we’ll change it to a float, and we get 2.0 instead of 2. Unlike the .NET type system, Python has four numeric types. It has INT, LONG, FLOAT and you can do complex number. So there’s also functions called LONG and COMPLEX.

Now, let’s look at how variables are used. Variables and IronPython are not declared, the don’t have a declared type. You create a new variable by simply assigning a value to it. At run time, the variable is typed based on the content it holds. This behavior is, of course, different from standard .NET syntax where all variables have to be types or the compiling won’t compile. Now VB6 provided a variant type that could also accept an e-data type, Visual Basic.NET doesn’t haven’t that type any more although it does the object type that can hold any type of object and of course, unless you use option strict, the VB.NET compiler doesn’t enforce strict data typing when data of one type is assigned to a variable of another type.

So, I can create a variable X by typing X=3 and then I can use it’s value and then in the very next line, I can change the type of x so that it now holds a flow or I can put a string in the same variable. This is handy but you can probably already see that it’s also potentially the source of hard to find bugs. If you accidentally reuse a variable name, a value can just vanish without warning. Notice that I use single quotes for the strings too. I could have used double quotes and you can nest double quotes within single or vice versa, if you need to. If I need to use an apostrophe inside a quoted string then the back slash is one of the ways you can do that, it’s an escape character and so that gives me an apostrophe. Now in VB.NET, there’s different ways to handle it, you can use the character function or double double quotes or control characters or regular expressions, maybe others. Another think you can do in Python is to put the single quote inside a double quote and that takes cares of it. Unlike VB, which uses control characters or perhaps the environment class, you can also in IronPython, back slash some characters to create special meanings so I could say print double quote Hello, new line, back slash in World and get “Hello World” on two different lines.

IronPython is case sensitive so if I type the command print x and use a capital P, the result is an error called a trace back, it shows errors. Here it say, unexpected token x but that’s actually caused, of course, because capital P, print wasn’t recognized as a key word. So, like in most languages, you sometimes have to do a little detective work to understand an error message. It’s called a trace back because not only does it shows errors but it will move back up the stack if that’s needed. In this case of course, we have to go back only one level. Now case sensitivity can cause funny errors like this. I’ve got X=3 and I’m going to try to increment x by 1, add 1 to it but when I print x, it’s still 3 because that was a capital X, not a small x, which might be hard to see the screen there and when I assign to it an new variable, capital X was created and the compiler didn’t warn me. Now this only happens, by the way, if you use a capital X for the first time on the left hand side of the assignment cause that’s what creates that new variable. If, instead, I said X=Y+1 and remember that we haven’t used Y before so it’s never been declared and I get an error that basically says that the name Y is not defined.

So, in a sense, variables do have to be declared in IronPython. It’s just that they’re declared by using them as an L value on the left side of an assignment an L value and they aren’t given a type until run time. IronPython is also white space sensitive. If I type several spaces and then type my X=3, I get an error and it says invalid syntax. We’ll see later why that is because white spaces are indentation white spaces have a special meaning in IronPython but IronPython does allow blank lines within a program, within a script. One more thing to do a comment, you start with the pound sign so if I say X=3 and I need a comment I put the pound sign and say this is a comment and now it’s commented out from their until the end of the line.

Now I’m going to exit, I’ll use Control-Z, which is the end of file character. When I hit Return, I’m back to a regular command prompt. Conditionals are multi-lines statements so IronPython has a special syntax to show that. Unlike Visual Basic, IronPython doesn’t use End to show the end of a multi-line statement. Instead, the first line of the block begins at the left margin like normal code lines and in the lines that belong to block are indented to the right. The exact number of spaces doesn’t matter but the indentation level has to be the same for each line that belongs in the same block. So, let’s look at a conditional. I’ll set N equal to 14 and then I’ll say if N is greater than or equal to 10, unlike VB, you don’t need a then after the built in conditional but notice that you have to have a colon, that colon at the end of the if line is what says this is the start of a multiline statement. So, when I press enter, the prompt changes to an ellipsis is to 3 dots to show that now I’m inside a multi line statement. Whatever I do in here has to be indented so I’ll indent a little and print high and now I want an L IF but the syntax is ELIF and I can have another condition there and I’ll have to have a colon after IF also and then whatever I want to do in that case. I keep pressing enter. I’m still inside my loops, so I still have an ellipsis.

Now the comparison operators, like you see here, less than or great than or equal to, they’re mostly the same as in VB except, instead of a single equals sign for equivalence it uses two, equals equals so I’d say ELIF N = = zero. If N is equal to zero and I still have to have a colon there because it’s still a multi -line statement and then oh, I’ll print zero, I’ll print something here and then I’ll give one more ELIF N, of course, this is the same as the final L. Now I go down one more blank line. I’m finished with the whole IF construct so I have to tell IronPython that I’m finished with the block so I’ll just press enter. It knows that I’m finished now with my IF and I’m not going to do any more indenting or anymore IFs and so it runs and tells me ‘Hi’.

One block can be listed inside another and if so, then nested block has to be indented more than the outer block and one more thing, unlike Visual Basic, there is not select case statement in IronPython. They syntax of an IronPython loop looks something like a four each loop. Here’s my colon that I always need to have if it’s a multi line statement. Now, where it says range 3, that’s a function and it’s a function that generates a list that’s an arithmetic progression starting at zero and ending at the number one less than the argument to the function. It creates a zero based list that has the number of elements specified by the argument, zero, 1, 2. X takes on each of these values one by one so it starts at zero and ends at 2 and now, I’ll just have it print X and you can see after I press enter here that the value of X runs from zero to 2 and also notice how like for each four loop you don’t have to do any incrementing of X within the loop that’s all automatic. Now if you want to nest loops, you can do that, you’ll use extra indentation for the inner loop so I’ll say for X in range 4, indenting for Y in range 3 and another colon. I’ll print out Y plus X times 3 and I’m putting a comma here because that will suppress the new line so these three values will be printed on the same line.

Then this next line I want to have be part of the outer loop, not the inner loop so I indent it to that level. This, without an argument, will print a new line only so I’ll get a blank line and there’s my output. Now, IronPython also has a wild loop, it looks like this. I’ll start X equal to zero because inside my loop, I can say, while X is less than 4, and X here is not an L value, it’s not being assigned to. So, if I have not previously assigned to X, this would cause an error because IronPython wouldn’t known how to understand X. Now, I’m going to write the body of the loop, I’ll indent, print X and then in a wild loop, of course, I do have to do an incrementation so I’ll say X equals X plus 1 and then I execute it and I get my output.

You can also use break and continue statements in loops so let’s do one of those per X in range. We’ll start out trying to count to 10 but we’ll say, if X is equal to, that’s equal equals, right? If X equal equal 3, so if X is 3, will continue. So, when it’ll print 0, 1, 2 but when X becomes 3, continue says just go on to the next iteration of the loop and skip any steps below this point or one of the steps below this point is where we’re going to print X. So X won’t be printed for 3. So we’ll say if X is 7, again a colon, cause we’ve got a conditional here, then we’ll do a break and break breaks us out of this loop entirely so 7, 8 and 9 won’t be printed because here’s the print statement and since the print statement is below the break and below the continue, when either the continue or the break is executed if those conditional are true, then X doesn’t get printed.

So, you’ll see we printed 0, 1, 2, skipped 3, that’s what continue does but continue does go on to the next iteration so then 4, 5, 6 but starting with 7, nothing else gets printed cause we’ve broken completely out of the loop. So you can see break here is the equivalent of exit in Visual Basic. We said before that range is a function that generates a list, an arithmetic progression starting from zero and ending at the number that’s 1 less than the argument to the function. Notice how the output here is comma separated and in square brackets. That shows that this object, this type is an IronPython list type, similar to an array list in .NET. You can change the start point and the step value by calling the function like this. We’ll start at 2, go to 10, bystepping by 2. So we have 2, 4, 6, 8, 10. I can use this format then to create a Python List data type that holds a zero index collection of any thing, of items.

Now I’ve got my list called Test and I’m going to use my 4 loop. I’ll make it for L in range and so this will do my for each loop and I’m going to go to the link, here’s a new function, LEN, that gets me the length of that list named Text, there’s my colon that I have to have. I’ll print it out from Test Element Number L and there we go and I should have used a comma after that Print Test so that I could have gotten it all on the same line. That’s okay. I’ll have another chance. You can see that you place an integer index inside your square brackets in order to access the specific value within that list which is the same as using parentheses around an index in VB.NET. Now actually, since this is a four each loop, I did it the hard way, just so I could show you how indexes work. This would be a better and easier way for L in Test print L here, I’ll remember to do my comma. There we go. A list holds objects so it can hold anything, for example, this creates an empty list that could store strings, integers, floats, other objects. Now L has now been typed as a list and therefore, I can use list methods with it, for example, I can say append and I can put a 4 into my list. I can say append again and this time, I’ll put a string into it and if I want to see what’s in it, I can just print L and it knows how to print itself. There’s the 4 and the 4.

You can define functions in IronPython and I’m not talking about object methods now. I’m talking about standalone functions that extend IronPython. Here’s a simple one. We’ll define a function called add one and send it an argument. There’s my colon showing that this is multi lines so now I indent and my return from this function is going to be one more than the number that was sent to it. When I press enter, nothing happens but that function has now been defined, that’s what the def means, define the function and so I can use it. Now to use it, I’m going to say, add one and send it a number and it will return the number that’s one greater than that. There’s only one line here but there could have been many, the last line here returned to value but in Iron Ruby, functions don’t even have to return a value, they could just do something like print something. So unlike Visual Basic, there’s no distinction between procedures and functions. Both kinds of operations are called functions and so functions can either return a value or not. If you need multiple parameters, you just comma separate them, both in the definition and when you call your function.

IronPython also includes lamda functions. These are short in line functions that don’t have a name, they’re assigned to a variable and in that variable is used like a function so for example, I can say G equals lamda, showing that is a lamda function coming up. This X is the argument to the lamda function. You see it’s not in parenthesis and then after the colon is the return values. So, it’s going to return X times 2. So, it’s a sort of a short hand way to declare a function. You don’t have to have the def, you don’t have to have the return keyword, takes one parameter called X, no parenthesis and return a value. The function has no name either but because it’s been assigned to G, I can now use G like a function so I could send it 6 and the return value would be 12. Strings in IronPython are arrays of characters and they can be either single or double quoted. They’re zero based, like in other .NET languages so X equals hello, which assigns the string hello to X and then if I print X sub zero, I get the H. You can also use an index against a literal string so I can say hello, sub zero and get same H.

Now a variation on this is what’s called slice notation. I’m going to take 2 indexes and I’m going to separate them by a colon to take a slice out of my string. So, if I say 2 to 2 4, what that will is select 2 and 3, starting at 2 and up till 4, all the things in between those which is actually only 2 of them so I will get the third and fourth characters. There we go. I’ll get the third and fourth characters need to be square brackets, not mixed. Strings in Python are immutable so if I try to do this, if I try to assign the character capital H to the first character that hello, then it gives me an error and it says, string object has no attribute, set item. It’s immutable. It can’t be changed but I could do this. I’m going to say that X equals capital H and add to that the slice of H that starts at the second character which is 1 and runs till the end. I’m not even going to put a second index there and I’ll run to the end and now, if I print X, I’ve got my capital H, Hello, because a plus sign can concatenates the capital H with a slice of hello that starts at index 1 and runs forever till the end of it.

By the way, there’s no separate character type. A character is a string of link to 1 so I could have used either single or double quotes around that capital H. Now the function STR will take this number 14 and convert it into the string 14. It’s the reverse of the ENT and FLOAT functions we saw earlier that can convert between numbers or convert strings to numbers. Now I know that strings can be concatenated, with the plus, we just saw what you can also take a string and apply the multiplier operator to it. Now if we had not converted X to a string, and I tried to figure out the value of X times 3, I get 42, right? 3 times 14 but X has been converted to a string so I get 141414, it just duplicates and can concatenate all those duplications of the string when you apply the multiplication operator to a string.

There’s also a compare function that’s often used with strings, I’ll give it two strings and it will return a negative number if the first is less than the second, zero if they’re equal and positive number if the first is greater than the second. So, it’s sort of like the COMPARE or COMPARE TO functions in .NET.

There’re also all the standard functions that you would expect for string manipulation, you can change case, you can find a substring, format, justify, all kinds of things. I won’t mention them all, you can check the documentation for whatever function you need, but I will give you a couple of quick examples. I’ll give you a conditional here. If X is digit, that will change to see if every character in a string X is actually a digit so that it could be a number, right and if it is, I’ll print yes. Well, we happen to know that X has 141414 in it, so this returns true, it is digit returns true. Notice here that this is a new way of writing an IF statement, a little more condensed, you don’t have to do the indentation but of course, it works only if there’s a single statement to be executed in the condition and then you just put it all on a single line.

Here’s another example, the upper function converts to all uppercase. Let me quickly warn you about one more thing about strings. Python supports both Unicode Strings and your standard 8-bit strings but the names of methods that do the very same thing might be different, depending on whether they’re being applied to a Unicode string or an 8-bit string.

In Python all objects; numbers, strings, lists, instances of classes, any object, can be tested for its truth values so they can be treated like booleans and conditions. Most objects have a default value of True only if few are false including false, this is not the string false but the keyword false, with a capital F, there’s also a keyword True, with a capital T. None, that’s also a keyword, not a string. It’s similar to nothing in VB. In Python, for example, functions that don’t explicitly return a value return none. A zero of any numeric type, integers long, floats, complex, that’s also considered false. Empty sequences are false. Now a sequence is a category of collection, a list is a sequence type and so if you have an empty sequence, that’s false, if there’s anything at all. I’m sorry, if you have empty list, that’s false, if there’s anything in it at all, then it’s true and there’s a few other special cases we won’t talk about. Everything else is considered true so most objects are always true.

You can also use logical operators; and, or and not, all lower case with booleans. So, I’m going to assign X the value of True, capital T, True and Y the value of False. Again, these are keywords, not strings and I’ll say if X and Y, there’s my colon, then print yes, they’re both true, otherwise there’s my Else and my colon. I’ll print no, and of course it’s going to print NO because they’re not both true. Now these operators, the And operator and the Or operator, they use short circuit logic. So, if they’re two conditions joined by Or or And, then the second condition won’t be checked unless it needs to be. So, in other words, and always behaves like And Also in Visual Basic and or always behaves like Or Else in Visual Basic.

Now, I’m going to define a function called ‘SAY YES’ and all it’s going to do is print YES. Now I’ve got that function defined. I didn’t get an error message when I pressed enter on the ellipsis line so we know that worked and then I’m going to say, IF NOT Y OR ‘SAY YES’ PRINT TRUE. Now here Y was declared to be false so when I put the NOT in front of it, it becomes TRUE. Now OR requires that only one of the conditions be TRUE so IronPython isn’t going to bother to look at that second condition. The whole thing is already true if Y alone is true so the function ‘SAY YES’ is never going to be executed and YES won’t be printed but TRUE will be printed because one of the conditions was true.

But now, if I change this to IF Y, take out the NOT, IF Y or ‘SAY YES,’ then I’m going to print TRUE, then it is going to print YES and the reason is because Y was not TRUE so it has to go check the second half of the OR and it was going to execute ‘SAY YES’ which will print the YES, right, to check it’s return value but the return value form ‘SAY YES’ is NONE because the ‘SAY YES’ function that we defined didn’t have any return value and remember, when there is no return value, then NONE is returned. Well, NONE is false so Y is false and ‘SAY YES’ is false. So even though it’s already printed the YES, it’s not going to print the TRUE. There’s the YES and not the TRUE.

Syntax Basics Demo

So, here’s a little short bit of a program that shows many of the basics we just talked about along with a few new things. You can see that I wrote this in Notepad and gave it the extension py. It’s a called demo 1.py and I’ve saved it in the directory that I’m going run it from. Now what it does, first it defines a function called ASK, here it is. It’s got three comma separated arguments, got the colon after it. The first prompt looks normal but the next two have something we haven’t seen before, the last two have default values. So, the user who uses ASK is going to have to pass in something first to fill that variable prompt or that parameter prompt, but they can leave retries and remainder vacant, that is they only have to send one argument to it and if they do retries will be three and reminder will be enter YES or NO. If they put a second argument in their call, then it will replace retries. Then I’ve got while true, and that’s an endless loop so inside there will have some returns that break us out of that loop.

The next line, ans equals raw_input (prompt), is another new function we haven’t seen before. It gets input from the user. You don’t have to supply a parameter to it but if you do, then that parameter whatever it is, will be printed out to the user as a prompt for their input. So whatever the person who calls this method puts in it for a prompt, is what will be prompted before this raw input is executed. Then whatever the user types in is a sign to ans, and we’re going to make it lower case with the ans lower function, you know, just like the upper that we saw earlier. And then we’re going to use something else new, if – this is a different kind of conditional, IF THIS VARIABLE IS ans and here’s a list so if whatever value is in ans, made lower case, is either Y or YES, then we’ll return TRUE from the whole function and we’ll break out of that true loop, that Y loop. Same thing with NO, except that it’ll return FALSE. But if the user does not type in Y, N, YES or NO, doesn’t give an acceptable answer, then we’re going to decrement the value and in retries, they get three retries normally but now they’re one down. If it falls below zero, they’ve used up all their tries, then we’ll return false, that’s just the default. If they can’t get it right, then the answer’s going to be false. But if they’re not below zero yet, then we’ll print out the reminder. We’ll print ENTER YES or NO and give them a couple more chances.

Now that’s the end of that definition because it’s the end of the indenting and that’s what shows a code block in IronPython. So, now we’re going to use it in the script. The next thing we’re going to do is we’re going to say IF and then here we’re calling our function and the return value TRUE or FALSE is a boolean, so it works in the IF. So, we’re sending it a prompt and two which means this person is only going to get two retries but we didn’t send it a reminder so the reminder will still be yes or no. so if they say YES, the return value is TRUE, print CONTINUING, otherwise print STOPPING. Okay now, let’s try it out.

Now to use it, I’m going to have to work from the regular DOS prompt, not from inside IPY. Because what I do is I start out by typing IPY to start the Python engine but then I give it something to run against mydemo1.py and you do have to put the extension there. And it asks me do I want to continue, let’s suppose I can’t manage to get it right, and it says enter YES or NO, so we know that’s working. I’m going to say YES and it tells me CONTINUING and if I had entered NO, of course it would told me STOPPING.

Object Orientation

Now, let’s talk about object orientation. IronPython is a fully object oriented language with both built in classes, imported classes and classes you write yourself. IronPython comes with its own built in modules and you can use the functionality of these modules by importing them into your code so for example, to use the IronPython SYS module, you say IMPORT SYS. This is similar to IMPORTS and VB. One important difference though is that when you use IMPORTS in VB, you bring those names from the imported name spacing that the global name space so you can just use their names. But in IronPython you must both use the import statement and then also prefix the name of the classes you’re using with their name space so, for example, I can’t just type Version, I’ve still got to type the SYS in front of it, even though I imported the SYS. But if I use this Runsys, Import * now I can just use the plain old version.

I can also use the dear function and pass it, this name space SYS and it will give me information about some of the other functions in the SYS name space. One that you’re going to be using as SYS.PATH. I’ll just print out what the path is. You can see that the default path includes the current working directory and the lib, the library folder for IronPython.

What makes IronPython special, of course, and different from regular Python is the fact that it can import name spaces from the .NET libraries and use them in the same way that it uses its own native libraries. So, you can say import system and then see what’s in it or you can use it. I’ll print system environment OS version. With import, you can access any of the constant or classes of a named space also so suppose you want to use the pie constant, I can say from system map, Import * and then we’ll print PI. There it is.

If you want to use a hash table, you could import it and use it exactly the way you would expect to use it, same methods and now I can say, H=hash table and I’ve instantiated a hash table. Notice that I don’t have to use the key word New to do that. Now, I can begin to use my hash table. Let’s put a few things in it; put a key value here, a key value pair and now I can, I’ve put things in it and I can manipulate it. So I can use the For Each Loop, print the key, print a colon and print the value and there it is.

Here’s an example of how easy dynamic languages are. I just say ENH and E knows that it should be a dictionary entry type with key and value properties. Now I had not previously defined E and it doesn’t look here like it’s an L value but it really is because on each iteration through this loop, E is being assigned something that the next value, the next key value pair out of H. I should mention here that IronPython also has its own version of a hash table, it calls it the dictionary and like a dynamic language, should be it’s really easy to set up and use. So, I’ll start out by saying MyDict equals – oops, needs curly’s here – so there’s my key first and my value comma, separated, another key value pair and I’ll just put one more in and a curly to close it. oops – I see I forgot one of my quotes, I’ll just go back and put it in and I should be okay. And now, I can ask for the value associated with Key 17.

Not all .NET name spaces can just be imported directly, the way we just imported system and collections. But other .NET libraries can be explicitly referenced to import them, you first have to import the built in name space call CLR, Import CLR. That indicates that I intend to use .NET Interoperability. Then CLR has a method called ADD REFERENCE and in that method I can tell it other name space, like in this case, SYSTEM XML that I want to import.

Now, from SYSTEM XML, I’ll import all the classes, so I can have all the functionality and what I’ll do here is, I’m going to instantiate an XML document. Again, I don’t need the keyword but I do need the parenthesis there. Now, I’m going to load up a simple little XML file and let me show you what that file is, just a simple little XML file of names. So I’m going to use – I’m sorry, I didn’t see that error – let me try again – Yeah, okay, now it’s got it loaded. So, now I’m going to use the SELECT NODES method to load up all these nodes here. The node’s called NAME. Looks like they’re in there so I’m going to use the Last Child enter text Inner Text properties. So, I’m going to say for E and N, I’m going to print e.LastChild.InnerText property for each node and there it is. The names came out.

Besides Interoperating with classes in the .NET framework, IronPython can interact with classes that you write yourself in .NET languages, for example, I’ve written a class that looks like this, very simple little class called Simple Class, got one method, ‘Say Hello,’ that returns ‘Hello.’ Then I’ve written a Python program that can use that class. I’ve already compiled the class to a DLL so that I can say import CLR, CLR add reference and here’s my simple class library DLL which is the compiled version of what I just showed you. Then from that I am going to Import * but I could just import Simple Class, that’s the only thing in it, anyway. Then, I’ll instantiate Simple Class to a variable and using that variable call the Say Hello method. So; I’m going to run that from the command line, got to have that extension .py and it prints ‘Hello’ so that we know that it worked.

You can also write your own classes in IronPython. Here’s a simple example. I’ve written it as a script, class, my class, this is the class definition and it’s multi line so we have a parentheses, a colon and everything else is indented. Here, I’ve set myval equal to 3 and this method called underscore underscore init, underscore underscore (_ _init_ _ ) is the constructor, double underscores are used for special methods like this. The first argument the constructor into all methods has to be a reference to the current instance. Now you often see self used for that, like here, but you can call it whatever you like, so if you want to call it Me, no problem. And then we have get and set methods and both of which again, have self, you could call it me as their first argument and use self internally as well and then the SET VAL because it needs to have something passed in, has both self and the passed in value as part of it’s arguments there.

Now, the code for this class could be included in another Python Script that was going to use it. It doesn’t have to be in a separate file but I certainly can be so it’s accessible to lots of scripts. If it is placed in a separate file, Python has to be able to find it, so either put the class file into your IronPython lib directory or, add the directory that it’s in to your path with SysPathAppend which we saw earlier, and then you can use it like this. I’m going to start out by importing Sys and then I’ll use SysPathAppend to add the directory where I’ve got it to my current path. And now, from my class, Import my class means from the file name, without the extensions so the file name for this class is myclass.py. From that file I’m going to import the class, myclass so that file, the .py file could have lots of classes in it and I could say import* to import them all or I could import a particular one . So I’m showing you how to just do a import only a specific one. Now, I’m going to instantiate that myclass class and it printed CONSTRUCTING NEW, only because we put that in the constructor to tell you that it was happening. They were going to do a setVal and set some value into it and then we’ll do a getVal, so you can see that it worked

And now I want to show you another example, here’s another script and in this script, we’re going to use winform so we have imported the CLR and addreference to winforms and then we’re importing everything. Now this class MyForm, the from in parenthesis here means that myform inherits from form. Here’s our constructor again as we’ve seen before, got self as an argument calls the constructor of its parent and then here, it’s taking the Click Event of Self, that is the click event when you click on the form itself, not a button but the form itself and we’re adding a handler to it with plus equals to add an extra handler to whatever handlers may or may not already exist for it. Then here’s the actual implementation of the click handler method, it always takes, of course, an argument.

The first argument is always a reference to the current object that is the self and then it takes the sender and event args are givens that you’re familiar with. So, in that, we’re first going to instantiate a label and in our constructor, we’ll go ahead and set the text for that label to be ‘hello.’ And then we’re going to take these event args here which behave the same way that they do in .NET and we’re going to find the location when that click happened. Where was the mouse at the time? We’ll assign the labels location to that, so when we click somewhere on the form that label hello will be placed in that place. And then, we’ll just add that label to the controls array for the form. Then down here, just to show you a message box, we’re going to get the type of the form. Find out what run time type that form is, assign it to T and print that out in the message box. The last thing we’ll do, now that’s the end, of course, of this class, right? That has to be there, sorry. That’s the end of the class cause their indentation has stopped so here is the form being instantiated, my form is being instantiated, we’re assigning it to F and then we’re calling the application Run Method there to run that form. Make sure I’ve got those changes there and now I’m ready to run it. I’ll just go to a command prompt. IPY and it’s called MyWinFormsClass.PY and when it pops up, there it is. Now, when I click with the mouse, a label called ‘hello’ is placed where ever my mouse was and a message box pops up telling us that the type of this is IronPython new types system windows forms, Form 1 and I can do that however many times I want.

IronPython and .NET Demo

So here’s a demo of IronPython inner operating with .NET. Here’s my script, you’re probably familiar with the Twitter website that let’s you send and receive little messages, you may also be familiar with the Twitter timeline that can show you message that have been sent recently, generally. This demo shows using Inter-Op capabilities to download the time line in XML and then use the Microsoft Speech Synthesizer to read it out loud.

We’ll use the system, speech and XML names spaces. I’m importing the speech synthesizer or web client and some XML classes. Here I’m going to instantiate the web client and then use it’s download string method to pick up this XML file, you actually go to this website and see it yourself, if you’d like. It’s obviously publicly available. Then I’m going to instantiate an XML document and a speech synthesizer. Now, I’m going to take my document and load up the XML from that content, then I’m going to select just the statuses nodes and then for each status there, I’m going to create some new XML in the format that the speech synthesizer expects to see it and basically what I’m doing is taking the inner text out of each node and that’s the speech synthesizer is going to speak to us and then, I’ll tell it to speak. And now, I’m ready to run it, close this.

Speech Synthesizer

I spoke way too soon, it’s been snowing all day with more to come according to the forecasters, @Crystal Nicole: lol you’re right …Houston highways are like Fear Factor . @Mike Willis: It’s slowed down here but it will be back

Now, I’m going to hit CTRL-C to stop it, what you’re hearing is some other recent posted Twitter had to say. The contents kind of dumb but it’s an interesting demo. So this little short demo showed us how to use, how to Inter-Op with web sites and with XML and the speech synthesizer.

And I have one more very short little demo to show importing, not from the .NET framework but Python, not IronPython, Python. I’m using version 2.5 and I’m going to take advantage of a handy little function it has that grabs a web page and saves to a local file. So I’m going into IronPython and I’ll import sys and then I’ll append to the path the directory where I have IronPython. So that I can get the Python libraries and then, from the URL library, I’m going to import URL retrieve. This is a little function that will take a web site URLRETRIEVE based on a web URL and I’ll just use MSN and it will import into whatever file I tell it to. I’m going to put it into Temp.htm and I’ll let it put it right on the desktop, sort of the default location there. And now it should have done it so let’s look at the desktop. I’ll pull it up, here’s my temp file right here, let’s open it. If I make it big enough to see, you can see that, that was recorded, that it was captured today, Sunday, December 14, the day I’m making this recording. There it is.

Data

Now, we’ll talk about accessing data external to the program and to the files and databases. This kind of programming always needs exception handling so we’ll cover that too. Working with files is just cookbook, the simplest way to work with files is just to import the file manipulation classes from .NET and use them like this. I’ll import Sys and then from System file, I’ll import everything and then I can instantiate a stream reader and I’ll open a file called test.txt. Let me show you what’s in that file, just ‘Hello World’. Two lines. Now, I’ll read from it, there is the ‘Hello’ and I’ll close it. Now, of course if I want to read the whole thing, I’ll need to create a loop there and I can do that. I don’t need to import the Sys again. I don’t even need to do my imports but I will reopen my file here, then I’ll set up a variable to hold, oops – let’s fix that, there we go – then, I’ll set up a variable L to hold each line as I read it in. And then I’ll set up a while loop to read them in, While L is not equal to none, remember that none is the equivalent of nothing so, while there’s something that’s been read in, I’ll read and I’ll print and then, when I’m finished, going back here to the margin again, I’ll close it.

Exception handling is pretty much what you’d expect just with slightly different labels. I’m going to show you this script and basically, it breaks the app by changing the name of the test file to one that doesn’t exist and then here’s a try catch to handle it, it’s try and accept the catch then, accept is the same as catch and then at the end here, I’ll check to make sure if SR is still none, that is it if my stream reader did not get instantiated, I’ll close it. So now, I’ll just run that and we should see that there was a problem with the file which is true.

Accessing a database is pretty much cookbook straightforward. You’re going to import the appropriate classes and whatever you need so we’ll have the data and the SQL client. Then, in our class here, we’re defining a method called get data. Def get self has to be passed to every method. We’ll set up a SQL query, select * from customers. We’ll set up a connection string, of course, your will be different, depending on where you’re connecting. Then we’ll instantiate a SQL data adapter, passing it our SQL string and our connections string and then, we will instantiate the data set and use our data adapter to fill the data set with data. Then I’m going to iterate through. I’m going to take the data set, take the zero, the first table, actually there’s only one table in it, take the rows collection from that table and just use a little for each loop, a for i in loop and then i, of course, will be a row and we’ll print out the zero, the first column from that row. Now that’s the end of the test cause we’re not indented anymore so I’m instantiating that class to C and then I’m calling the get data method of that class. Let’s run it.

It’s connecting to the database and then, in a minute, it’s going to print out for me, that first column. There it is and if you’ve worked with Northwind before that, probably look familiar to you. Of course, if you’re doing DMN manipulation language, instead of simple query, then you’ll just use the commands appropriate for that. Again, it’s the same as the standard .NET languages logically and you use the same objects and the same methods, you just change the syntax a little for the IronPython part of it.

Data Demo

In this demo, I’m going to demonstrate this Windows database application. You can see that I started out by setting appropriate references and importing things that I need. Then I create a form and this form, called TestDB inherits from Windows Form, the father, the parent class. Then here in my constructor, I’m going to do most of the work. I will set a text for the form itself. I will instantiate a button. I’m doing this mostly just so you can see how to work with the button. I set its text to say ‘click here,’ give it a location and give it a click handler, myButton click += and then here’s the myButton down here, the handler method. All it’s going to do is pop up a message box and say ‘just to see how to set up a button.’ And what’s being passed to that is self because, of course, that always has to be the current instance, always has to be the first argument and then the sender and the event arcs. Then, I add that button to the set of controls, to the collection of controls on the form, then I’m also going to instantiate a data grid view and I’m going to give it a location and a size and add it to the collection of controls.

Now, I’m doing the basic database work. I’m setting up a SQL query as a string. I’m setting up the connection string to connect to my particular instance of Northwind. I’m instantiating a SQL data adaptor and sending it the SQL and the connection string. And then I instantiate the data set and use the data adaptor to fill that data set, standard .NET stuff. Then with my data grid view, I’m going to set its data source to be table zero of the tables collection, table zero which is the first and only table that would have been returned from the query into that data set. So, we’ll be able to see what’s there. Now, the only thing slightly different here is that instead of instantiating TestDB to a variable and then saying application run that variable, I’ve just consolidated here. I’m instantiating it and sending to application run in a single line of code. So, I think we’re ready to run that now. And there it is, here’s my data group full of data and if I click here, I get my button just to see how to set up a button.

So that’s the end of this brief introduction to the syntax of IronPython with specific reference to how it’s similar to or different from VB. For more information, here are some links to sites that include the home sites for the Dynamic Language Runtime and IronPython, these sites contain links that will lead you to other useful sites, including tutorials, examples and blogs. I also recommend that you search the web for more help because IronPython is a new language and so right now, lots of new material is being written about it. I also want to remind you that there’s more information on IronPython and the fundamentals of the DLR Video which should be available from the same source where you got this video. It isn’t really a lower level session than this one, they’re in the same series. It’s just that it’s less syntax oriented and so it covers a wider range of topics that you’re going to want to know about. Thanks for watching today. Bye, bye.

[End of Audio]