ASP.NET IronPython Resource

Learn python and .net

Beginning IronPython - Creating a class (Part 3)

In this tutorial we will be creating a sql table based class for a simple form. It will demonstrate how to create a class and reference it from a form.

The first step is to create a new file in the app_script directory. We will create the class definition there that can be used by any form in the site. Right-click on the app_script folder and select "New Item." Choose "Script Module" from the dialog box. Name the file "WorkOrder.py",  make sure the selected language is "IronPython", and click the "Add" button.

IronPython Dialog Box

It will create a new file which is unfortunately, pretty blank. Let's add some basic namespaces to the top of the file:

import clr
clr.AddReference('System.Data')
from System.Data import *
from System.Data.SqlClient import *
clr.AddReference('System.Configuration')
from System.Configuration import *

Next, let's create a basic skeleton class for the WorkOrder table.

class WorkOrder(object):
    "Provide database operations for the WorkOrder table"

    def __init__(self):
        pass

The first line declares the class name, WorkObject, and tells it to inherit from the object .net class (in parentheses). It isn't necessary to inherit from the object class, but it is good practice. Unlike c#, you can inherit from multiple classes, however that is beyond this tutorial. The second line is a comment about the class. You can create xml comments about the class/method which can be picked up by an code XML compiler to create documentation. This isn't the same as a code comment, which is prefixed by the # sign. The fourth line is similiar to a c# constructor. It will be called when an instance of the class is created.  It also has a parameter "self". It is the same as the "this" keyword in c#. When creating class methods, it is necessary to have the "self" keyword as the first parameter.

Next, let's write out the actual class.class.

class WorkOrder(object):
      "Provide database operations for the WorkOrder table"
      WorkOrderID = None
      ProductID = None
      OrderQty = None
      StockedQty = None
      ScrappedQty = None
      StartDate = None
      EndDate = None
      DueDate = None
      ScrapReasonID = None
      ModifiedDate = None
      __ConnectionString = ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString

      def __init__(self, workOrderID):
          "Get the database record with the specified workOrderId"

          # Open a new connection
          conn = SqlConnection(self.__ConnectionString)
          conn.Open()

          # Define sql statement
          sql = """SELECT WorkOrderID, ProductID, OrderQty, StockedQty, ScrappedQty, StartDate, EndDate, DueDate, ScrapReasonID, ModifiedDate
              FROM Production.WorkOrder
              WHERE WorkOrderID = @WorkOrderID"""

          # Add paramater   
          cmd = SqlCommand(sql, conn)
          cmd.Parameters.AddWithValue("@WorkOrderID", workOrderID)

          # Get record and populate object
          reader = cmd.ExecuteReader();
          if reader.Read():
              self.WorkOrderID = reader["WorkOrderID"]
              self.ProductID = reader["ProductID"]
              self.OrderQty = reader["OrderQty"]
              self.StockedQty = reader["StockedQty"]
              self.ScrappedQty = reader["ScrappedQty"]
              self.StartDate = reader["StartDate"]
              self.EndDate = reader["EndDate"]
              self.DueDate = reader["DueDate"]
              self.ScrapReasonID = reader["ScrapReasonID"]
              self.ModifiedDate = reader["ModifiedDate"]

          # Close the reader and connection   
          reader.Close()
          conn.Close()

'

Click here to see this class in c# for comparison. The constructor will accept the WorkOrderId and pull the corresponding record from the database. There are a few differences from C#. The first obvious one is there are no datatypes defined, making the code look a bit cleaner. In the variable declaration section, you will notice the "None" keyword. This is equivalent to the "null" keyword in C#. All variables in Python are reference variables and they need to be assigned on creation (unlike c#, where you can create a variable without assigning it.) Also, you will notice the variable __ConnectionString has two underscores prefixed to it. This is to designate it as a private variable. Unlike c#, "private" variables can still be accessing outside the class, although they are mangled to avoid outside access.

Another difference is the "self" keyword. The equivalent to the "this" keyword in c#. In Python, the "self" keyword is mandatory when using class variables. In c#, it is optional. Also, code comments are prefixed with a pound(#) sign, rather than a double slash(//) in C#.

Now, time to go back to the form and get the data from the class that was created. Update the code-behind with the following code:

import clr
clr.AddReference('System.Data')
clr.AddReference('System.Configuration')
clr.AddReference('System.Web')
from System.Data import *
from System.Configuration import *
from System.Web import *
from System.Web.Security import *
from System.Web.UI import *
from System.Web.UI.WebControls import *
from System.Web.UI.WebControls.WebParts import *
from System.Web.UI.HtmlControls import *
from WorkOrder import *

def Page_Load(sender, e):
    if not sender.IsPostBack:
         wo = WorkOrder(1)
         Response.Write(wo.StockedQty)

The first thing that needs to be done is to reference the code file. Unlike c#, files in the app_script folder aren't automatically referenced globally in all the forms. I've added from WorkOrder import * under the namespaces list at the top of the file to reference the class we created. Next, the following lines were added in the Page_Load section:

    wo = WorkOrder(1)
    Response.Write(wo.StockedQty)

The first line creates a new WorkOrder object and populates it with data for record 1. Remember, there is no "new" keyword when creating an object. The next line will output the StockedQuantity for the WorkOrder. In this case, it will be 8.

That's it for this tutorial. The next tutorial will go into something practical - creating and updating live data on a form. The code files can be downloaded below. Remember to change the connection string to point to an AdventureWorks database.

IronPython Tutorial3.zip (797.51 kb)
IronPython Tutorial3 (Csharp).zip (4.49 kb)

Posted: Aug 10 2008, 13:47 by Administrator | Comments (854) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: IronPython ASP.NET
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Comments